Video-Text-to-Text
Safetensors
custom_code
ynhe commited on
Commit
75c67a3
1 Parent(s): d1c86bc
config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/petrelfs/wangchenting/multimodalllm/logs/scripts/pt/1b_qformer_internlm2.5_7b/stage2_8f.sh_20240807_005800/checkpoint-last",
3
+ "model_cls": "InternVideo2_VideoChat2",
4
+ "architectures": [
5
+ "InternVideo2_VideoChat2"
6
+ ],
7
+ "attn_implementation": "eager",
8
+ "auto_map": {
9
+ "AutoConfig": "model_config.VideoChat2Config",
10
+ "AutoModel": "modeling_videochat2.InternVideo2_VideoChat2"
11
+ },
12
+ "model_config": {
13
+ "bridge": {
14
+ "extra_num_query_token": 64,
15
+ "name": "qformer",
16
+ "num_query_token": 32,
17
+ "qformer_attention_probs_dropout_prob": 0.1,
18
+ "qformer_drop_path_rate": 0.2,
19
+ "qformer_hidden_dropout_prob": 0.1
20
+ },
21
+ "freeze_bridge": false,
22
+ "freeze_llm": false,
23
+ "freeze_vision_encoder": false,
24
+ "llm": {
25
+ "lora_alpha": 32,
26
+ "lora_dropout": 0.1,
27
+ "lora_r": 16,
28
+ "name": "internlm2_5_7b",
29
+ "pretrained_llm_path": "internlm/internlm2_5-7b-chat-1m",
30
+ "use_lora": true
31
+ },
32
+ "loss": {
33
+ "use_vision_regression_loss": false
34
+ },
35
+ "pretrained_paths": {},
36
+ "use_flash_attention": true,
37
+ "vision_encoder": {
38
+ "checkpoint_num": 48,
39
+ "d_model": 1408,
40
+ "encoder_embed_dim": 1408,
41
+ "img_size": 224,
42
+ "name": "internvideo2-1B",
43
+ "num_frames": 8,
44
+ "origin_num_frames": 4,
45
+ "patch_size": 14,
46
+ "pretrained": null,
47
+ "sep_image_video_pos_embed": true,
48
+ "tubelet_size": 1,
49
+ "use_checkpoint": true,
50
+ "vit_add_ln": true,
51
+ "x_vis_only": true,
52
+ "x_vis_return_idx": -2
53
+ }
54
+ },
55
+ "torch_dtype": "float32",
56
+ "transformers_version": "4.38.0",
57
+ "use_cache": true
58
+ }
configuration_internlm2.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ InternLM2 model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
28
+ class InternLM2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
31
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`InternLM2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 11008):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer decoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer decoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
61
+ The maximum sequence length that this model might ever be used with. InternLM2 supports up to 32768 tokens.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)
78
+ to understand more about it. This value is necessary to ensure exact reproducibility
79
+ of the pretraining results. Please refer to [this
80
+ issue](https://github.com/pytorch/pytorch/issues/76232).
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`Dict`, *optional*):
86
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
87
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
88
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
89
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
90
+ these scaling strategies behave:
91
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
92
+ experimental feature, subject to breaking API changes in future versions.
93
+ """
94
+ _auto_class = "AutoConfig"
95
+ model_type = "internlm2"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__( # pylint: disable=W0102
99
+ self,
100
+ vocab_size=103168,
101
+ hidden_size=4096,
102
+ intermediate_size=11008,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ num_key_value_heads=None,
106
+ hidden_act="silu",
107
+ max_position_embeddings=2048,
108
+ initializer_range=0.02,
109
+ rms_norm_eps=1e-6,
110
+ use_cache=True,
111
+ pad_token_id=0,
112
+ bos_token_id=1,
113
+ eos_token_id=2,
114
+ pretraining_tp=1,
115
+ tie_word_embeddings=False,
116
+ bias=True,
117
+ rope_theta=10000,
118
+ rope_scaling=None,
119
+ attn_implementation=None,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+ self.bias = bias
129
+
130
+ if num_key_value_heads is None:
131
+ num_key_value_heads = num_attention_heads
132
+ self.num_key_value_heads = num_key_value_heads
133
+
134
+ self.hidden_act = hidden_act
135
+ self.initializer_range = initializer_range
136
+ self.rms_norm_eps = rms_norm_eps
137
+ self.pretraining_tp = pretraining_tp
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.rope_scaling = rope_scaling
141
+ self._rope_scaling_validation()
142
+ self.attn_implementation = attn_implementation
143
+ if self.attn_implementation is None:
144
+ self.attn_implementation = "eager"
145
+
146
+ super().__init__(
147
+ pad_token_id=pad_token_id,
148
+ bos_token_id=bos_token_id,
149
+ eos_token_id=eos_token_id,
150
+ tie_word_embeddings=tie_word_embeddings,
151
+ **kwargs,
152
+ )
153
+
154
+ def _rope_scaling_validation(self):
155
+ """
156
+ Validate the `rope_scaling` configuration.
157
+ """
158
+ if self.rope_scaling is None:
159
+ return
160
+
161
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
162
+ raise ValueError(
163
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
164
+ f"got {self.rope_scaling}"
165
+ )
166
+ rope_scaling_type = self.rope_scaling.get("type", None)
167
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
168
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
169
+ raise ValueError(
170
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
171
+ )
172
+ if (
173
+ rope_scaling_factor is None
174
+ or not isinstance(rope_scaling_factor, (float, int))
175
+ or rope_scaling_factor < 1.0
176
+ ):
177
+ raise ValueError(
178
+ f"`rope_scaling`'s factor field must be a number >= 1, got {rope_scaling_factor} "
179
+ f"of type {type(rope_scaling_factor)}"
180
+ )
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef1857238242f6e81191155d762384eb255c00169e123501ca8a03841b9b73e0
3
+ size 4979479072
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69046c0047c219b5357c5cd15d2871b1c7a93bd2096298977f67eebeb36d5523
3
+ size 4976290664
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51e8870c7ce5ad64e1e342078b35e9694ee26ed465dae076b0212702b7a10706
3
+ size 4942473752
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bcd1aa2e9dbbbe669544a525ee2f39ffb6005c715e9015137880f7b55ad4741
3
+ size 3014479504
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
model_config.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import re, ast
3
+ from transformers import AutoConfig, LlamaConfig
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ from easydict import EasyDict as MyEasyDict
8
+ from importlib import import_module
9
+ import os.path as osp
10
+ import argparse
11
+ import json
12
+ from copy import deepcopy
13
+ import sys
14
+
15
+
16
+ class VideoChat2Config(PretrainedConfig):
17
+ model_type = 'InternVideo2_VideoChat2'
18
+
19
+ def __init__(
20
+ self,
21
+ model_config=None,
22
+ **kwargs):
23
+ super().__init__(**kwargs)
24
+ self.model_config = MyEasyDict(model_config)
modeling_base.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import warnings
4
+ import logging
5
+ import torch
6
+ import torch.utils.checkpoint
7
+ from torch import nn
8
+ from torch.nn import MSELoss
9
+
10
+ from torch.cuda.amp import autocast as autocast
11
+
12
+ from .modeling_internvideo2_vit import pretrain_internvideo2_giant_patch14_224_clean
13
+ from .modeling_qformer import build_qformer
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ from transformers import LlamaTokenizer,AutoTokenizer,AutoModel,AutoModelForCausalLM,AutoProcessor
18
+ from transformers import AutoConfig, PreTrainedModel
19
+ from .model_config import VideoChat2Config
20
+
21
+
22
+ def disabled_train(self, mode=True):
23
+ """Overwrite model.train with this function to make sure train/eval mode
24
+ does not change anymore."""
25
+ return self
26
+
27
+
28
+ def freeze_module(module):
29
+ for _, param in module.named_parameters():
30
+ param.requires_grad = False
31
+ module = module.eval()
32
+ module.train = disabled_train
33
+ return module
34
+
35
+
36
+ class LLMConfig(AutoConfig):
37
+ model_type = ""
38
+
39
+
40
+ class BaseMLLM(PreTrainedModel):
41
+ config_class = VideoChat2Config
42
+ def __init__(self, config):
43
+ # super().__init__(config)
44
+ self.model_config = config.model_config
45
+ config.model_config = None
46
+ super().__init__(config)
47
+ self.build_vision_encoder()
48
+ self.build_llm()
49
+ self.build_bridge()
50
+ self.build_loss()
51
+ # NOTE place it after freeze llm
52
+ for n, p in self.named_parameters():
53
+ if p.requires_grad:
54
+ logger.info(f'{n} requires_grad')
55
+
56
+
57
+ def build_vision_encoder(self):
58
+ # load pretrained internvideo2-1b here, simplified as it receives no args
59
+ # note that we haven't load the internvideo pretrained version
60
+ if 'internvideo2' in self.model_config.vision_encoder.name.lower():
61
+ encoder_name = self.model_config.vision_encoder.name
62
+ logger.info(f"Build vision_encoder: {encoder_name}")
63
+ if encoder_name == 'internvideo2-1B':
64
+ self.vision_encoder = pretrain_internvideo2_giant_patch14_224_clean(self.model_config)
65
+ else:
66
+ raise ValueError(f"Not implemented: {encoder_name}")
67
+ else:
68
+ raise NotImplementedError(self.model_config.vision_encoder.name)
69
+
70
+ if self.model_config.vision_encoder.vit_add_ln:
71
+ self.vision_layernorm = nn.LayerNorm(self.model_config.vision_encoder.encoder_embed_dim, eps=1e-12)
72
+ else:
73
+ self.vision_layernorm = nn.Identity()
74
+
75
+ self.freeze_vision_encoder = self.model_config.get("freeze_vision_encoder", False)
76
+
77
+ if self.freeze_vision_encoder:
78
+ logger.info("freeze vision encoder")
79
+ freeze_module(self.vision_encoder)
80
+ freeze_module(self.vision_layernorm)
81
+
82
+
83
+ def build_bridge(self):
84
+ # ViT to LM: 1792 -> 6656 NOTE 768 is qformer dim
85
+ self.project_up = nn.Linear(768, self.lm.config.hidden_size) # whether bias is needed?
86
+ # LM to ViT: 6656 -> 1792
87
+ self.project_down = nn.Linear(self.lm.config.hidden_size, 768)
88
+
89
+ if 'qformer' in self.model_config.bridge.name.lower():
90
+ from transformers import BertTokenizer
91
+ self.qformer_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased", truncation_side="left")
92
+ self.qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"})
93
+ self.qformer_tokenizer.padding_side = "left"
94
+ if self.model_config.bridge.name == 'qformer':
95
+ self.qformer, self.query_tokens = build_qformer(
96
+ self.model_config.bridge.num_query_token, self.model_config.vision_encoder.encoder_embed_dim,
97
+ qformer_hidden_dropout_prob=self.model_config.bridge.qformer_hidden_dropout_prob,
98
+ qformer_attention_probs_dropout_prob=self.model_config.bridge.qformer_attention_probs_dropout_prob,
99
+ qformer_drop_path_rate=self.model_config.bridge.qformer_drop_path_rate,
100
+ )
101
+ self.qformer.resize_token_embeddings(len(self.qformer_tokenizer))
102
+ self.qformer.cls = None
103
+ self.extra_num_query_token = self.model_config.bridge.extra_num_query_token
104
+ if self.model_config.bridge.extra_num_query_token > 0:
105
+ logger.info(f"Add extra {self.model_config.bridge.extra_num_query_token} tokens in QFormer")
106
+ self.extra_query_tokens = nn.Parameter(
107
+ torch.zeros(1, self.model_config.bridge.extra_num_query_token, self.query_tokens.shape[-1])
108
+ )
109
+
110
+ self.freeze_bridge = self.model_config.get("freeze_bridge", False)
111
+ if self.freeze_bridge:
112
+ logger.info("freeze bridge")
113
+ freeze_module(self.qformer)
114
+ self.query_tokens.requires_grad = False
115
+
116
+ def build_llm(self):
117
+ self.lm_name = self.model_config.llm.name
118
+ if self.model_config.llm.name == 'mistral_7b':
119
+ from transformers import AutoModelForCausalLM
120
+ config = AutoConfig.from_pretrained(
121
+ self.model_config.llm.pretrained_llm_path,
122
+ torch_dtype=torch.bfloat16,
123
+ token=token,
124
+ # attn_implementation="flash_attention_2",
125
+ )
126
+ self.lm = AutoModelForCausalLM.from_config(config)
127
+ elif self.model_config.llm.name == 'internlm_20b':
128
+ from transformers import AutoModelForCausalLM
129
+ self.lm = AutoModelForCausalLM.from_pretrained(
130
+ self.model_config.llm.pretrained_llm_path,
131
+ torch_dtype=torch.bfloat16,
132
+ trust_remote_code=True,
133
+ )
134
+ self.lm.gradient_checkpointing = True
135
+ self.lm._set_gradient_checkpointing()
136
+ elif self.model_config.llm.name == 'internlm2_5_7b':
137
+ from transformers import AutoModelForCausalLM
138
+ config = AutoConfig.from_pretrained(
139
+ self.model_config.llm.pretrained_llm_path,
140
+ torch_dtype=torch.bfloat16,
141
+ trust_remote_code=True,
142
+ )
143
+ self.lm = AutoModelForCausalLM.from_config(config,trust_remote_code=True)
144
+ else:
145
+ raise NotImplementedError(self.model_config.llm.name)
146
+
147
+ self.freeze_llm = self.model_config.get("freeze_llm", True)
148
+ logger.info(f'freeze_llm: {self.freeze_llm}')
149
+ if self.freeze_llm:
150
+ logger.info("freeze llm")
151
+ freeze_module(self.lm)
152
+
153
+ if self.model_config.llm.use_lora:
154
+ self.use_lora = True
155
+ from peft import get_peft_model, LoraConfig, TaskType
156
+ logger.info("Use lora")
157
+ if "internlm" in self.model_config.llm.name:
158
+ peft_config = LoraConfig(
159
+ task_type=TaskType.CAUSAL_LM, inference_mode=False,
160
+ r=self.model_config.llm.lora_r, lora_alpha=self.model_config.llm.lora_alpha, lora_dropout=self.model_config.llm.lora_dropout,
161
+ target_modules=['wqkv', 'wo', 'w1', 'w2', 'w3']
162
+ )
163
+ else:
164
+ peft_config = LoraConfig(
165
+ task_type=TaskType.CAUSAL_LM, inference_mode=False,
166
+ r=self.model_config.llm.lora_r, lora_alpha=self.model_config.llm.lora_alpha, lora_dropout=self.model_config.llm.lora_dropout,
167
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
168
+ "gate_proj", "up_proj", "down_proj", "lm_head"]
169
+ )
170
+
171
+ self.lm = get_peft_model(self.lm, peft_config)
172
+ self.lm.enable_input_require_grads()
173
+ self.lm.print_trainable_parameters()
174
+ else:
175
+ self.use_lora = False
176
+
177
+
178
+ def build_loss(self):
179
+ self.use_vision_regression_loss = self.model_config.loss.get("use_vision_regression_loss", False)
180
+ if self.use_vision_regression_loss:
181
+ self.image_loss_fct = MSELoss()
182
+
183
+ @property
184
+ def dtype(self):
185
+ return self.lm.dtype
186
+
187
+
188
+ @property
189
+ def device(self):
190
+ return self.lm.device
modeling_internlm2.py ADDED
@@ -0,0 +1,1808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch InternLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from einops import rearrange
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+
48
+ try:
49
+ from transformers.generation.streamers import BaseStreamer
50
+ except Exception:
51
+ BaseStreamer = None
52
+
53
+ from .configuration_internlm2 import InternLM2Config
54
+
55
+
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
59
+ except:
60
+ pass
61
+
62
+ try:
63
+ support_bf16_triu = torch.__version__ >= "2.1.0"
64
+ except Exception:
65
+ support_bf16_triu = False
66
+
67
+ logger = logging.get_logger(__name__)
68
+
69
+ _CONFIG_FOR_DOC = "InternLM2Config"
70
+
71
+
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) # pylint: disable=E1102
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ class InternLM2RMSNorm(nn.Module):
85
+ """InternLM2RMSNorm is equivalent to T5LayerNorm."""
86
+
87
+ def __init__(self, hidden_size, eps=1e-6):
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
97
+ return self.weight * hidden_states.to(input_dtype)
98
+
99
+
100
+ ALL_LAYERNORM_LAYERS.append(InternLM2RMSNorm)
101
+
102
+
103
+ class InternLM2RotaryEmbedding(nn.Module):
104
+ """Rotary Position Embedding for the InternLM2 model. Credits to the Reddit user /u/lucidrains."""
105
+
106
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
107
+ super().__init__()
108
+ self.scaling_factor = scaling_factor
109
+ self.dim = dim
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.base = base
112
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
113
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
114
+ # For BC we register cos and sin cached
115
+ self.max_seq_len_cached = max_position_embeddings
116
+
117
+ @torch.no_grad()
118
+ def forward(self, x, position_ids):
119
+ # x: [bs, num_attention_heads, seq_len, head_size]
120
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
121
+ position_ids_expanded = position_ids[:, None, :].float()
122
+ # Force float32 since bfloat16 loses precision on long contexts
123
+ # See https://github.com/huggingface/transformers/pull/29285
124
+ device_type = x.device.type
125
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
126
+ with torch.autocast(device_type=device_type, enabled=False):
127
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
128
+ emb = torch.cat((freqs, freqs), dim=-1)
129
+ cos = emb.cos()
130
+ sin = emb.sin()
131
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
132
+
133
+
134
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
135
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
136
+
137
+ def forward(self, x, position_ids):
138
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
139
+ position_ids = position_ids.float() / self.scaling_factor
140
+ cos, sin = super().forward(x, position_ids)
141
+ return cos, sin
142
+
143
+
144
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
145
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
146
+ Credits to the Reddit users /u/bloc97 and /u/emozilla"""
147
+
148
+ def forward(self, x, position_ids):
149
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
150
+ seq_len = torch.max(position_ids) + 1
151
+ if seq_len > self.max_position_embeddings:
152
+ base = self.base * (
153
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
154
+ ) ** (self.dim / (self.dim - 2))
155
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim))
156
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
157
+
158
+ cos, sin = super().forward(x, position_ids)
159
+ return cos, sin
160
+
161
+
162
+ def rotate_half(x):
163
+ """Rotates half the hidden dims of the input."""
164
+ x1 = x[..., : x.shape[-1] // 2]
165
+ x2 = x[..., x.shape[-1] // 2 :]
166
+ return torch.cat((-x2, x1), dim=-1)
167
+
168
+
169
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): # pylint: disable=unused-argument
170
+ """Applies Rotary Position Embedding to the query and key tensors.
171
+
172
+ Args:
173
+ q (`torch.Tensor`): The query tensor.
174
+ k (`torch.Tensor`): The key tensor.
175
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
176
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
177
+ position_ids (`torch.Tensor`, *optional*):
178
+ Deprecated and unused.
179
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
180
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
181
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
182
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
183
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
184
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
185
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
186
+ Returns:
187
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
188
+ """
189
+ cos = cos.unsqueeze(unsqueeze_dim)
190
+ sin = sin.unsqueeze(unsqueeze_dim)
191
+ q_embed = (q * cos) + (rotate_half(q) * sin)
192
+ k_embed = (k * cos) + (rotate_half(k) * sin)
193
+ return q_embed, k_embed
194
+
195
+
196
+ class InternLM2MLP(nn.Module):
197
+ """MLP for InternLM2 model."""
198
+
199
+ def __init__(self, config):
200
+ super().__init__()
201
+ self.config = config
202
+ self.hidden_size = config.hidden_size
203
+ self.intermediate_size = config.intermediate_size
204
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
205
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
206
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
207
+ self.act_fn = ACT2FN[config.hidden_act]
208
+
209
+ def forward(self, x):
210
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
211
+
212
+ return down_proj
213
+
214
+
215
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
216
+ """
217
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
218
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
219
+ """
220
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
221
+ if n_rep == 1:
222
+ return hidden_states
223
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
224
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
225
+
226
+
227
+ class InternLM2Attention(nn.Module):
228
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
229
+
230
+ def __init__(self, config: InternLM2Config, layer_idx: Optional[int] = None):
231
+ super().__init__()
232
+ self.config = config
233
+ self.layer_idx = layer_idx
234
+ if layer_idx is None:
235
+ logger.warning_once(
236
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
237
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
238
+ "when creating this class."
239
+ )
240
+
241
+ self.hidden_size = config.hidden_size
242
+ self.num_heads = config.num_attention_heads
243
+ self.head_dim = self.hidden_size // self.num_heads
244
+ self.num_key_value_heads = config.num_key_value_heads
245
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
246
+ self.max_position_embeddings = config.max_position_embeddings
247
+ self.rope_theta = config.rope_theta
248
+ self.is_causal = True
249
+
250
+ if (self.head_dim * self.num_heads) != self.hidden_size:
251
+ raise ValueError(
252
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
253
+ f" and `num_heads`: {self.num_heads})."
254
+ )
255
+
256
+ self.wqkv = nn.Linear(
257
+ self.hidden_size,
258
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
259
+ bias=config.bias,
260
+ )
261
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
262
+
263
+ self._init_rope()
264
+
265
+ def _init_rope(self):
266
+ if self.config.rope_scaling is None:
267
+ self.rotary_emb = InternLM2RotaryEmbedding(
268
+ self.head_dim,
269
+ max_position_embeddings=self.max_position_embeddings,
270
+ base=self.rope_theta,
271
+ )
272
+ else:
273
+ scaling_type = self.config.rope_scaling["type"]
274
+ scaling_factor = self.config.rope_scaling["factor"]
275
+ if scaling_type == "linear":
276
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
277
+ self.head_dim,
278
+ max_position_embeddings=self.max_position_embeddings,
279
+ scaling_factor=scaling_factor,
280
+ base=self.rope_theta,
281
+ )
282
+ elif scaling_type == "dynamic":
283
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
284
+ self.head_dim,
285
+ max_position_embeddings=self.max_position_embeddings,
286
+ scaling_factor=scaling_factor,
287
+ base=self.rope_theta,
288
+ )
289
+ else:
290
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
291
+
292
+ def forward(
293
+ self,
294
+ hidden_states: torch.Tensor,
295
+ attention_mask: Optional[torch.Tensor] = None,
296
+ position_ids: Optional[torch.LongTensor] = None,
297
+ past_key_value: Optional[Cache] = None,
298
+ output_attentions: bool = False,
299
+ use_cache: bool = False, # pylint: disable=unused-argument
300
+ cache_position: Optional[torch.LongTensor] = None,
301
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
302
+ bsz, q_len, _ = hidden_states.size()
303
+
304
+ if self.config.pretraining_tp > 1:
305
+ # split qkv_states by tp size
306
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
307
+ qkv_slices = self.wqkv.weight.split(key_value_slicing, dim=0)
308
+ qkv_states = torch.cat(
309
+ [F.linear(hidden_states, qkv_slice) for qkv_slice in qkv_slices], dim=-1 # pylint: disable=E1102
310
+ )
311
+ else:
312
+ qkv_states = self.wqkv(hidden_states)
313
+
314
+ qkv_states = rearrange(
315
+ qkv_states,
316
+ "b q (h gs d) -> b q h gs d",
317
+ gs=2 + self.num_key_value_groups,
318
+ d=self.head_dim,
319
+ )
320
+
321
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
322
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d").transpose(1, 2)
323
+ key_states = qkv_states[..., -2, :].transpose(1, 2)
324
+ value_states = qkv_states[..., -1, :].transpose(1, 2)
325
+
326
+ cos, sin = self.rotary_emb(value_states, position_ids)
327
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
328
+
329
+ if past_key_value is not None:
330
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
331
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
332
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
333
+
334
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
335
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
336
+
337
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
338
+
339
+ if attention_mask is not None: # no matter the length, we just slice it
340
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
341
+ attn_weights = attn_weights + causal_mask
342
+
343
+ # upcast attention to fp32
344
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
345
+ attn_output = torch.matmul(attn_weights, value_states)
346
+
347
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
348
+ raise ValueError(
349
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
350
+ f" {attn_output.size()}"
351
+ )
352
+
353
+ attn_output = attn_output.transpose(1, 2).contiguous()
354
+
355
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
356
+
357
+ if self.config.pretraining_tp > 1:
358
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
359
+ o_proj_slices = self.wo.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
360
+ attn_output = sum(
361
+ [
362
+ F.linear(attn_output[i], o_proj_slices[i]) # pylint: disable=E1102
363
+ for i in range(self.config.pretraining_tp)
364
+ ]
365
+ )
366
+ else:
367
+ attn_output = self.wo(attn_output)
368
+
369
+ if not output_attentions:
370
+ attn_weights = None
371
+
372
+ return attn_output, attn_weights, past_key_value
373
+
374
+
375
+ class InternLM2FlashAttention2(InternLM2Attention):
376
+ """
377
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
378
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
379
+ flash attention and deal with padding tokens in case the input contains any of them.
380
+ """
381
+
382
+ def __init__(self, *args, **kwargs):
383
+ super().__init__(*args, **kwargs)
384
+
385
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
386
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement,
387
+ # that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
388
+ # Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
389
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1)
390
+ # produces a wrong mask (top-left).
391
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
392
+
393
+ def forward(
394
+ self,
395
+ hidden_states: torch.Tensor,
396
+ attention_mask: Optional[torch.LongTensor] = None,
397
+ position_ids: Optional[torch.LongTensor] = None,
398
+ past_key_value: Optional[Cache] = None,
399
+ output_attentions: bool = False,
400
+ use_cache: bool = False,
401
+ cache_position: Optional[torch.LongTensor] = None,
402
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
403
+ if isinstance(past_key_value, StaticCache):
404
+ raise ValueError(
405
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
406
+ "make sure to use `sdpa` in the mean time, and open an issue at "
407
+ "https://github.com/huggingface/transformers"
408
+ )
409
+
410
+ output_attentions = False
411
+
412
+ bsz, q_len, _ = hidden_states.size()
413
+
414
+ qkv_states = self.wqkv(hidden_states)
415
+
416
+ qkv_states = rearrange(
417
+ qkv_states,
418
+ "b q (h gs d) -> b q h gs d",
419
+ gs=2 + self.num_key_value_groups,
420
+ d=self.head_dim,
421
+ )
422
+
423
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
424
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
425
+ key_states = qkv_states[..., -2, :]
426
+ value_states = qkv_states[..., -1, :]
427
+
428
+ query_states = query_states.transpose(1, 2)
429
+ key_states = key_states.transpose(1, 2)
430
+ value_states = value_states.transpose(1, 2)
431
+
432
+ cos, sin = self.rotary_emb(value_states, position_ids)
433
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
434
+
435
+ if past_key_value is not None:
436
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
437
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
438
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
439
+
440
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout
441
+ # [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
442
+ # to be able to avoid many of these transpose/reshape/view.
443
+ query_states = query_states.transpose(1, 2)
444
+ key_states = key_states.transpose(1, 2)
445
+ value_states = value_states.transpose(1, 2)
446
+
447
+ # dropout_rate = self.attention_dropout if self.training else 0.0
448
+ dropout_rate = 0.0
449
+
450
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
451
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
452
+ # cast them back in the correct dtype just to be sure everything works as expected.
453
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
454
+ # in fp32. (InternLM2RMSNorm handles it correctly)
455
+
456
+ input_dtype = query_states.dtype
457
+ if input_dtype == torch.float32:
458
+ if torch.is_autocast_enabled():
459
+ target_dtype = torch.get_autocast_gpu_dtype()
460
+ # Handle the case where the model is quantized
461
+ elif hasattr(self.config, "_pre_quantization_dtype"):
462
+ target_dtype = self.config._pre_quantization_dtype
463
+ else:
464
+ target_dtype = self.wqkv.weight.dtype
465
+
466
+ logger.warning_once(
467
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
468
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
469
+ f" {target_dtype}."
470
+ )
471
+
472
+ query_states = query_states.to(target_dtype)
473
+ key_states = key_states.to(target_dtype)
474
+ value_states = value_states.to(target_dtype)
475
+
476
+ attn_output = self._flash_attention_forward(
477
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
478
+ )
479
+
480
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
481
+ attn_output = self.wo(attn_output)
482
+
483
+ if not output_attentions:
484
+ attn_weights = None
485
+
486
+ return attn_output, attn_weights, past_key_value # pylint: disable=E0606
487
+
488
+ def _flash_attention_forward(
489
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
490
+ ):
491
+ """
492
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
493
+ first unpad the input, then computes the attention scores and pad the final attention scores.
494
+
495
+ Args:
496
+ query_states (`torch.Tensor`):
497
+ Input query states to be passed to Flash Attention API
498
+ key_states (`torch.Tensor`):
499
+ Input key states to be passed to Flash Attention API
500
+ value_states (`torch.Tensor`):
501
+ Input value states to be passed to Flash Attention API
502
+ attention_mask (`torch.Tensor`):
503
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
504
+ position of padding tokens and 1 for the position of non-padding tokens.
505
+ dropout (`float`):
506
+ Attention dropout
507
+ softmax_scale (`float`, *optional*):
508
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
509
+ """
510
+ if not self._flash_attn_uses_top_left_mask:
511
+ causal = self.is_causal
512
+ else:
513
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1.
514
+ # For details, please see the comment in InternLM2FlashAttention2 __init__.
515
+ causal = self.is_causal and query_length != 1
516
+
517
+ # Contains at least one padding token in the sequence
518
+ if attention_mask is not None:
519
+ batch_size = query_states.shape[0]
520
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
521
+ query_states, key_states, value_states, attention_mask, query_length
522
+ )
523
+
524
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
525
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
526
+
527
+ attn_output_unpad = flash_attn_varlen_func( # pylint: disable=E0606
528
+ query_states,
529
+ key_states,
530
+ value_states,
531
+ cu_seqlens_q=cu_seqlens_q,
532
+ cu_seqlens_k=cu_seqlens_k,
533
+ max_seqlen_q=max_seqlen_in_batch_q,
534
+ max_seqlen_k=max_seqlen_in_batch_k,
535
+ dropout_p=dropout,
536
+ softmax_scale=softmax_scale,
537
+ causal=causal,
538
+ )
539
+
540
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) # pylint: disable=E0606
541
+ else:
542
+ attn_output = flash_attn_func( # pylint: disable=E0606
543
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
544
+ )
545
+
546
+ return attn_output
547
+
548
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
549
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
550
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
551
+
552
+ key_layer = index_first_axis( # pylint: disable=E0606
553
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
554
+ )
555
+ value_layer = index_first_axis( # pylint: disable=E0606
556
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
557
+ )
558
+ if query_length == kv_seq_len:
559
+ query_layer = index_first_axis( # pylint: disable=E0606
560
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
561
+ )
562
+ cu_seqlens_q = cu_seqlens_k
563
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
564
+ indices_q = indices_k
565
+ elif query_length == 1:
566
+ max_seqlen_in_batch_q = 1
567
+ cu_seqlens_q = torch.arange(
568
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
569
+ ) # There is a memcpy here, that is very bad.
570
+ indices_q = cu_seqlens_q[:-1]
571
+ query_layer = query_layer.squeeze(1)
572
+ else:
573
+ # The -q_len: slice assumes left padding.
574
+ attention_mask = attention_mask[:, -query_length:]
575
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( # pylint: disable=E0606
576
+ query_layer, attention_mask
577
+ )
578
+
579
+ return (
580
+ query_layer,
581
+ key_layer,
582
+ value_layer,
583
+ indices_q,
584
+ (cu_seqlens_q, cu_seqlens_k),
585
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
586
+ )
587
+
588
+
589
+ # Copied from transformers.models.llama.modeling_llama.LllamaSdpaAttention with Llama->InternLM2
590
+ class InternLM2SdpaAttention(InternLM2Attention):
591
+ """
592
+ InternLM2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
593
+ `InternLM2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
594
+ to adapt to SDPA API.
595
+ """
596
+
597
+ # Adapted from InternLM2Attention.forward
598
+ def forward(
599
+ self,
600
+ hidden_states: torch.Tensor,
601
+ attention_mask: Optional[torch.Tensor] = None,
602
+ position_ids: Optional[torch.LongTensor] = None,
603
+ past_key_value: Optional[Cache] = None,
604
+ output_attentions: bool = False,
605
+ use_cache: bool = False,
606
+ cache_position: Optional[torch.LongTensor] = None,
607
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
608
+ if output_attentions:
609
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"`
610
+ # once this is implemented.
611
+ logger.warning_once(
612
+ "InternLM2Model uses InternLM2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` "
613
+ "does not support `output_attentions=True`. Falling back to the manual attention implementation, "
614
+ "but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
615
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
616
+ )
617
+ return super().forward(
618
+ hidden_states=hidden_states,
619
+ attention_mask=attention_mask,
620
+ position_ids=position_ids,
621
+ past_key_value=past_key_value,
622
+ output_attentions=output_attentions,
623
+ use_cache=use_cache,
624
+ cache_position=cache_position,
625
+ )
626
+
627
+ bsz, q_len, _ = hidden_states.size()
628
+
629
+ qkv_states = self.wqkv(hidden_states)
630
+
631
+ qkv_states = rearrange(
632
+ qkv_states,
633
+ "b q (h gs d) -> b q h gs d",
634
+ gs=2 + self.num_key_value_groups,
635
+ d=self.head_dim,
636
+ )
637
+
638
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
639
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
640
+ key_states = qkv_states[..., -2, :]
641
+ value_states = qkv_states[..., -1, :]
642
+
643
+ query_states = query_states.transpose(1, 2)
644
+ key_states = key_states.transpose(1, 2)
645
+ value_states = value_states.transpose(1, 2)
646
+
647
+ cos, sin = self.rotary_emb(value_states, position_ids)
648
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
649
+
650
+ if past_key_value is not None:
651
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
652
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
653
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
654
+
655
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
656
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
657
+
658
+ causal_mask = attention_mask
659
+ if attention_mask is not None:
660
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
661
+
662
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with
663
+ # custom attn_mask, Reference: https://github.com/pytorch/pytorch/issues/112577.
664
+ if query_states.device.type == "cuda" and causal_mask is not None:
665
+ query_states = query_states.contiguous()
666
+ key_states = key_states.contiguous()
667
+ value_states = value_states.contiguous()
668
+
669
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of
670
+ # an inline conditional assignment in SDPA to support both torch.compile's dynamic shapes and full graph
671
+ # options. An inline conditional prevents dynamic shapes from compiling.
672
+ is_causal = bool(causal_mask is None and q_len > 1)
673
+
674
+ attn_output = torch.nn.functional.scaled_dot_product_attention( # pylint: disable=E1102
675
+ query_states,
676
+ key_states,
677
+ value_states,
678
+ attn_mask=causal_mask,
679
+ dropout_p=0.0,
680
+ is_causal=is_causal,
681
+ )
682
+
683
+ attn_output = attn_output.transpose(1, 2).contiguous()
684
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
685
+
686
+ attn_output = self.wo(attn_output)
687
+
688
+ return attn_output, None, past_key_value
689
+
690
+
691
+ INTERNLM2_ATTENTION_CLASSES = {
692
+ "eager": InternLM2Attention,
693
+ "flash_attention_2": InternLM2FlashAttention2,
694
+ "sdpa": InternLM2SdpaAttention,
695
+ }
696
+
697
+
698
+ # Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->InternLM2
699
+ class InternLM2DecoderLayer(nn.Module):
700
+ """InternLM2 Decoder Layer. This module is a single layer of the InternLM2 model."""
701
+
702
+ def __init__(self, config: InternLM2Config, layer_idx: int):
703
+ super().__init__()
704
+ self.hidden_size = config.hidden_size
705
+ self.layer_idx = layer_idx
706
+
707
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config, layer_idx=layer_idx)
708
+
709
+ self.feed_forward = InternLM2MLP(config)
710
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
711
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
712
+
713
+ def forward(
714
+ self,
715
+ hidden_states: torch.Tensor,
716
+ attention_mask: Optional[torch.Tensor] = None,
717
+ position_ids: Optional[torch.LongTensor] = None,
718
+ past_key_value: Optional[Cache] = None,
719
+ output_attentions: Optional[bool] = False,
720
+ use_cache: Optional[bool] = False,
721
+ cache_position: Optional[torch.LongTensor] = None,
722
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
723
+ """
724
+ Args:
725
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
726
+ attention_mask (`torch.FloatTensor`, *optional*):
727
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
728
+ query_sequence_length, key_sequence_length)` if default attention is used.
729
+ output_attentions (`bool`, *optional*):
730
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
731
+ returned tensors for more detail.
732
+ use_cache (`bool`, *optional*):
733
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
734
+ (see `past_key_values`).
735
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
736
+ """
737
+ residual = hidden_states
738
+
739
+ hidden_states = self.attention_norm(hidden_states)
740
+
741
+ # Self Attention
742
+ hidden_states, self_attn_weights, present_key_value = self.attention(
743
+ hidden_states=hidden_states,
744
+ attention_mask=attention_mask,
745
+ position_ids=position_ids,
746
+ past_key_value=past_key_value,
747
+ output_attentions=output_attentions,
748
+ use_cache=use_cache,
749
+ cache_position=cache_position,
750
+ )
751
+ hidden_states = residual + hidden_states
752
+
753
+ # Fully Connected
754
+ residual = hidden_states
755
+ hidden_states = self.ffn_norm(hidden_states)
756
+ hidden_states = self.feed_forward(hidden_states)
757
+ hidden_states = residual + hidden_states
758
+
759
+ outputs = (hidden_states,)
760
+
761
+ if output_attentions:
762
+ outputs += (self_attn_weights,)
763
+
764
+ if use_cache:
765
+ outputs += (present_key_value,)
766
+
767
+ return outputs
768
+
769
+
770
+ InternLM2_START_DOCSTRING = r"""
771
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
772
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
773
+ etc.)
774
+
775
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
776
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
777
+ and behavior.
778
+
779
+ Parameters:
780
+ config ([`InternLM2Config`]):
781
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
782
+ load the weights associated with the model, only the configuration. Check out the
783
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
784
+ """
785
+
786
+
787
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
788
+ @add_start_docstrings(
789
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
790
+ InternLM2_START_DOCSTRING,
791
+ )
792
+ class InternLM2PreTrainedModel(PreTrainedModel):
793
+ """
794
+ InternLM2 pretraiend model's base class.
795
+ """
796
+
797
+ config_class = InternLM2Config
798
+ base_model_prefix = "model"
799
+ supports_gradient_checkpointing = True
800
+ _no_split_modules = ["InternLM2DecoderLayer"]
801
+ _skip_keys_device_placement = ["past_key_values"]
802
+ _supports_flash_attn_2 = True
803
+ _supports_sdpa = True
804
+ _supports_cache_class = True
805
+ _supports_quantized_cache = True
806
+ _supports_static_cache = True
807
+
808
+ def _init_weights(self, module):
809
+ std = self.config.initializer_range
810
+ if isinstance(module, nn.Linear):
811
+ module.weight.data.normal_(mean=0.0, std=std)
812
+ if module.bias is not None:
813
+ module.bias.data.zero_()
814
+ elif isinstance(module, nn.Embedding):
815
+ module.weight.data.normal_(mean=0.0, std=std)
816
+ if module.padding_idx is not None:
817
+ module.weight.data[module.padding_idx].zero_()
818
+
819
+
820
+ InternLM2_INPUTS_DOCSTRING = r"""
821
+ Args:
822
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
823
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
824
+ it.
825
+
826
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
827
+ [`PreTrainedTokenizer.__call__`] for details.
828
+
829
+ [What are input IDs?](../glossary#input-ids)
830
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
831
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
832
+
833
+ - 1 for tokens that are **not masked**,
834
+ - 0 for tokens that are **masked**.
835
+
836
+ [What are attention masks?](../glossary#attention-mask)
837
+
838
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
839
+ [`PreTrainedTokenizer.__call__`] for details.
840
+
841
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
842
+ `past_key_values`).
843
+
844
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
845
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
846
+ information on the default strategy.
847
+
848
+ - 1 indicates the head is **not masked**,
849
+ - 0 indicates the head is **masked**.
850
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
851
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
852
+ config.n_positions - 1]`.
853
+
854
+ [What are position IDs?](../glossary#position-ids)
855
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
856
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
857
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
858
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
859
+
860
+ Two formats are allowed:
861
+ - a [`~cache_utils.Cache`] instance;
862
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
863
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
864
+ cache format.
865
+
866
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
867
+ legacy cache format will be returned.
868
+
869
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
870
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
871
+ of shape `(batch_size, sequence_length)`.
872
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
873
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
874
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
875
+ model's internal embedding lookup matrix.
876
+ use_cache (`bool`, *optional*):
877
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
878
+ `past_key_values`).
879
+ output_attentions (`bool`, *optional*):
880
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
881
+ tensors for more detail.
882
+ output_hidden_states (`bool`, *optional*):
883
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
884
+ more detail.
885
+ return_dict (`bool`, *optional*):
886
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
887
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
888
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
889
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
890
+ the complete sequence length.
891
+ """
892
+
893
+
894
+ # Modified from transformers.models.llama.modeling_llama.LlamaModel with Llama->InternLM2
895
+ @add_start_docstrings(
896
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
897
+ InternLM2_START_DOCSTRING,
898
+ )
899
+ class InternLM2Model(InternLM2PreTrainedModel):
900
+ """
901
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
902
+
903
+ Args:
904
+ config: InternLM2Config
905
+ """
906
+
907
+ _auto_class = "AutoModel"
908
+
909
+ def __init__(self, config: InternLM2Config):
910
+ super().__init__(config)
911
+ self.padding_idx = config.pad_token_id
912
+ self.vocab_size = config.vocab_size
913
+ self.config = config
914
+
915
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
916
+
917
+ self.layers = nn.ModuleList(
918
+ [InternLM2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
919
+ )
920
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
921
+
922
+ self.gradient_checkpointing = False
923
+ # Initialize weights and apply final processing
924
+ self.post_init()
925
+
926
+ def get_input_embeddings(self):
927
+ return self.tok_embeddings
928
+
929
+ def set_input_embeddings(self, value):
930
+ self.tok_embeddings = value
931
+
932
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
933
+ def forward(
934
+ self,
935
+ input_ids: torch.LongTensor = None,
936
+ attention_mask: Optional[torch.Tensor] = None,
937
+ position_ids: Optional[torch.LongTensor] = None,
938
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
939
+ inputs_embeds: Optional[torch.FloatTensor] = None,
940
+ use_cache: Optional[bool] = None,
941
+ output_attentions: Optional[bool] = None,
942
+ output_hidden_states: Optional[bool] = None,
943
+ return_dict: Optional[bool] = None,
944
+ cache_position: Optional[torch.LongTensor] = None,
945
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
946
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
947
+ output_hidden_states = (
948
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
949
+ )
950
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
951
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
952
+
953
+ if (input_ids is None) ^ (inputs_embeds is not None):
954
+ raise ValueError(
955
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
956
+ )
957
+
958
+ if self.gradient_checkpointing and self.training and use_cache:
959
+ logger.warning_once(
960
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
961
+ )
962
+ use_cache = False
963
+
964
+ if inputs_embeds is None:
965
+ inputs_embeds = self.tok_embeddings(input_ids)
966
+
967
+ return_legacy_cache = False
968
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
969
+ return_legacy_cache = True
970
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
971
+
972
+ if cache_position is None:
973
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
974
+ cache_position = torch.arange(
975
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
976
+ )
977
+ if position_ids is None:
978
+ position_ids = cache_position.unsqueeze(0)
979
+
980
+ causal_mask = self._update_causal_mask(
981
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
982
+ )
983
+
984
+ # embed positions
985
+ hidden_states = inputs_embeds
986
+
987
+ # decoder layers
988
+ all_hidden_states = () if output_hidden_states else None
989
+ all_self_attns = () if output_attentions else None
990
+ next_decoder_cache = None
991
+
992
+ for decoder_layer in self.layers:
993
+ if output_hidden_states:
994
+ all_hidden_states += (hidden_states,)
995
+
996
+ if self.gradient_checkpointing and self.training:
997
+ layer_outputs = self._gradient_checkpointing_func(
998
+ decoder_layer.__call__,
999
+ hidden_states,
1000
+ causal_mask,
1001
+ position_ids,
1002
+ past_key_values,
1003
+ output_attentions,
1004
+ use_cache,
1005
+ cache_position,
1006
+ )
1007
+ else:
1008
+ layer_outputs = decoder_layer(
1009
+ hidden_states,
1010
+ attention_mask=causal_mask,
1011
+ position_ids=position_ids,
1012
+ past_key_value=past_key_values,
1013
+ output_attentions=output_attentions,
1014
+ use_cache=use_cache,
1015
+ cache_position=cache_position,
1016
+ )
1017
+
1018
+ hidden_states = layer_outputs[0]
1019
+
1020
+ if use_cache:
1021
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1022
+
1023
+ if output_attentions:
1024
+ all_self_attns += (layer_outputs[1],)
1025
+
1026
+ hidden_states = self.norm(hidden_states)
1027
+
1028
+ # add hidden states from the last decoder layer
1029
+ if output_hidden_states:
1030
+ all_hidden_states += (hidden_states,)
1031
+
1032
+ next_cache = next_decoder_cache if use_cache else None
1033
+ if return_legacy_cache:
1034
+ next_cache = next_cache.to_legacy_cache()
1035
+
1036
+ if not return_dict:
1037
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1038
+ return BaseModelOutputWithPast(
1039
+ last_hidden_state=hidden_states,
1040
+ past_key_values=next_cache,
1041
+ hidden_states=all_hidden_states,
1042
+ attentions=all_self_attns,
1043
+ )
1044
+
1045
+ def _update_causal_mask(
1046
+ self,
1047
+ attention_mask: torch.Tensor,
1048
+ input_tensor: torch.Tensor,
1049
+ cache_position: torch.Tensor,
1050
+ past_key_values: Cache,
1051
+ output_attentions: bool,
1052
+ ):
1053
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length
1054
+ # even when the static KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at
1055
+ # each decode steps due to the dynamic shapes. (`recording cudagraph tree for symint key 13`, etc.), which is
1056
+ # VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using `fullgraph=True`.
1057
+ # See more context in https://github.com/huggingface/transformers/pull/29114
1058
+
1059
+ if self.config.attn_implementation == "flash_attention_2":
1060
+ if attention_mask is not None and 0.0 in attention_mask:
1061
+ return attention_mask
1062
+ return None
1063
+
1064
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1065
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1066
+ # to infer the attention mask.
1067
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1068
+ using_static_cache = isinstance(past_key_values, StaticCache)
1069
+
1070
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1071
+ if self.config.attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1072
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1073
+ attention_mask,
1074
+ inputs_embeds=input_tensor,
1075
+ past_key_values_length=past_seen_tokens,
1076
+ is_training=self.training,
1077
+ ):
1078
+ return None
1079
+
1080
+ dtype, device = input_tensor.dtype, input_tensor.device
1081
+ min_dtype = torch.finfo(dtype).min
1082
+ sequence_length = input_tensor.shape[1]
1083
+ if using_static_cache:
1084
+ target_length = past_key_values.get_max_length()
1085
+ else:
1086
+ target_length = (
1087
+ attention_mask.shape[-1]
1088
+ if isinstance(attention_mask, torch.Tensor)
1089
+ else past_seen_tokens + sequence_length + 1
1090
+ )
1091
+
1092
+ if attention_mask is not None and attention_mask.dim() == 4:
1093
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1094
+ if attention_mask.max() != 0:
1095
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1096
+ causal_mask = attention_mask
1097
+ else:
1098
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1099
+ if sequence_length != 1:
1100
+ if support_bf16_triu or dtype == torch.float32:
1101
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1102
+ else:
1103
+ triu_mask = torch.triu(torch.ones(causal_mask.size(), device=device), diagonal=1).bool()
1104
+ causal_mask.masked_fill_(~triu_mask, 0)
1105
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1106
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1107
+ if attention_mask is not None:
1108
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1109
+ mask_length = attention_mask.shape[-1]
1110
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1111
+ padding_mask = padding_mask == 0
1112
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1113
+ padding_mask, min_dtype
1114
+ )
1115
+ if (
1116
+ self.config.attn_implementation == "sdpa"
1117
+ and attention_mask is not None
1118
+ and attention_mask.device.type == "cuda"
1119
+ and not output_attentions
1120
+ ):
1121
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1122
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1123
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1124
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) # pylint: disable=E1120
1125
+
1126
+ return causal_mask
1127
+
1128
+
1129
+ # Modified from transformers.models.llama.modeling_llama.LlamaForCausalLM
1130
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1131
+ """Causal language model (CLM) for InternLM2."""
1132
+
1133
+ _auto_class = "AutoModelForCausalLM"
1134
+ _tied_weights_keys = ["output.weight"]
1135
+
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+ self.model = InternLM2Model(config)
1139
+ self.vocab_size = config.vocab_size
1140
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1141
+
1142
+ # Initialize weights and apply final processing
1143
+ self.post_init()
1144
+
1145
+ def get_input_embeddings(self):
1146
+ return self.model.tok_embeddings
1147
+
1148
+ def set_input_embeddings(self, value):
1149
+ self.model.tok_embeddings = value
1150
+
1151
+ def get_output_embeddings(self):
1152
+ return self.output
1153
+
1154
+ def set_output_embeddings(self, new_embeddings):
1155
+ self.output = new_embeddings
1156
+
1157
+ def set_decoder(self, decoder):
1158
+ self.model = decoder
1159
+
1160
+ def get_decoder(self):
1161
+ return self.model
1162
+
1163
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1164
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1165
+ def forward(
1166
+ self,
1167
+ input_ids: torch.LongTensor = None,
1168
+ attention_mask: Optional[torch.Tensor] = None,
1169
+ position_ids: Optional[torch.LongTensor] = None,
1170
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1171
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1172
+ labels: Optional[torch.LongTensor] = None,
1173
+ use_cache: Optional[bool] = None,
1174
+ output_attentions: Optional[bool] = None,
1175
+ output_hidden_states: Optional[bool] = None,
1176
+ return_dict: Optional[bool] = None,
1177
+ cache_position: Optional[torch.LongTensor] = None,
1178
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1179
+ r"""
1180
+ Args:
1181
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1182
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1183
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1184
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1185
+
1186
+ Returns:
1187
+
1188
+ Example:
1189
+
1190
+ ```python
1191
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1192
+
1193
+ >>> model = InternLM2ForCausalLM.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
1194
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
1195
+
1196
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1197
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1198
+
1199
+ >>> # Generate
1200
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1201
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1202
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1203
+ ```"""
1204
+
1205
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1206
+ output_hidden_states = (
1207
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1208
+ )
1209
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1210
+
1211
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1212
+ outputs = self.model(
1213
+ input_ids=input_ids,
1214
+ attention_mask=attention_mask,
1215
+ position_ids=position_ids,
1216
+ past_key_values=past_key_values,
1217
+ inputs_embeds=inputs_embeds,
1218
+ use_cache=use_cache,
1219
+ output_attentions=output_attentions,
1220
+ output_hidden_states=output_hidden_states,
1221
+ return_dict=return_dict,
1222
+ cache_position=cache_position,
1223
+ )
1224
+
1225
+ hidden_states = outputs[0]
1226
+ if self.config.pretraining_tp > 1:
1227
+ output_slices = self.output.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1228
+ logits = [
1229
+ F.linear(hidden_states, output_slices[i]) # pylint: disable=not-callable
1230
+ for i in range(self.config.pretraining_tp)
1231
+ ]
1232
+ logits = torch.cat(logits, dim=-1)
1233
+ else:
1234
+ logits = self.output(hidden_states)
1235
+ logits = logits.float()
1236
+
1237
+ loss = None
1238
+ if labels is not None:
1239
+ # Shift so that tokens < n predict n
1240
+ shift_logits = logits[..., :-1, :].contiguous()
1241
+ shift_labels = labels[..., 1:].contiguous()
1242
+ # Flatten the tokens
1243
+ loss_fct = CrossEntropyLoss()
1244
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1245
+ shift_labels = shift_labels.view(-1)
1246
+ # Enable model parallelism
1247
+ shift_labels = shift_labels.to(shift_logits.device)
1248
+ loss = loss_fct(shift_logits, shift_labels)
1249
+
1250
+ if not return_dict:
1251
+ output = (logits,) + outputs[1:]
1252
+ return (loss,) + output if loss is not None else output
1253
+
1254
+ return CausalLMOutputWithPast(
1255
+ loss=loss,
1256
+ logits=logits,
1257
+ past_key_values=outputs.past_key_values,
1258
+ hidden_states=outputs.hidden_states,
1259
+ attentions=outputs.attentions,
1260
+ )
1261
+
1262
+ def prepare_inputs_for_generation(
1263
+ self,
1264
+ input_ids,
1265
+ past_key_values=None,
1266
+ attention_mask=None,
1267
+ inputs_embeds=None,
1268
+ cache_position=None,
1269
+ use_cache=True,
1270
+ **kwargs,
1271
+ ):
1272
+ past_length = 0
1273
+ if past_key_values is not None:
1274
+ if isinstance(past_key_values, Cache):
1275
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1276
+ max_cache_length = (
1277
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1278
+ if past_key_values.get_max_length() is not None
1279
+ else None
1280
+ )
1281
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1282
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1283
+ else:
1284
+ cache_length = past_length = past_key_values[0][0].shape[2]
1285
+ max_cache_length = None
1286
+
1287
+ # Keep only the unprocessed tokens:
1288
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1289
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1290
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1291
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1292
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1293
+ # input_ids based on the past_length.
1294
+ elif past_length < input_ids.shape[1]:
1295
+ input_ids = input_ids[:, past_length:]
1296
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1297
+
1298
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1299
+ if (
1300
+ max_cache_length is not None
1301
+ and attention_mask is not None
1302
+ and cache_length + input_ids.shape[1] > max_cache_length
1303
+ ):
1304
+ attention_mask = attention_mask[:, -max_cache_length:] # pylint: disable=E1130
1305
+
1306
+ position_ids = kwargs.get("position_ids", None)
1307
+ if attention_mask is not None and position_ids is None:
1308
+ # create position_ids on the fly for batch generation
1309
+ position_ids = attention_mask.long().cumsum(-1) - 1
1310
+ position_ids.masked_fill_(attention_mask == 0, 1)
1311
+ if past_key_values:
1312
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1313
+
1314
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1315
+ if inputs_embeds is not None and past_key_values is None:
1316
+ model_inputs = {"inputs_embeds": inputs_embeds}
1317
+ else:
1318
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1319
+ # recompiles graphs as the stride of the inputs is a guard.
1320
+ # Ref: https://github.com/huggingface/transformers/pull/29114
1321
+ # TODO: use `next_tokens` directly instead.
1322
+ model_inputs = {"input_ids": input_ids.contiguous()}
1323
+
1324
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1325
+ if cache_position is None:
1326
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1327
+ elif use_cache:
1328
+ cache_position = cache_position[-input_length:]
1329
+
1330
+ model_inputs.update(
1331
+ {
1332
+ "position_ids": position_ids,
1333
+ "cache_position": cache_position,
1334
+ "past_key_values": past_key_values,
1335
+ "use_cache": use_cache,
1336
+ "attention_mask": attention_mask,
1337
+ }
1338
+ )
1339
+ return model_inputs
1340
+
1341
+ @staticmethod
1342
+ def _reorder_cache(past_key_values, beam_idx):
1343
+ reordered_past = ()
1344
+ for layer_past in past_key_values:
1345
+ reordered_past += (
1346
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1347
+ )
1348
+ return reordered_past
1349
+
1350
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, meta_instruction=""):
1351
+ if history is None:
1352
+ history = []
1353
+ if tokenizer.add_bos_token:
1354
+ prompt = ""
1355
+ else:
1356
+ prompt = tokenizer.bos_token
1357
+ if meta_instruction:
1358
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1359
+ for record in history:
1360
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1361
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1362
+ return tokenizer([prompt], return_tensors="pt")
1363
+
1364
+ @torch.no_grad()
1365
+ def chat(
1366
+ self,
1367
+ tokenizer,
1368
+ query: str,
1369
+ history: Optional[List[Tuple[str, str]]] = None,
1370
+ streamer: Optional[BaseStreamer] = None,
1371
+ max_new_tokens: int = 1024,
1372
+ do_sample: bool = True,
1373
+ temperature: float = 0.8,
1374
+ top_p: float = 0.8,
1375
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1376
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
1377
+ "(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
1378
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such "
1379
+ "as English and 中文.",
1380
+ **kwargs,
1381
+ ):
1382
+ if history is None:
1383
+ history = []
1384
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1385
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1386
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1387
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
1388
+ outputs = self.generate(
1389
+ **inputs,
1390
+ streamer=streamer,
1391
+ max_new_tokens=max_new_tokens,
1392
+ do_sample=do_sample,
1393
+ temperature=temperature,
1394
+ top_p=top_p,
1395
+ eos_token_id=eos_token_id,
1396
+ **kwargs,
1397
+ )
1398
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1399
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1400
+ response = response.split("<|im_end|>")[0]
1401
+ history = history + [(query, response)]
1402
+ return response, history
1403
+
1404
+ @torch.no_grad()
1405
+ def stream_chat(
1406
+ self,
1407
+ tokenizer,
1408
+ query: str,
1409
+ history: List[Tuple[str, str]] = None,
1410
+ max_new_tokens: int = 1024,
1411
+ do_sample: bool = True,
1412
+ temperature: float = 0.8,
1413
+ top_p: float = 0.8,
1414
+ **kwargs,
1415
+ ):
1416
+ if history is None:
1417
+ history = []
1418
+ """
1419
+ Return a generator in format: (response, history)
1420
+ Eg.
1421
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1422
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1423
+ """
1424
+ if BaseStreamer is None:
1425
+ raise ModuleNotFoundError(
1426
+ "The version of `transformers` is too low. Please make sure "
1427
+ "that you have installed `transformers>=4.28.0`."
1428
+ )
1429
+
1430
+ response_queue = queue.Queue(maxsize=20)
1431
+
1432
+ class ChatStreamer(BaseStreamer):
1433
+ """
1434
+ Streamer used in generate to print words one by one.
1435
+ """
1436
+
1437
+ def __init__(self, tokenizer) -> None:
1438
+ super().__init__()
1439
+ self.tokenizer = tokenizer
1440
+ self.queue = response_queue
1441
+ self.query = query
1442
+ self.history = history
1443
+ self.response = ""
1444
+ self.cache = []
1445
+ self.received_inputs = False
1446
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1447
+
1448
+ def put(self, value):
1449
+ if len(value.shape) > 1 and value.shape[0] > 1:
1450
+ raise ValueError("ChatStreamer only supports batch size 1")
1451
+ elif len(value.shape) > 1:
1452
+ value = value[0]
1453
+
1454
+ if not self.received_inputs:
1455
+ # The first received value is input_ids, ignore here
1456
+ self.received_inputs = True
1457
+ return
1458
+
1459
+ self.cache.extend(value.tolist())
1460
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1461
+ if token.strip() != "<|im_end|>":
1462
+ self.response = self.response + token
1463
+ history = self.history + [(self.query, self.response)]
1464
+ self.queue.put((self.response, history))
1465
+ self.cache = []
1466
+ else:
1467
+ self.end()
1468
+
1469
+ def end(self):
1470
+ self.queue.put(None)
1471
+
1472
+ def stream_producer():
1473
+ return self.chat(
1474
+ tokenizer=tokenizer,
1475
+ query=query,
1476
+ streamer=ChatStreamer(tokenizer=tokenizer),
1477
+ history=history,
1478
+ max_new_tokens=max_new_tokens,
1479
+ do_sample=do_sample,
1480
+ temperature=temperature,
1481
+ top_p=top_p,
1482
+ **kwargs,
1483
+ )
1484
+
1485
+ def consumer():
1486
+ producer = threading.Thread(target=stream_producer)
1487
+ producer.start()
1488
+ while True:
1489
+ res = response_queue.get()
1490
+ if res is None:
1491
+ return
1492
+ yield res
1493
+
1494
+ return consumer()
1495
+
1496
+
1497
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1498
+ @add_start_docstrings(
1499
+ """
1500
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1501
+
1502
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1503
+ (e.g. GPT-2) do.
1504
+
1505
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1506
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1507
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1508
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1509
+ each row of the batch).
1510
+ """,
1511
+ InternLM2_START_DOCSTRING,
1512
+ )
1513
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1514
+ """Sequence Classification Head for InternLM2 Model."""
1515
+
1516
+ def __init__(self, config):
1517
+ super().__init__(config)
1518
+ self.num_labels = config.num_labels
1519
+ self.model = InternLM2Model(config)
1520
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1521
+
1522
+ # Initialize weights and apply final processing
1523
+ self.post_init()
1524
+
1525
+ def get_input_embeddings(self):
1526
+ return self.model.tok_embeddings
1527
+
1528
+ def set_input_embeddings(self, value):
1529
+ self.model.tok_embeddings = value
1530
+
1531
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1532
+ def forward(
1533
+ self,
1534
+ input_ids: torch.LongTensor = None,
1535
+ attention_mask: Optional[torch.Tensor] = None,
1536
+ position_ids: Optional[torch.LongTensor] = None,
1537
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1538
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1539
+ labels: Optional[torch.LongTensor] = None,
1540
+ use_cache: Optional[bool] = None,
1541
+ output_attentions: Optional[bool] = None,
1542
+ output_hidden_states: Optional[bool] = None,
1543
+ return_dict: Optional[bool] = None,
1544
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1545
+ r"""
1546
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1547
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1548
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1549
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1550
+ """
1551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1552
+
1553
+ transformer_outputs = self.model(
1554
+ input_ids,
1555
+ attention_mask=attention_mask,
1556
+ position_ids=position_ids,
1557
+ past_key_values=past_key_values,
1558
+ inputs_embeds=inputs_embeds,
1559
+ use_cache=use_cache,
1560
+ output_attentions=output_attentions,
1561
+ output_hidden_states=output_hidden_states,
1562
+ return_dict=return_dict,
1563
+ )
1564
+ hidden_states = transformer_outputs[0]
1565
+ logits = self.score(hidden_states)
1566
+
1567
+ if input_ids is not None:
1568
+ batch_size = input_ids.shape[0]
1569
+ else:
1570
+ batch_size = inputs_embeds.shape[0]
1571
+
1572
+ if self.config.pad_token_id is None and batch_size != 1:
1573
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1574
+ if self.config.pad_token_id is None:
1575
+ sequence_lengths = -1
1576
+ else:
1577
+ if input_ids is not None:
1578
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1579
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1580
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1581
+ sequence_lengths = sequence_lengths.to(logits.device)
1582
+ else:
1583
+ sequence_lengths = -1
1584
+
1585
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1586
+
1587
+ loss = None
1588
+ if labels is not None:
1589
+ labels = labels.to(logits.device)
1590
+ if self.config.problem_type is None:
1591
+ if self.num_labels == 1:
1592
+ self.config.problem_type = "regression"
1593
+ elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)):
1594
+ self.config.problem_type = "single_label_classification"
1595
+ else:
1596
+ self.config.problem_type = "multi_label_classification"
1597
+
1598
+ if self.config.problem_type == "regression":
1599
+ loss_fct = MSELoss()
1600
+ if self.num_labels == 1:
1601
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1602
+ else:
1603
+ loss = loss_fct(pooled_logits, labels)
1604
+ elif self.config.problem_type == "single_label_classification":
1605
+ loss_fct = CrossEntropyLoss()
1606
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1607
+ elif self.config.problem_type == "multi_label_classification":
1608
+ loss_fct = BCEWithLogitsLoss()
1609
+ loss = loss_fct(pooled_logits, labels)
1610
+ if not return_dict:
1611
+ output = (pooled_logits,) + transformer_outputs[1:]
1612
+ return ((loss,) + output) if loss is not None else output
1613
+
1614
+ return SequenceClassifierOutputWithPast(
1615
+ loss=loss,
1616
+ logits=pooled_logits,
1617
+ past_key_values=transformer_outputs.past_key_values,
1618
+ hidden_states=transformer_outputs.hidden_states,
1619
+ attentions=transformer_outputs.attentions,
1620
+ )
1621
+
1622
+
1623
+ # Copied from transformers.models.llama.modeling_llama.LlamaForQuestionAnswering with Llama->InternLM2
1624
+ @add_start_docstrings(
1625
+ """
1626
+ The InternLM2 Model transformer with a span classification head on top for extractive question-answering tasks like
1627
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1628
+ """,
1629
+ InternLM2_START_DOCSTRING,
1630
+ )
1631
+ class InternLM2ForQuestionAnswering(InternLM2PreTrainedModel):
1632
+ """Question Answering model for InternLM2."""
1633
+
1634
+ base_model_prefix = "transformer"
1635
+
1636
+ def __init__(self, config):
1637
+ super().__init__(config)
1638
+ self.transformer = InternLM2Model(config)
1639
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1640
+
1641
+ # Initialize weights and apply final processing
1642
+ self.post_init()
1643
+
1644
+ def get_input_embeddings(self):
1645
+ return self.transformer.tok_embeddings
1646
+
1647
+ def set_input_embeddings(self, value):
1648
+ self.transformer.tok_embeddings = value
1649
+
1650
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1651
+ def forward(
1652
+ self,
1653
+ input_ids: Optional[torch.LongTensor] = None,
1654
+ attention_mask: Optional[torch.FloatTensor] = None,
1655
+ position_ids: Optional[torch.LongTensor] = None,
1656
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1657
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1658
+ start_positions: Optional[torch.LongTensor] = None,
1659
+ end_positions: Optional[torch.LongTensor] = None,
1660
+ output_attentions: Optional[bool] = None,
1661
+ output_hidden_states: Optional[bool] = None,
1662
+ return_dict: Optional[bool] = None,
1663
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1664
+ r"""
1665
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1666
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1667
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1668
+ are not taken into account for computing the loss.
1669
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1670
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1671
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1672
+ are not taken into account for computing the loss.
1673
+ """
1674
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1675
+
1676
+ outputs = self.transformer(
1677
+ input_ids,
1678
+ attention_mask=attention_mask,
1679
+ position_ids=position_ids,
1680
+ past_key_values=past_key_values,
1681
+ inputs_embeds=inputs_embeds,
1682
+ output_attentions=output_attentions,
1683
+ output_hidden_states=output_hidden_states,
1684
+ return_dict=return_dict,
1685
+ )
1686
+
1687
+ sequence_output = outputs[0]
1688
+
1689
+ logits = self.qa_outputs(sequence_output)
1690
+ start_logits, end_logits = logits.split(1, dim=-1)
1691
+ start_logits = start_logits.squeeze(-1).contiguous()
1692
+ end_logits = end_logits.squeeze(-1).contiguous()
1693
+
1694
+ total_loss = None
1695
+ if start_positions is not None and end_positions is not None:
1696
+ # If we are on multi-GPU, split add a dimension
1697
+ if len(start_positions.size()) > 1:
1698
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1699
+ if len(end_positions.size()) > 1:
1700
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1701
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1702
+ ignored_index = start_logits.size(1)
1703
+ start_positions = start_positions.clamp(0, ignored_index)
1704
+ end_positions = end_positions.clamp(0, ignored_index)
1705
+
1706
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1707
+ start_loss = loss_fct(start_logits, start_positions)
1708
+ end_loss = loss_fct(end_logits, end_positions)
1709
+ total_loss = (start_loss + end_loss) / 2
1710
+
1711
+ if not return_dict:
1712
+ output = (start_logits, end_logits) + outputs[2:]
1713
+ return ((total_loss,) + output) if total_loss is not None else output
1714
+
1715
+ return QuestionAnsweringModelOutput(
1716
+ loss=total_loss,
1717
+ start_logits=start_logits,
1718
+ end_logits=end_logits,
1719
+ hidden_states=outputs.hidden_states,
1720
+ attentions=outputs.attentions,
1721
+ )
1722
+
1723
+
1724
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->InternLM2
1725
+ @add_start_docstrings(
1726
+ """
1727
+ The InternLM2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1728
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1729
+ """,
1730
+ InternLM2_START_DOCSTRING,
1731
+ )
1732
+ class InternLM2ForTokenClassification(InternLM2PreTrainedModel):
1733
+ """Token classification model for InternLM2."""
1734
+
1735
+ def __init__(self, config):
1736
+ super().__init__(config)
1737
+ self.num_labels = config.num_labels
1738
+ self.model = InternLM2Model(config)
1739
+ if getattr(config, "classifier_dropout", None) is not None:
1740
+ classifier_dropout = config.classifier_dropout
1741
+ elif getattr(config, "hidden_dropout", None) is not None:
1742
+ classifier_dropout = config.hidden_dropout
1743
+ else:
1744
+ classifier_dropout = 0.1
1745
+ self.dropout = nn.Dropout(classifier_dropout)
1746
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1747
+
1748
+ # Initialize weights and apply final processing
1749
+ self.post_init()
1750
+
1751
+ def get_input_embeddings(self):
1752
+ return self.model.tok_embeddings
1753
+
1754
+ def set_input_embeddings(self, value):
1755
+ self.model.tok_embeddings = value
1756
+
1757
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1758
+ def forward(
1759
+ self,
1760
+ input_ids: torch.LongTensor = None,
1761
+ attention_mask: Optional[torch.Tensor] = None,
1762
+ position_ids: Optional[torch.LongTensor] = None,
1763
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1764
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1765
+ labels: Optional[torch.LongTensor] = None,
1766
+ use_cache: Optional[bool] = None,
1767
+ output_attentions: Optional[bool] = None,
1768
+ output_hidden_states: Optional[bool] = None,
1769
+ return_dict: Optional[bool] = None,
1770
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1771
+ r"""
1772
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1773
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1774
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1775
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1776
+ """
1777
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1778
+
1779
+ outputs = self.model(
1780
+ input_ids,
1781
+ attention_mask=attention_mask,
1782
+ position_ids=position_ids,
1783
+ past_key_values=past_key_values,
1784
+ inputs_embeds=inputs_embeds,
1785
+ use_cache=use_cache,
1786
+ output_attentions=output_attentions,
1787
+ output_hidden_states=output_hidden_states,
1788
+ return_dict=return_dict,
1789
+ )
1790
+ sequence_output = outputs[0]
1791
+ sequence_output = self.dropout(sequence_output)
1792
+ logits = self.score(sequence_output)
1793
+
1794
+ loss = None
1795
+ if labels is not None:
1796
+ loss_fct = CrossEntropyLoss()
1797
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1798
+
1799
+ if not return_dict:
1800
+ output = (logits,) + outputs[2:]
1801
+ return ((loss,) + output) if loss is not None else output
1802
+
1803
+ return TokenClassifierOutput(
1804
+ loss=loss,
1805
+ logits=logits,
1806
+ hidden_states=outputs.hidden_states,
1807
+ attentions=outputs.attentions,
1808
+ )
modeling_internvideo2_vit.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import logging
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
6
+ from torch import nn
7
+
8
+ import torch.utils.checkpoint as checkpoint
9
+ from functools import partial
10
+ from einops import rearrange
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # try:
16
+ # from .flash_attention_class import FlashAttention
17
+ # except:
18
+ # logger.warn(f'flash_attn is not installed, you can install it by `pip install flash_attn` ')
19
+ # try:
20
+ # from flash_attn.modules.mlp import FusedMLP
21
+ # except:
22
+ # logger.warn(f'FusedMLP of flash_attn is not installed!!!')
23
+
24
+ # try:
25
+ # from flash_attn.ops.rms_norm import DropoutAddRMSNorm
26
+ # except:
27
+ # logger.warn(f'DropoutAddRMSNorm of flash_attn is not installed!!!')
28
+
29
+ import numpy as np
30
+ import torch
31
+ import logging
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ # --------------------------------------------------------
36
+ # 3D sine-cosine position embedding
37
+ # References:
38
+ # MVD: https://github.com/ruiwang2021/mvd/blob/main/modeling_finetune.py
39
+ # --------------------------------------------------------
40
+ def get_3d_sincos_pos_embed(embed_dim, grid_size, t_size, cls_token=False):
41
+ """
42
+ grid_size: int of the grid height and width
43
+ t_size: int of the temporal size
44
+ return:
45
+ pos_embed: [t_size*grid_size*grid_size, embed_dim] or [1+t_size*grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
46
+ """
47
+ assert embed_dim % 4 == 0
48
+ embed_dim_spatial = embed_dim // 4 * 3
49
+ embed_dim_temporal = embed_dim // 4
50
+
51
+ # spatial
52
+ grid_h = np.arange(grid_size, dtype=np.float32)
53
+ grid_w = np.arange(grid_size, dtype=np.float32)
54
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
55
+ grid = np.stack(grid, axis=0)
56
+
57
+ grid = grid.reshape([2, 1, grid_size, grid_size])
58
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(
59
+ embed_dim_spatial, grid
60
+ )
61
+
62
+ # temporal
63
+ grid_t = np.arange(t_size, dtype=np.float32)
64
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(
65
+ embed_dim_temporal, grid_t
66
+ )
67
+
68
+ # concate: [T, H, W] order
69
+ pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
70
+ pos_embed_temporal = np.repeat(
71
+ pos_embed_temporal, grid_size**2, axis=1
72
+ ) # [T, H*W, D // 4]
73
+ pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
74
+ pos_embed_spatial = np.repeat(
75
+ pos_embed_spatial, t_size, axis=0
76
+ ) # [T, H*W, D // 4 * 3]
77
+
78
+ pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1)
79
+ pos_embed = pos_embed.reshape([-1, embed_dim]) # [T*H*W, D]
80
+
81
+ if cls_token:
82
+ pos_embed = np.concatenate(
83
+ [np.zeros([1, embed_dim]), pos_embed], axis=0
84
+ )
85
+ return pos_embed
86
+
87
+
88
+ # --------------------------------------------------------
89
+ # 2D sine-cosine position embedding
90
+ # References:
91
+ # Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
92
+ # MoCo v3: https://github.com/facebookresearch/moco-v3
93
+ # --------------------------------------------------------
94
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
95
+ """
96
+ grid_size: int of the grid height and width
97
+ return:
98
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
99
+ """
100
+ grid_h = np.arange(grid_size, dtype=np.float32)
101
+ grid_w = np.arange(grid_size, dtype=np.float32)
102
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
103
+ grid = np.stack(grid, axis=0)
104
+
105
+ grid = grid.reshape([2, 1, grid_size, grid_size])
106
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
107
+ if cls_token:
108
+ pos_embed = np.concatenate(
109
+ [np.zeros([1, embed_dim]), pos_embed], axis=0
110
+ )
111
+ return pos_embed
112
+
113
+
114
+ def get_1d_sincos_pos_embed(embed_dim, t_size, cls_token=False):
115
+ """
116
+ t_size: int of the temporal size
117
+ return:
118
+ pos_embed: [t_size, embed_dim] or [1+t_size, embed_dim] (w/ or w/o cls_token)
119
+ """
120
+ grid_t = np.arange(t_size, dtype=np.float32)
121
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid_t)
122
+ if cls_token:
123
+ pos_embed = np.concatenate(
124
+ [np.zeros([1, embed_dim]), pos_embed], axis=0
125
+ )
126
+ return pos_embed
127
+
128
+
129
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
130
+ assert embed_dim % 2 == 0
131
+
132
+ # use half of dimensions to encode grid_h
133
+ emb_h = get_1d_sincos_pos_embed_from_grid(
134
+ embed_dim // 2, grid[0]
135
+ ) # (H*W, D/2)
136
+ emb_w = get_1d_sincos_pos_embed_from_grid(
137
+ embed_dim // 2, grid[1]
138
+ ) # (H*W, D/2)
139
+
140
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
141
+ return emb
142
+
143
+
144
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
145
+ """
146
+ embed_dim: output dimension for each position
147
+ pos: a list of positions to be encoded: size (M,)
148
+ out: (M, D)
149
+ """
150
+ assert embed_dim % 2 == 0
151
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
152
+ omega /= embed_dim / 2.0
153
+ omega = 1.0 / 10000**omega # (D/2,)
154
+
155
+ pos = pos.reshape(-1) # (M,)
156
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
157
+
158
+ emb_sin = np.sin(out) # (M, D/2)
159
+ emb_cos = np.cos(out) # (M, D/2)
160
+
161
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
162
+ return emb
163
+
164
+
165
+ def interpolate_pos_embed_internvideo2(checkpoint_model, model, orig_t_size = 8):
166
+ # interpolate position embedding
167
+ for pos_name in ['pos_embed', 'clip_pos_embed']:
168
+ if pos_name in checkpoint_model:
169
+ pos_embed_checkpoint = checkpoint_model[pos_name]
170
+ embedding_size = pos_embed_checkpoint.shape[-1] # channel dim
171
+ num_patches = model.patch_embed.num_patches #
172
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches # 0/1
173
+
174
+ # we use 8 frames for pretraining
175
+ # new_t_size = args.num_frames * args.num_segments // model.patch_embed.tubelet_size
176
+ new_t_size = model.num_frames // model.tubelet_size
177
+ # height (== width) for the checkpoint position embedding
178
+ orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(orig_t_size)) ** 0.5)
179
+ # height (== width) for the new position embedding
180
+ new_size = int((num_patches // (new_t_size))** 0.5)
181
+
182
+ # class_token and dist_token are kept unchanged
183
+ if orig_t_size != new_t_size:
184
+ logger.info(f"Temporal interpolate from {orig_t_size} to {new_t_size} ({pos_name})")
185
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
186
+ # only the position tokens are interpolated
187
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
188
+ # B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
189
+ pos_tokens = pos_tokens.view(1, orig_t_size, -1, embedding_size)
190
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, orig_t_size)
191
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=new_t_size, mode='linear')
192
+ pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
193
+ pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
194
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
195
+ checkpoint_model[pos_name] = new_pos_embed
196
+ pos_embed_checkpoint = new_pos_embed
197
+
198
+ # class_token and dist_token are kept unchanged
199
+ if orig_size != new_size:
200
+ logger.info(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size} ({pos_name})")
201
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
202
+ # only the position tokens are interpolated
203
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
204
+ # B, L, C -> BT, H, W, C -> BT, C, H, W
205
+ pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
206
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
207
+ pos_tokens = torch.nn.functional.interpolate(
208
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
209
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
210
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
211
+ pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
212
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
213
+ checkpoint_model[pos_name] = new_pos_embed
214
+
215
+
216
+ if 'pos_embed_spatial' in checkpoint_model or 'pos_embed_temporal' in checkpoint_model:
217
+ raise NotImplementedError
218
+
219
+ def interpolate_pos_embed_internvideo2_new(checkpoint_model, model, orig_t_size = 8):
220
+ pos_names = []
221
+ for k in checkpoint_model.keys():
222
+ if ('pos_embed' in k or 'clip_pos_embed' in k) and 'img_pos_embed' not in k: # NOTE 暂时不插值img_pos,高分辨率时可能需要再加
223
+ pos_names.append(k)
224
+
225
+ logger.info(f"pos names list for interpolating: {pos_names}")
226
+
227
+ assert len(pos_names) > 0, checkpoint_model.keys()
228
+
229
+ if 'pos_embed_spatial' in checkpoint_model.keys() or 'pos_embed_temporal' in checkpoint_model.keys():
230
+ raise NotImplementedError
231
+
232
+ # interpolate position embedding
233
+ for pos_name in pos_names:
234
+
235
+ pos_embed_checkpoint = checkpoint_model[pos_name]
236
+ embedding_size = pos_embed_checkpoint.shape[-1] # channel dim
237
+ num_patches = model.patch_embed.num_patches #
238
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches # 0/1
239
+
240
+ # we use 8 frames for pretraining
241
+ # new_t_size = args.num_frames * args.num_segments // model.patch_embed.tubelet_size
242
+ new_t_size = model.num_frames // model.tubelet_size
243
+ # height (== width) for the checkpoint position embedding
244
+ orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(orig_t_size)) ** 0.5)
245
+ # height (== width) for the new position embedding
246
+ new_size = int((num_patches // (new_t_size))** 0.5)
247
+
248
+ # class_token and dist_token are kept unchanged
249
+ if orig_t_size != new_t_size:
250
+ logger.info(f"Temporal interpolate from {orig_t_size} to {new_t_size} ({pos_name})")
251
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
252
+ # only the position tokens are interpolated
253
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
254
+ # B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
255
+ pos_tokens = pos_tokens.view(1, orig_t_size, -1, embedding_size)
256
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, orig_t_size)
257
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=new_t_size, mode='linear')
258
+ pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
259
+ pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
260
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
261
+ checkpoint_model[pos_name] = new_pos_embed
262
+ pos_embed_checkpoint = new_pos_embed
263
+
264
+ # class_token and dist_token are kept unchanged
265
+ if orig_size != new_size:
266
+ logger.info(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size} ({pos_name})")
267
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
268
+ # only the position tokens are interpolated
269
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
270
+ # B, L, C -> BT, H, W, C -> BT, C, H, W
271
+ pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
272
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
273
+ pos_tokens = torch.nn.functional.interpolate(
274
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
275
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
276
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
277
+ pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
278
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
279
+ checkpoint_model[pos_name] = new_pos_embed
280
+
281
+
282
+
283
+ def interpolate_pos_embed(checkpoint_model, model, orig_t_size=4, pos_name='vision_encoder.pos_embed'):
284
+ if pos_name in checkpoint_model:
285
+ pos_embed_checkpoint = checkpoint_model[pos_name]
286
+ embedding_size = pos_embed_checkpoint.shape[-1] # channel dim
287
+ num_patches = model.patch_embed.num_patches #
288
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches # 0/1
289
+
290
+ # we use 4 frames for pretraining
291
+ new_t_size = model.T
292
+ # height (== width) for the checkpoint position embedding
293
+ orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(orig_t_size)) ** 0.5)
294
+ # height (== width) for the new position embedding
295
+ new_size = int((num_patches // (new_t_size))** 0.5)
296
+
297
+ # class_token and dist_token are kept unchanged
298
+ if orig_t_size != new_t_size:
299
+ print(f"Temporal interpolate from {orig_t_size} to {new_t_size} ({pos_name})")
300
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
301
+ # only the position tokens are interpolated
302
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
303
+ # B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
304
+ pos_tokens = pos_tokens.view(1, orig_t_size, -1, embedding_size)
305
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, orig_t_size)
306
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=new_t_size, mode='linear')
307
+ pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
308
+ pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
309
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
310
+ checkpoint_model[pos_name] = new_pos_embed
311
+ pos_embed_checkpoint = new_pos_embed
312
+
313
+ # class_token and dist_token are kept unchanged
314
+ if orig_size != new_size:
315
+ print(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size} ({pos_name})")
316
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
317
+ # only the position tokens are interpolated
318
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
319
+ # B, L, C -> BT, H, W, C -> BT, C, H, W
320
+ pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
321
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
322
+ pos_tokens = torch.nn.functional.interpolate(
323
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
324
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
325
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
326
+ pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
327
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
328
+ checkpoint_model[pos_name] = new_pos_embed
329
+ else:
330
+ raise NotImplementedError
331
+
332
+
333
+
334
+ class CrossAttention(nn.Module):
335
+ def __init__(
336
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
337
+ proj_drop=0., attn_head_dim=None, out_dim=None):
338
+ super().__init__()
339
+ if out_dim is None:
340
+ out_dim = dim
341
+ self.num_heads = num_heads
342
+ head_dim = dim // num_heads
343
+ if attn_head_dim is not None:
344
+ head_dim = attn_head_dim
345
+ all_head_dim = head_dim * self.num_heads
346
+ self.scale = qk_scale or head_dim ** -0.5
347
+ assert all_head_dim == dim
348
+
349
+ self.q = nn.Linear(dim, all_head_dim, bias=False)
350
+ self.k = nn.Linear(dim, all_head_dim, bias=False)
351
+ self.v = nn.Linear(dim, all_head_dim, bias=False)
352
+
353
+ if qkv_bias:
354
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
355
+ self.k_bias = nn.Parameter(torch.zeros(all_head_dim))
356
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
357
+ else:
358
+ self.q_bias = None
359
+ self.k_bias = None
360
+ self.v_bias = None
361
+
362
+ self.attn_drop = nn.Dropout(attn_drop)
363
+ self.proj = nn.Linear(all_head_dim, out_dim)
364
+ self.proj_drop = nn.Dropout(proj_drop)
365
+
366
+ def forward(self, x, k=None, v=None):
367
+ B, N, C = x.shape
368
+ N_k = k.shape[1]
369
+ N_v = v.shape[1]
370
+
371
+ q_bias, k_bias, v_bias = None, None, None
372
+ if self.q_bias is not None:
373
+ q_bias = self.q_bias
374
+ k_bias = self.k_bias
375
+ v_bias = self.v_bias
376
+
377
+ q = F.linear(input=x, weight=self.q.weight, bias=q_bias)
378
+ q = q.reshape(B, N, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0) # (B, N_head, N_q, dim)
379
+
380
+ k = F.linear(input=k, weight=self.k.weight, bias=k_bias)
381
+ k = k.reshape(B, N_k, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
382
+
383
+ v = F.linear(input=v, weight=self.v.weight, bias=v_bias)
384
+ v = v.reshape(B, N_v, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
385
+
386
+ q = q * self.scale
387
+ attn = (q @ k.transpose(-2, -1)) # (B, N_head, N_q, N_k)
388
+
389
+ attn = attn.softmax(dim=-1)
390
+ attn = self.attn_drop(attn)
391
+
392
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
393
+ x = self.proj(x)
394
+ x = self.proj_drop(x)
395
+
396
+ return x
397
+
398
+
399
+ class AttentiveBlock(nn.Module):
400
+
401
+ def __init__(self, dim, num_heads, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
402
+ drop_path=0., norm_layer=nn.LayerNorm, attn_head_dim=None, out_dim=None):
403
+ super().__init__()
404
+
405
+ self.norm1_q = norm_layer(dim)
406
+ self.norm1_k = norm_layer(dim)
407
+ self.norm1_v = norm_layer(dim)
408
+ self.cross_attn = CrossAttention(
409
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop,
410
+ proj_drop=drop, attn_head_dim=attn_head_dim, out_dim=out_dim)
411
+
412
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
413
+
414
+ def forward(self, x_q, x_kv, pos_q, pos_k, bool_masked_pos, rel_pos_bias=None):
415
+ x_q = self.norm1_q(x_q + pos_q)
416
+ x_k = self.norm1_k(x_kv + pos_k)
417
+ x_v = self.norm1_v(x_kv)
418
+ x = self.cross_attn(x_q, k=x_k, v=x_v)
419
+
420
+ return x
421
+
422
+
423
+ class AttentionPoolingBlock(AttentiveBlock):
424
+
425
+ def forward(self, x):
426
+ x_q = x.mean(1, keepdim=True)
427
+ x_kv, pos_q, pos_k = x, 0, 0
428
+ x = super().forward(x_q, x_kv, pos_q, pos_k, bool_masked_pos=None, rel_pos_bias=None)
429
+ x = x.squeeze(1)
430
+ return x
431
+
432
+
433
+ class RMSNorm(nn.Module):
434
+ def __init__(self, hidden_size, eps=1e-6):
435
+ super().__init__()
436
+ self.weight = nn.Parameter(torch.ones(hidden_size))
437
+ self.variance_epsilon = eps
438
+
439
+ def forward(self, hidden_states):
440
+ input_dtype = hidden_states.dtype
441
+ hidden_states = hidden_states.to(torch.float32)
442
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
443
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
444
+ return self.weight * hidden_states.to(input_dtype)
445
+
446
+
447
+ class Attention(nn.Module):
448
+ def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., use_flash_attn=False,
449
+ causal=False, norm_layer=nn.LayerNorm, qk_normalization=False, use_fused_rmsnorm=False):
450
+ super().__init__()
451
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
452
+ self.num_heads = num_heads
453
+ head_dim = dim // num_heads
454
+ self.scale = head_dim ** -0.5
455
+
456
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
457
+ self.attn_drop = nn.Dropout(attn_drop)
458
+ self.proj = nn.Linear(dim, dim)
459
+ self.proj_drop = nn.Dropout(proj_drop)
460
+
461
+ self.use_flash_attn = use_flash_attn
462
+ if use_flash_attn:
463
+ self.causal = causal
464
+ self.inner_attn = FlashAttention(attention_dropout=attn_drop)
465
+
466
+ self.qk_normalization = qk_normalization
467
+ self.q_norm = norm_layer(dim) if qk_normalization else nn.Identity()
468
+ self.k_norm = norm_layer(dim) if qk_normalization else nn.Identity()
469
+ self.use_fused_rmsnorm = use_fused_rmsnorm
470
+
471
+ def _naive_attn(self, x):
472
+ B, N, C = x.shape
473
+ # print(x.shape, torch.cuda.memory_allocated(), torch.cuda.memory_allocated())
474
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
475
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
476
+
477
+ if self.qk_normalization:
478
+ B_, H_, N_, D_ = q.shape
479
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
480
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
481
+
482
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
483
+ # attn = attn - attn.max(-1)[0].unsqueeze(-1) # in case of overflow for fp16
484
+ attn = attn.softmax(dim=-1)
485
+ attn = self.attn_drop(attn)
486
+ # print(torch.cuda.memory_allocated(), torch.cuda.memory_allocated())
487
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
488
+ # print(f"\033[31m这{x.device}是{self.proj.weight.device} {self.proj.bias.device}\033[0m")
489
+ # print(f"\033[31m类型{x.dtype}是{self.proj.weight.dtype} {self.proj.bias.dtype}\033[0m")
490
+ x = self.proj(x)
491
+ x = self.proj_drop(x)
492
+ return x
493
+
494
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
495
+
496
+ qkv = self.qkv(x)
497
+ qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads)
498
+
499
+ if self.qk_normalization:
500
+ q, k, v = qkv.unbind(2)
501
+ if self.use_fused_rmsnorm:
502
+ q = self.q_norm(q.flatten(-2, -1))[0].view(q.shape)
503
+ k = self.k_norm(k.flatten(-2, -1))[0].view(k.shape)
504
+ else:
505
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
506
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
507
+ qkv = torch.stack([q, k, v], dim=2)
508
+
509
+ context, _ = self.inner_attn(
510
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=self.causal
511
+ )
512
+ outs = self.proj(rearrange(context, "b s h d -> b s (h d)"))
513
+ outs = self.proj_drop(outs)
514
+ return outs
515
+
516
+ def forward(self, x):
517
+ x = self._naive_attn(x) if not self.use_flash_attn else self._flash_attn(x)
518
+ return x
519
+
520
+
521
+ class Mlp(nn.Module):
522
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks
523
+ """
524
+
525
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU,
526
+ bias=True, drop=0.):
527
+ super().__init__()
528
+ out_features = out_features or in_features
529
+ hidden_features = hidden_features or in_features
530
+ bias = to_2tuple(bias)
531
+ drop_probs = to_2tuple(drop)
532
+
533
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0])
534
+ self.act = act_layer()
535
+ self.drop1 = nn.Dropout(drop_probs[0])
536
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1])
537
+ self.drop2 = nn.Dropout(drop_probs[1])
538
+
539
+ def forward(self, x):
540
+ x = self.fc1(x)
541
+ x = self.act(x)
542
+ x = self.drop1(x)
543
+ x = self.fc2(x)
544
+ x = self.drop2(x)
545
+ return x
546
+
547
+
548
+ class Block(nn.Module):
549
+
550
+ def __init__(
551
+ self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., init_values=None,
552
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flash_attn=False, use_fused_mlp=False,
553
+ fused_mlp_heuristic=1, with_cp=False, qk_normalization=False, layerscale_no_force_fp32=False,
554
+ use_fused_rmsnorm=False):
555
+ super().__init__()
556
+
557
+ self.norm1 = norm_layer(dim)
558
+ self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
559
+ use_flash_attn=use_flash_attn, causal=False, norm_layer=norm_layer,
560
+ qk_normalization=qk_normalization,
561
+ use_fused_rmsnorm=use_fused_rmsnorm)
562
+ self.ls1 = nn.Parameter(init_values * torch.ones(dim))
563
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
564
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
565
+
566
+ self.norm2 = norm_layer(dim)
567
+ mlp_hidden_dim = int(dim * mlp_ratio)
568
+ if use_fused_mlp:
569
+ self.mlp = FusedMLP(in_features=dim, hidden_features=mlp_hidden_dim, heuristic=fused_mlp_heuristic)
570
+ else:
571
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
572
+ self.ls2 = nn.Parameter(init_values * torch.ones(dim))
573
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
574
+
575
+ self.with_cp = with_cp
576
+ self.use_fused_rmsnorm = use_fused_rmsnorm
577
+
578
+ def forward(self, x, residual=None):
579
+
580
+ def _inner_forward(x, residual=None):
581
+ if self.use_fused_rmsnorm:
582
+ x, residual = self.norm1(x, residual)
583
+ x = self.drop_path1(self.ls1 * self.attn(x) )
584
+ x, residual = self.norm2(x, residual)
585
+ x = self.drop_path2(self.ls2 * self.mlp(x) )
586
+ return x, residual
587
+ else:
588
+ assert residual is None
589
+ x = x + self.drop_path1(self.ls1 * self.attn(self.norm1(x)))
590
+ x = x + self.drop_path2(self.ls2 * self.mlp(self.norm2(x)))
591
+ return x
592
+
593
+ if self.with_cp:
594
+ # print(f"\033[31m use_checkpoint [0m")
595
+ return checkpoint.checkpoint(_inner_forward, x, residual)
596
+ else:
597
+ return _inner_forward(x, residual=residual)
598
+
599
+
600
+ class PatchEmbed(nn.Module):
601
+ """ 3D Image to Patch Embedding
602
+ """
603
+
604
+ def __init__(
605
+ self, img_size=224, patch_size=16, in_chans=3, embed_dim=768,
606
+ num_frames=8, tubelet_size=1, norm_layer=None
607
+ ):
608
+ super().__init__()
609
+ img_size = to_2tuple(img_size)
610
+ patch_size = to_2tuple(patch_size)
611
+ self.tubelet_size = tubelet_size
612
+ self.img_size = img_size
613
+ self.patch_size = patch_size
614
+ self.grid_size = (
615
+ num_frames // tubelet_size,
616
+ img_size[0] // patch_size[0],
617
+ img_size[1] // patch_size[1]
618
+ ) # (T, H, W)
619
+ self.num_patches = self.grid_size[0] * self.grid_size[1] * self.grid_size[2]
620
+ self.num_img_patches = self.grid_size[1] * self.grid_size[2]
621
+
622
+ self.proj = nn.Conv3d(
623
+ in_channels=in_chans, out_channels=embed_dim,
624
+ kernel_size=(tubelet_size, patch_size[0], patch_size[1]),
625
+ stride=(tubelet_size, patch_size[0], patch_size[1])
626
+ )
627
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
628
+
629
+ def forward(self, x):
630
+ x = self.proj(x)
631
+ x = x.flatten(3).permute(0, 2, 3, 1) # B x C x T x HW => B x T x HW x C
632
+ x = self.norm(x)
633
+ return x
634
+
635
+ class PretrainVisionTransformer_clean(nn.Module):
636
+ def __init__(
637
+ self,
638
+ in_chans: int = 3,
639
+ patch_size: int = 14,
640
+ img_size: int = 224,
641
+ qkv_bias: bool = False, # follow internvl_clip to set False
642
+ drop_path_rate: float = 0.25, # may need ablation
643
+ embed_dim: int = 1408,
644
+ num_heads: int = 16,
645
+ mlp_ratio: float = 48/11,
646
+ init_values: float = 1e-5, # may need ablation
647
+ qk_normalization: bool = True,
648
+ depth: int = 40,
649
+ use_flash_attn: bool = True,
650
+ use_fused_rmsnorm: bool = True,
651
+ use_fused_mlp: bool = True,
652
+ fused_mlp_heuristic: int = 1,
653
+ attn_pool_num_heads: int = 16,
654
+ clip_embed_dim: int = 768,
655
+ layerscale_no_force_fp32: bool = False, # whether True for training?
656
+ num_frames: int = 8,
657
+ tubelet_size: int = 1,
658
+ sep_pos_embed: bool = False,
659
+ sep_image_video_pos_embed: bool = False,
660
+ use_checkpoint: bool = False,
661
+ checkpoint_num: int = 0,
662
+ # for unmasked teacher
663
+ x_vis_return_idx=-1,
664
+ x_vis_only=False
665
+ ):
666
+ super().__init__()
667
+
668
+ self.num_frames = num_frames
669
+ self.tubelet_size = tubelet_size
670
+ assert use_flash_attn == use_fused_rmsnorm == use_fused_mlp, 'use_flash_attn, use_fused_rmsnorm and use_fused_mlp should be consistent'
671
+
672
+ self.use_flash_attn = use_flash_attn
673
+ self.embed_dim = embed_dim
674
+
675
+ logger.info(f"Origin depth: {depth}")
676
+ depth = depth + x_vis_return_idx + 1
677
+ logger.info(f"New depth: {depth}")
678
+ self.depth = depth
679
+
680
+ self.x_vis_only = x_vis_only
681
+
682
+ if use_fused_rmsnorm:
683
+ norm_layer_for_blocks = partial(DropoutAddRMSNorm, eps=1e-6, prenorm=True)
684
+ else:
685
+ norm_layer_for_blocks = partial(RMSNorm, eps=1e-6)
686
+ self.norm_layer_for_blocks = norm_layer_for_blocks
687
+ self.patch_embed = PatchEmbed(
688
+ img_size, patch_size, in_chans, embed_dim,
689
+ num_frames=num_frames, tubelet_size=tubelet_size,
690
+ )
691
+ num_patches = self.patch_embed.num_patches
692
+ num_img_patches = self.patch_embed.num_img_patches
693
+ # print(f"num_patches: {num_patches}, num_img_patches: {num_img_patches}")
694
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
695
+
696
+ # stolen from https://github.com/facebookresearch/mae_st/blob/dc072aaaf640d06892e23a33b42223a994efe272/models_vit.py#L65-L73C17
697
+ self.sep_pos_embed = sep_pos_embed
698
+ self.sep_image_video_pos_embed = sep_image_video_pos_embed
699
+ if sep_pos_embed:
700
+ raise NotImplementedError
701
+ else:
702
+ if sep_image_video_pos_embed:
703
+ logger.info("Use joint position embedding, for image and video we use different pos_embed.")
704
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
705
+ self.img_pos_embed = nn.Parameter(torch.zeros(1, num_img_patches + 1, embed_dim))
706
+ else:
707
+ logger.info("Use joint position embedding, for image and video we use same pos_embed.")
708
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
709
+
710
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
711
+ # choose which layer to use checkpoint
712
+ with_cp_list = [False] * depth
713
+ if use_checkpoint:
714
+ for idx in range(depth):
715
+ if idx < checkpoint_num:
716
+ with_cp_list[idx] = True
717
+ logger.info(f"Droppath rate: {dpr}")
718
+ logger.info(f"Checkpoint list: {with_cp_list}")
719
+
720
+ self.blocks = nn.ModuleList([
721
+ Block(embed_dim, num_heads, mlp_ratio, qkv_bias=qkv_bias,
722
+ norm_layer=norm_layer_for_blocks,
723
+ drop_path=dpr[i], init_values=init_values, attn_drop=0.,
724
+ use_flash_attn=use_flash_attn, use_fused_mlp=use_fused_mlp,
725
+ fused_mlp_heuristic=fused_mlp_heuristic,
726
+ with_cp=with_cp_list[i],
727
+ qk_normalization=qk_normalization,
728
+ layerscale_no_force_fp32=layerscale_no_force_fp32,
729
+ use_fused_rmsnorm=use_fused_rmsnorm)
730
+ for i in range(depth)])
731
+
732
+ if not self.x_vis_only:
733
+ self.clip_projector = AttentionPoolingBlock(
734
+ dim=embed_dim, num_heads=attn_pool_num_heads, qkv_bias=True, qk_scale=None,
735
+ drop=0., attn_drop=0., norm_layer=partial(nn.LayerNorm, eps=1e-5), out_dim=clip_embed_dim)
736
+
737
+
738
+
739
+ self.init_pos_embed()
740
+ # trunc_normal_(self.cls_token, std=.02)
741
+ # self.apply(self._init_weights)
742
+ # self.fix_init_weight()
743
+
744
+ def init_pos_embed(self):
745
+ logger.info("Init pos_embed from sincos pos_embed")
746
+ if self.sep_pos_embed:
747
+ raise NotImplementedError
748
+ else:
749
+ pos_embed = get_3d_sincos_pos_embed(
750
+ self.pos_embed.shape[-1],
751
+ self.patch_embed.grid_size[1], # height & weight
752
+ self.patch_embed.grid_size[0], # t_size
753
+ cls_token=True
754
+ )
755
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
756
+
757
+ if self.sep_image_video_pos_embed:
758
+ img_pos_embed = get_3d_sincos_pos_embed(
759
+ self.pos_embed.shape[-1],
760
+ self.patch_embed.grid_size[1], # height & weight
761
+ 1,
762
+ cls_token=True
763
+ )
764
+ self.img_pos_embed.data.copy_(torch.from_numpy(img_pos_embed).float().unsqueeze(0))
765
+
766
+
767
+ def _init_weights(self, m):
768
+ if isinstance(m, nn.Linear):
769
+ trunc_normal_(m.weight, std=.02)
770
+ if isinstance(m, nn.Linear) and m.bias is not None:
771
+ nn.init.constant_(m.bias, 0)
772
+ elif isinstance(m, nn.LayerNorm):
773
+ nn.init.constant_(m.bias, 0)
774
+ nn.init.constant_(m.weight, 1.0)
775
+
776
+ def fix_init_weight(self):
777
+ def rescale(param, layer_id):
778
+ param.div_(math.sqrt(2.0 * layer_id))
779
+
780
+ for layer_id, layer in enumerate(self.blocks):
781
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
782
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
783
+
784
+ @property
785
+ def dtype(self):
786
+ return self.patch_embed.proj.weight.dtype
787
+
788
+ def get_num_layers(self):
789
+ return len(self.blocks)
790
+
791
+ @torch.jit.ignore
792
+ def no_weight_decay(self):
793
+ return {
794
+ 'pos_embed',
795
+ 'pos_embed_spatial',
796
+ 'pos_embed_temporal',
797
+ 'pos_embed_cls',
798
+ 'img_pos_embed',
799
+ 'cls_token'
800
+ }
801
+
802
+ def expand_pos_embed(self, pos_embed, new_t_size, L, use_vitar_fuzzing=False):
803
+ '''
804
+ @param:
805
+ pos_embed: original pos_embed, (1, T*L + 1, embed_dim)
806
+ T: frames
807
+ L: w * h
808
+ method: interpolation method
809
+ '''
810
+ pos_embed_checkpoint = pos_embed
811
+ embedding_size = pos_embed_checkpoint.shape[-1]
812
+ num_extra_tokens = 1
813
+
814
+ # height (== width) for the checkpoint position embedding
815
+ orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(self.num_frames / self.patch_embed.tubelet_size)) ** 0.5)
816
+ # height (== width) for the new position embedding
817
+ new_size = int(L ** 0.5)
818
+
819
+ # class_token and dist_token are kept unchanged
820
+ if self.num_frames != new_t_size:
821
+ logger.info(f"Temporal interpolate from {self.num_frames} to {new_t_size} ")
822
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
823
+ # only the position tokens are interpolated
824
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
825
+ # B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
826
+ pos_tokens = pos_tokens.view(1, self.num_frames, -1, embedding_size)
827
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, self.num_frames)
828
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens.cpu(), size=new_t_size, mode='linear').cuda()
829
+ pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
830
+ pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
831
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
832
+ pos_embed_checkpoint = new_pos_embed
833
+
834
+ # class_token and dist_token are kept unchanged
835
+ if orig_size != new_size:
836
+ logger.info(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size}")
837
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
838
+ # only the position tokens are interpolated
839
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
840
+ # B, L, C -> BT, H, W, C -> BT, C, H, W
841
+ pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
842
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
843
+ pos_tokens = torch.nn.functional.interpolate(
844
+ pos_tokens.cpu(), size=(new_size, new_size), mode='bicubic', align_corners=False).cuda()
845
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
846
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
847
+ pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
848
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
849
+
850
+ if use_vitar_fuzzing:
851
+ ...
852
+
853
+ return new_pos_embed
854
+
855
+ # @torch.cuda.amp.autocast(enabled=False)
856
+ def forward(self, x, mask=None, use_image=False):
857
+ x = self.patch_embed(x.type(self.dtype))
858
+ # print(f"x.shape: {x.shape} x.dtype: {x.dtype}, model.dtype: {self.dtype}")
859
+ B, T, L, C = x.shape # T: temporal; L: spatial
860
+ x = x.view([B, T * L, C])
861
+
862
+ # append cls token
863
+ cls_tokens = self.cls_token.expand(B, -1, -1)
864
+ x = torch.cat((cls_tokens, x), dim=1)
865
+
866
+ # add pos_embed
867
+ if self.sep_pos_embed:
868
+ raise NotImplementedError
869
+ else:
870
+ if use_image:
871
+ if self.sep_image_video_pos_embed:
872
+ pos_embed = self.img_pos_embed
873
+ else:
874
+ # (1, num_img_patches + 1, embed_dim)
875
+ # print('origin pos_embed.shape:', self.pos_embed.shape)
876
+ cls_pos_embed = self.pos_embed[:, 0:1, :]
877
+ # print('cls_pos_embed.shape:', cls_pos_embed.shape)
878
+
879
+ img_pos_embed = self.pos_embed[:, 1:, :].view(1, self.num_frames, self.patch_embed.num_patches // self.num_frames, self.embed_dim).mean(dim=1)
880
+ # print('img_pos_embed.shape:', img_pos_embed.shape)
881
+
882
+ pos_embed = torch.cat([cls_pos_embed, img_pos_embed], dim=1)
883
+ # print('final img_pos_embed.shape:', pos_embed.shape)
884
+ else:
885
+ pos_embed = self.pos_embed
886
+
887
+ if pos_embed[0].shape != x[0].shape:
888
+ # print(f'pos embed shape {pos_embed.shape} does not match x[0].shape {x[0].shape}')
889
+ pos_embed = self.expand_pos_embed(pos_embed, T, L) # can accelerate here
890
+ assert pos_embed[0].shape == x[0].shape, f'pos embed shape: {pos_embed.shape} not match x[0].shape {x[0].shape}'
891
+ # print("pos_embed.shape:", pos_embed.shape)
892
+ x = x + pos_embed
893
+
894
+ # mask tokens, ~mask means visible
895
+ if mask is not None:
896
+ x = x[~mask].reshape(B, -1, C)
897
+ else:
898
+ x = x.reshape(B, -1, C)
899
+
900
+ residual = None
901
+
902
+ for idx, blk in enumerate(self.blocks):
903
+ if isinstance(x, tuple) and len(x) == 2:
904
+ x, residual = x
905
+ x = blk(x, residual=residual)
906
+
907
+ if isinstance(x, tuple) and len(x) == 2:
908
+ x, residual = x
909
+ if residual is not None:
910
+ x = x + residual
911
+
912
+ x_vis = x
913
+ if self.x_vis_only:
914
+ return x_vis
915
+ else:
916
+ x_pool_vis = self.clip_projector(x_vis)
917
+ return x_vis, x_pool_vis, None, None
918
+
919
+
920
+ def pretrain_internvideo2_giant_patch14_224_clean(config):
921
+ model = PretrainVisionTransformer_clean(
922
+ in_chans=3, img_size=224, patch_size=14,
923
+ embed_dim=1408, depth=40, num_heads=16, mlp_ratio=48/11,
924
+ attn_pool_num_heads=16, qkv_bias=False,
925
+ drop_path_rate=0.25,
926
+ init_values=0.00001,
927
+ qk_normalization=True,
928
+ use_flash_attn=config.vision_encoder.get('use_flash_attn', False),
929
+ use_fused_rmsnorm=config.vision_encoder.get('use_fused_rmsnorm', False),
930
+ use_fused_mlp=config.vision_encoder.get('use_fused_mlp', False),
931
+ fused_mlp_heuristic=1,
932
+ layerscale_no_force_fp32=True,
933
+ num_frames=config.vision_encoder.num_frames,
934
+ tubelet_size=config.vision_encoder.tubelet_size,
935
+ sep_pos_embed=False,
936
+ sep_image_video_pos_embed=config.vision_encoder.sep_image_video_pos_embed,
937
+ use_checkpoint=config.vision_encoder.use_checkpoint,
938
+ checkpoint_num=config.vision_encoder.checkpoint_num,
939
+ x_vis_return_idx=config.vision_encoder.x_vis_return_idx,
940
+ x_vis_only=config.vision_encoder.x_vis_only,
941
+ )
942
+
943
+ if config.vision_encoder.pretrained is not None:
944
+ logger.info(f"Loading pretrained weights from {config.vision_encoder.pretrained}")
945
+ state_dict = torch.load(config.vision_encoder.pretrained, map_location='cpu')
946
+ interpolate_pos_embed_internvideo2(state_dict, model, orig_t_size=4) # NOTE 8f for stage1
947
+ message = model.load_state_dict(state_dict, strict=False)
948
+ logger.info(message)
949
+ else:
950
+ logger.info("No pretrained weights!!!")
951
+ return model
952
+
953
+
954
+
955
+ def pretrain_internvideo2_6b_patch14_224_clean(config):
956
+ model = PretrainVisionTransformer_clean(
957
+ in_chans=3, img_size=224, patch_size=14,
958
+ embed_dim=3200, depth=48, num_heads=25, mlp_ratio=4,
959
+ clip_embed_dim=config.vision_encoder.clip_embed_dim,
960
+ attn_pool_num_heads=16, qkv_bias=False,
961
+ drop_path_rate=0.3,
962
+ init_values=0.00001,
963
+ qk_normalization=True,
964
+ use_flash_attn=config.vision_encoder.get('use_flash_attn', True),
965
+ use_fused_rmsnorm=config.vision_encoder.get('use_fused_rmsnorm', True),
966
+ use_fused_mlp=config.vision_encoder.get('use_fused_mlp', True),
967
+ fused_mlp_heuristic=1,
968
+ layerscale_no_force_fp32=True,
969
+ num_frames=config.vision_encoder.num_frames,
970
+ tubelet_size=config.vision_encoder.tubelet_size,
971
+ sep_pos_embed=False,
972
+ sep_image_video_pos_embed=config.vision_encoder.sep_image_video_pos_embed,
973
+ use_checkpoint=config.vision_encoder.use_checkpoint,
974
+ checkpoint_num=config.vision_encoder.checkpoint_num,
975
+ x_vis_return_idx=config.vision_encoder.x_vis_return_idx,
976
+ x_vis_only=config.vision_encoder.x_vis_only
977
+ )
978
+
979
+ if config.vision_encoder.pretrained is not None:
980
+ logger.info(f"Loading pretrained weights from {config.vision_encoder.pretrained}")
981
+ state_dict = torch.load(config.vision_encoder.pretrained, map_location='cpu')
982
+ interpolate_pos_embed_internvideo2(state_dict, model, orig_t_size=8) # NOTE 8f for stage1
983
+ msg = model.load_state_dict(state_dict, strict=False)
984
+ logger.info(msg)
985
+ else:
986
+ logger.info("No pretrained weights!!!")
987
+ return model
modeling_qformer.py ADDED
@@ -0,0 +1,1263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * Copyright (c) 2023, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ """
10
+ import logging
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple, Dict, Any
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from timm.models.layers import drop_path
25
+ from transformers.activations import ACT2FN
26
+ from transformers.file_utils import (
27
+ ModelOutput,
28
+ )
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import (
41
+ PreTrainedModel,
42
+ apply_chunking_to_forward,
43
+ find_pruneable_heads_and_indices,
44
+ prune_linear_layer,
45
+ )
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+ import logging
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ class BertEmbeddings(nn.Module):
53
+ """Construct the embeddings from word and position embeddings."""
54
+
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.word_embeddings = nn.Embedding(
58
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
59
+ )
60
+ self.position_embeddings = nn.Embedding(
61
+ config.max_position_embeddings, config.hidden_size
62
+ )
63
+
64
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
65
+ # any TensorFlow checkpoint file
66
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
67
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
68
+
69
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
70
+ self.register_buffer(
71
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
72
+ )
73
+ self.position_embedding_type = getattr(
74
+ config, "position_embedding_type", "absolute"
75
+ )
76
+
77
+ self.config = config
78
+
79
+ def forward(
80
+ self,
81
+ input_ids=None,
82
+ position_ids=None,
83
+ query_embeds=None,
84
+ past_key_values_length=0,
85
+ ):
86
+ if input_ids is not None:
87
+ seq_length = input_ids.size()[1]
88
+ else:
89
+ seq_length = 0
90
+
91
+ if position_ids is None:
92
+ position_ids = self.position_ids[
93
+ :, past_key_values_length : seq_length + past_key_values_length
94
+ ].clone()
95
+
96
+ if input_ids is not None:
97
+ embeddings = self.word_embeddings(input_ids)
98
+ if self.position_embedding_type == "absolute":
99
+ position_embeddings = self.position_embeddings(position_ids)
100
+ embeddings = embeddings + position_embeddings
101
+
102
+ if query_embeds is not None:
103
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
104
+ else:
105
+ embeddings = query_embeds
106
+
107
+ embeddings = self.LayerNorm(embeddings)
108
+ embeddings = self.dropout(embeddings)
109
+ return embeddings
110
+
111
+
112
+ class BertSelfAttention(nn.Module):
113
+ def __init__(self, config, is_cross_attention):
114
+ super().__init__()
115
+ self.config = config
116
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
117
+ config, "embedding_size"
118
+ ):
119
+ raise ValueError(
120
+ "The hidden size (%d) is not a multiple of the number of attention "
121
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
122
+ )
123
+
124
+ self.num_attention_heads = config.num_attention_heads
125
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
126
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
127
+
128
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
129
+ if is_cross_attention:
130
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
131
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
132
+ else:
133
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
134
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
135
+
136
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
137
+ self.position_embedding_type = getattr(
138
+ config, "position_embedding_type", "absolute"
139
+ )
140
+ if (
141
+ self.position_embedding_type == "relative_key"
142
+ or self.position_embedding_type == "relative_key_query"
143
+ ):
144
+ self.max_position_embeddings = config.max_position_embeddings
145
+ self.distance_embedding = nn.Embedding(
146
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
147
+ )
148
+ self.save_attention = False
149
+
150
+ def save_attn_gradients(self, attn_gradients):
151
+ self.attn_gradients = attn_gradients
152
+
153
+ def get_attn_gradients(self):
154
+ return self.attn_gradients
155
+
156
+ def save_attention_map(self, attention_map):
157
+ self.attention_map = attention_map
158
+
159
+ def get_attention_map(self):
160
+ return self.attention_map
161
+
162
+ def transpose_for_scores(self, x):
163
+ new_x_shape = x.size()[:-1] + (
164
+ self.num_attention_heads,
165
+ self.attention_head_size,
166
+ )
167
+ x = x.view(*new_x_shape)
168
+ return x.permute(0, 2, 1, 3)
169
+
170
+ def forward(
171
+ self,
172
+ hidden_states,
173
+ attention_mask=None,
174
+ head_mask=None,
175
+ encoder_hidden_states=None,
176
+ encoder_attention_mask=None,
177
+ past_key_value=None,
178
+ output_attentions=False,
179
+ ):
180
+
181
+ # If this is instantiated as a cross-attention module, the keys
182
+ # and values come from an encoder; the attention mask needs to be
183
+ # such that the encoder's padding tokens are not attended to.
184
+ is_cross_attention = encoder_hidden_states is not None
185
+
186
+ if is_cross_attention:
187
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
188
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
189
+ attention_mask = encoder_attention_mask
190
+ elif past_key_value is not None:
191
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
192
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
193
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
194
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
195
+ else:
196
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
197
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
198
+
199
+ mixed_query_layer = self.query(hidden_states)
200
+
201
+ query_layer = self.transpose_for_scores(mixed_query_layer)
202
+
203
+ past_key_value = (key_layer, value_layer)
204
+
205
+ # Take the dot product between "query" and "key" to get the raw attention scores.
206
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
207
+
208
+ if (
209
+ self.position_embedding_type == "relative_key"
210
+ or self.position_embedding_type == "relative_key_query"
211
+ ):
212
+ seq_length = hidden_states.size()[1]
213
+ position_ids_l = torch.arange(
214
+ seq_length, dtype=torch.long, device=hidden_states.device
215
+ ).view(-1, 1)
216
+ position_ids_r = torch.arange(
217
+ seq_length, dtype=torch.long, device=hidden_states.device
218
+ ).view(1, -1)
219
+ distance = position_ids_l - position_ids_r
220
+ positional_embedding = self.distance_embedding(
221
+ distance + self.max_position_embeddings - 1
222
+ )
223
+ positional_embedding = positional_embedding.to(
224
+ dtype=query_layer.dtype
225
+ ) # fp16 compatibility
226
+
227
+ if self.position_embedding_type == "relative_key":
228
+ relative_position_scores = torch.einsum(
229
+ "bhld,lrd->bhlr", query_layer, positional_embedding
230
+ )
231
+ attention_scores = attention_scores + relative_position_scores
232
+ elif self.position_embedding_type == "relative_key_query":
233
+ relative_position_scores_query = torch.einsum(
234
+ "bhld,lrd->bhlr", query_layer, positional_embedding
235
+ )
236
+ relative_position_scores_key = torch.einsum(
237
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
238
+ )
239
+ attention_scores = (
240
+ attention_scores
241
+ + relative_position_scores_query
242
+ + relative_position_scores_key
243
+ )
244
+
245
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
246
+ if attention_mask is not None:
247
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
248
+ attention_scores = attention_scores + attention_mask
249
+
250
+ # Normalize the attention scores to probabilities.
251
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
252
+
253
+ if is_cross_attention and self.save_attention:
254
+ self.save_attention_map(attention_probs)
255
+ attention_probs.register_hook(self.save_attn_gradients)
256
+
257
+ # This is actually dropping out entire tokens to attend to, which might
258
+ # seem a bit unusual, but is taken from the original Transformer paper.
259
+ attention_probs_dropped = self.dropout(attention_probs)
260
+
261
+ # Mask heads if we want to
262
+ if head_mask is not None:
263
+ attention_probs_dropped = attention_probs_dropped * head_mask
264
+
265
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
266
+
267
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
268
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
269
+ context_layer = context_layer.view(*new_context_layer_shape)
270
+
271
+ outputs = (
272
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
273
+ )
274
+
275
+ outputs = outputs + (past_key_value,)
276
+ return outputs
277
+
278
+
279
+ class DropPath(nn.Module):
280
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
281
+ """
282
+ def __init__(self, drop_prob=None):
283
+ super(DropPath, self).__init__()
284
+ self.drop_prob = drop_prob
285
+
286
+ def forward(self, x):
287
+ return drop_path(x, self.drop_prob, self.training)
288
+
289
+ def extra_repr(self) -> str:
290
+ return 'p={}'.format(self.drop_prob)
291
+
292
+
293
+ class BertSelfOutput(nn.Module):
294
+ def __init__(self, config, drop_path=0.):
295
+ super().__init__()
296
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
297
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
298
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
299
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
300
+
301
+ def forward(self, hidden_states, input_tensor):
302
+ hidden_states = self.dense(hidden_states)
303
+ hidden_states = self.dropout(hidden_states)
304
+ hidden_states = self.drop_path(hidden_states)
305
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
306
+ return hidden_states
307
+
308
+
309
+ class BertAttention(nn.Module):
310
+ def __init__(self, config, is_cross_attention=False, drop_path=0.,):
311
+ super().__init__()
312
+ self.self = BertSelfAttention(config, is_cross_attention)
313
+ self.output = BertSelfOutput(config, drop_path=drop_path)
314
+ self.pruned_heads = set()
315
+
316
+ def prune_heads(self, heads):
317
+ if len(heads) == 0:
318
+ return
319
+ heads, index = find_pruneable_heads_and_indices(
320
+ heads,
321
+ self.self.num_attention_heads,
322
+ self.self.attention_head_size,
323
+ self.pruned_heads,
324
+ )
325
+
326
+ # Prune linear layers
327
+ self.self.query = prune_linear_layer(self.self.query, index)
328
+ self.self.key = prune_linear_layer(self.self.key, index)
329
+ self.self.value = prune_linear_layer(self.self.value, index)
330
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
331
+
332
+ # Update hyper params and store pruned heads
333
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
334
+ self.self.all_head_size = (
335
+ self.self.attention_head_size * self.self.num_attention_heads
336
+ )
337
+ self.pruned_heads = self.pruned_heads.union(heads)
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states,
342
+ attention_mask=None,
343
+ head_mask=None,
344
+ encoder_hidden_states=None,
345
+ encoder_attention_mask=None,
346
+ past_key_value=None,
347
+ output_attentions=False,
348
+ ):
349
+ self_outputs = self.self(
350
+ hidden_states,
351
+ attention_mask,
352
+ head_mask,
353
+ encoder_hidden_states,
354
+ encoder_attention_mask,
355
+ past_key_value,
356
+ output_attentions,
357
+ )
358
+ attention_output = self.output(self_outputs[0], hidden_states)
359
+
360
+ outputs = (attention_output,) + self_outputs[
361
+ 1:
362
+ ] # add attentions if we output them
363
+ return outputs
364
+
365
+
366
+ class BertIntermediate(nn.Module):
367
+ def __init__(self, config):
368
+ super().__init__()
369
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
370
+ if isinstance(config.hidden_act, str):
371
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
372
+ else:
373
+ self.intermediate_act_fn = config.hidden_act
374
+
375
+ def forward(self, hidden_states):
376
+ hidden_states = self.dense(hidden_states)
377
+ hidden_states = self.intermediate_act_fn(hidden_states)
378
+ return hidden_states
379
+
380
+
381
+ class BertOutput(nn.Module):
382
+ def __init__(self, config, drop_path=0.):
383
+ super().__init__()
384
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
385
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
386
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
387
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
388
+
389
+ def forward(self, hidden_states, input_tensor):
390
+ hidden_states = self.dense(hidden_states)
391
+ hidden_states = self.dropout(hidden_states)
392
+ hidden_states = self.drop_path(hidden_states)
393
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
394
+ return hidden_states
395
+
396
+
397
+ class BertLayer(nn.Module):
398
+ def __init__(self, config, layer_num):
399
+ super().__init__()
400
+ self.config = config
401
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
402
+ self.seq_len_dim = 1
403
+ drop_path = config.drop_path_list[layer_num]
404
+ self.attention = BertAttention(config, drop_path=drop_path)
405
+ self.layer_num = layer_num
406
+ if (
407
+ self.config.add_cross_attention
408
+ and layer_num % self.config.cross_attention_freq == 0
409
+ ):
410
+ self.crossattention = BertAttention(
411
+ config, is_cross_attention=self.config.add_cross_attention,
412
+ drop_path=drop_path
413
+ )
414
+ self.has_cross_attention = True
415
+ else:
416
+ self.has_cross_attention = False
417
+ self.intermediate = BertIntermediate(config)
418
+ self.output = BertOutput(config, drop_path=drop_path)
419
+
420
+ self.intermediate_query = BertIntermediate(config)
421
+ self.output_query = BertOutput(config, drop_path=drop_path)
422
+
423
+ def forward(
424
+ self,
425
+ hidden_states,
426
+ attention_mask=None,
427
+ head_mask=None,
428
+ encoder_hidden_states=None,
429
+ encoder_attention_mask=None,
430
+ past_key_value=None,
431
+ output_attentions=False,
432
+ query_length=0,
433
+ ):
434
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
435
+ self_attn_past_key_value = (
436
+ past_key_value[:2] if past_key_value is not None else None
437
+ )
438
+ self_attention_outputs = self.attention(
439
+ hidden_states,
440
+ attention_mask,
441
+ head_mask,
442
+ output_attentions=output_attentions,
443
+ past_key_value=self_attn_past_key_value,
444
+ )
445
+ attention_output = self_attention_outputs[0]
446
+ outputs = self_attention_outputs[1:-1]
447
+
448
+ present_key_value = self_attention_outputs[-1]
449
+
450
+ if query_length > 0:
451
+ query_attention_output = attention_output[:, :query_length, :]
452
+
453
+ if self.has_cross_attention:
454
+ assert (
455
+ encoder_hidden_states is not None
456
+ ), "encoder_hidden_states must be given for cross-attention layers"
457
+ cross_attention_outputs = self.crossattention(
458
+ query_attention_output,
459
+ attention_mask,
460
+ head_mask,
461
+ encoder_hidden_states,
462
+ encoder_attention_mask,
463
+ output_attentions=output_attentions,
464
+ )
465
+ query_attention_output = cross_attention_outputs[0]
466
+ outputs = (
467
+ outputs + cross_attention_outputs[1:-1]
468
+ ) # add cross attentions if we output attention weights
469
+
470
+ layer_output = apply_chunking_to_forward(
471
+ self.feed_forward_chunk_query,
472
+ self.chunk_size_feed_forward,
473
+ self.seq_len_dim,
474
+ query_attention_output,
475
+ )
476
+ if attention_output.shape[1] > query_length:
477
+ layer_output_text = apply_chunking_to_forward(
478
+ self.feed_forward_chunk,
479
+ self.chunk_size_feed_forward,
480
+ self.seq_len_dim,
481
+ attention_output[:, query_length:, :],
482
+ )
483
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
484
+ else:
485
+ layer_output = apply_chunking_to_forward(
486
+ self.feed_forward_chunk,
487
+ self.chunk_size_feed_forward,
488
+ self.seq_len_dim,
489
+ attention_output,
490
+ )
491
+ outputs = (layer_output,) + outputs
492
+
493
+ outputs = outputs + (present_key_value,)
494
+
495
+ return outputs
496
+
497
+ def feed_forward_chunk(self, attention_output):
498
+ intermediate_output = self.intermediate(attention_output)
499
+ layer_output = self.output(intermediate_output, attention_output)
500
+ return layer_output
501
+
502
+ def feed_forward_chunk_query(self, attention_output):
503
+ intermediate_output = self.intermediate_query(attention_output)
504
+ layer_output = self.output_query(intermediate_output, attention_output)
505
+ return layer_output
506
+
507
+
508
+ class BertEncoder(nn.Module):
509
+ def __init__(self, config):
510
+ super().__init__()
511
+ self.config = config
512
+ self.layer = nn.ModuleList(
513
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
514
+ )
515
+
516
+ def forward(
517
+ self,
518
+ hidden_states,
519
+ attention_mask=None,
520
+ head_mask=None,
521
+ encoder_hidden_states=None,
522
+ encoder_attention_mask=None,
523
+ past_key_values=None,
524
+ use_cache=None,
525
+ output_attentions=False,
526
+ output_hidden_states=False,
527
+ return_dict=True,
528
+ query_length=0,
529
+ ):
530
+ all_hidden_states = () if output_hidden_states else None
531
+ all_self_attentions = () if output_attentions else None
532
+ all_cross_attentions = (
533
+ () if output_attentions and self.config.add_cross_attention else None
534
+ )
535
+
536
+ next_decoder_cache = () if use_cache else None
537
+
538
+ for i in range(self.config.num_hidden_layers):
539
+ layer_module = self.layer[i]
540
+ if output_hidden_states:
541
+ all_hidden_states = all_hidden_states + (hidden_states,)
542
+
543
+ layer_head_mask = head_mask[i] if head_mask is not None else None
544
+ past_key_value = past_key_values[i] if past_key_values is not None else None
545
+
546
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
547
+
548
+ if use_cache:
549
+ logger.warn(
550
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
551
+ )
552
+ use_cache = False
553
+
554
+ def create_custom_forward(module):
555
+ def custom_forward(*inputs):
556
+ return module(
557
+ *inputs, past_key_value, output_attentions, query_length
558
+ )
559
+
560
+ return custom_forward
561
+
562
+ layer_outputs = torch.utils.checkpoint.checkpoint(
563
+ create_custom_forward(layer_module),
564
+ hidden_states,
565
+ attention_mask,
566
+ layer_head_mask,
567
+ encoder_hidden_states,
568
+ encoder_attention_mask,
569
+ )
570
+ else:
571
+ layer_outputs = layer_module(
572
+ hidden_states,
573
+ attention_mask,
574
+ layer_head_mask,
575
+ encoder_hidden_states,
576
+ encoder_attention_mask,
577
+ past_key_value,
578
+ output_attentions,
579
+ query_length,
580
+ )
581
+
582
+ hidden_states = layer_outputs[0]
583
+ if use_cache:
584
+ next_decoder_cache += (layer_outputs[-1],)
585
+ if output_attentions:
586
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
587
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
588
+
589
+ if output_hidden_states:
590
+ all_hidden_states = all_hidden_states + (hidden_states,)
591
+
592
+ if not return_dict:
593
+ return tuple(
594
+ v
595
+ for v in [
596
+ hidden_states,
597
+ next_decoder_cache,
598
+ all_hidden_states,
599
+ all_self_attentions,
600
+ all_cross_attentions,
601
+ ]
602
+ if v is not None
603
+ )
604
+ return BaseModelOutputWithPastAndCrossAttentions(
605
+ last_hidden_state=hidden_states,
606
+ past_key_values=next_decoder_cache,
607
+ hidden_states=all_hidden_states,
608
+ attentions=all_self_attentions,
609
+ cross_attentions=all_cross_attentions,
610
+ )
611
+
612
+
613
+ class BertPooler(nn.Module):
614
+ def __init__(self, config):
615
+ super().__init__()
616
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
617
+ self.activation = nn.Tanh()
618
+
619
+ def forward(self, hidden_states):
620
+ # We "pool" the model by simply taking the hidden state corresponding
621
+ # to the first token.
622
+ first_token_tensor = hidden_states[:, 0]
623
+ pooled_output = self.dense(first_token_tensor)
624
+ pooled_output = self.activation(pooled_output)
625
+ return pooled_output
626
+
627
+
628
+ class BertPredictionHeadTransform(nn.Module):
629
+ def __init__(self, config):
630
+ super().__init__()
631
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
632
+ if isinstance(config.hidden_act, str):
633
+ self.transform_act_fn = ACT2FN[config.hidden_act]
634
+ else:
635
+ self.transform_act_fn = config.hidden_act
636
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
637
+
638
+ def forward(self, hidden_states):
639
+ hidden_states = self.dense(hidden_states)
640
+ hidden_states = self.transform_act_fn(hidden_states)
641
+ hidden_states = self.LayerNorm(hidden_states)
642
+ return hidden_states
643
+
644
+
645
+ class BertLMPredictionHead(nn.Module):
646
+ def __init__(self, config):
647
+ super().__init__()
648
+ self.transform = BertPredictionHeadTransform(config)
649
+
650
+ # The output weights are the same as the input embeddings, but there is
651
+ # an output-only bias for each token.
652
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
653
+
654
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
655
+
656
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
657
+ self.decoder.bias = self.bias
658
+
659
+ def forward(self, hidden_states):
660
+ hidden_states = self.transform(hidden_states)
661
+ hidden_states = self.decoder(hidden_states)
662
+ return hidden_states
663
+
664
+
665
+ class BertOnlyMLMHead(nn.Module):
666
+ def __init__(self, config):
667
+ super().__init__()
668
+ self.predictions = BertLMPredictionHead(config)
669
+
670
+ def forward(self, sequence_output):
671
+ prediction_scores = self.predictions(sequence_output)
672
+ return prediction_scores
673
+
674
+
675
+ class BertPreTrainedModel(PreTrainedModel):
676
+ """
677
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
678
+ models.
679
+ """
680
+
681
+ config_class = BertConfig
682
+ base_model_prefix = "bert"
683
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
684
+
685
+ def _init_weights(self, module):
686
+ """Initialize the weights"""
687
+ if isinstance(module, (nn.Linear, nn.Embedding)):
688
+ # Slightly different from the TF version which uses truncated_normal for initialization
689
+ # cf https://github.com/pytorch/pytorch/pull/5617
690
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
691
+ elif isinstance(module, nn.LayerNorm):
692
+ module.bias.data.zero_()
693
+ module.weight.data.fill_(1.0)
694
+ if isinstance(module, nn.Linear) and module.bias is not None:
695
+ module.bias.data.zero_()
696
+
697
+
698
+ class BertModel(BertPreTrainedModel):
699
+ """
700
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
701
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
702
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
703
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
704
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
705
+ input to the forward pass.
706
+ """
707
+
708
+ def __init__(self, config, add_pooling_layer=False):
709
+ super().__init__(config)
710
+ self.config = config
711
+
712
+ self.embeddings = BertEmbeddings(config)
713
+
714
+ self.encoder = BertEncoder(config)
715
+
716
+ self.pooler = BertPooler(config) if add_pooling_layer else None
717
+
718
+ self.init_weights()
719
+
720
+ def get_input_embeddings(self):
721
+ return self.embeddings.word_embeddings
722
+
723
+ def set_input_embeddings(self, value):
724
+ self.embeddings.word_embeddings = value
725
+
726
+ def _prune_heads(self, heads_to_prune):
727
+ """
728
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
729
+ class PreTrainedModel
730
+ """
731
+ for layer, heads in heads_to_prune.items():
732
+ self.encoder.layer[layer].attention.prune_heads(heads)
733
+
734
+ def get_extended_attention_mask(
735
+ self,
736
+ attention_mask: Tensor,
737
+ input_shape: Tuple[int],
738
+ device: device,
739
+ is_decoder: bool,
740
+ has_query: bool = False,
741
+ ) -> Tensor:
742
+ """
743
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
744
+
745
+ Arguments:
746
+ attention_mask (:obj:`torch.Tensor`):
747
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
748
+ input_shape (:obj:`Tuple[int]`):
749
+ The shape of the input to the model.
750
+ device: (:obj:`torch.device`):
751
+ The device of the input to the model.
752
+
753
+ Returns:
754
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
755
+ """
756
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
757
+ # ourselves in which case we just need to make it broadcastable to all heads.
758
+ if attention_mask.dim() == 3:
759
+ extended_attention_mask = attention_mask[:, None, :, :]
760
+ elif attention_mask.dim() == 2:
761
+ # Provided a padding mask of dimensions [batch_size, seq_length]
762
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
763
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
764
+ if is_decoder:
765
+ batch_size, seq_length = input_shape
766
+
767
+ seq_ids = torch.arange(seq_length, device=device)
768
+ causal_mask = (
769
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
770
+ <= seq_ids[None, :, None]
771
+ )
772
+
773
+ # add a prefix ones mask to the causal mask
774
+ # causal and attention masks must have same type with pytorch version < 1.3
775
+ causal_mask = causal_mask.to(attention_mask.dtype)
776
+
777
+ if causal_mask.shape[1] < attention_mask.shape[1]:
778
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
779
+ if has_query: # UniLM style attention mask
780
+ causal_mask = torch.cat(
781
+ [
782
+ torch.zeros(
783
+ (batch_size, prefix_seq_len, seq_length),
784
+ device=device,
785
+ dtype=causal_mask.dtype,
786
+ ),
787
+ causal_mask,
788
+ ],
789
+ axis=1,
790
+ )
791
+ causal_mask = torch.cat(
792
+ [
793
+ torch.ones(
794
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
795
+ device=device,
796
+ dtype=causal_mask.dtype,
797
+ ),
798
+ causal_mask,
799
+ ],
800
+ axis=-1,
801
+ )
802
+ extended_attention_mask = (
803
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
804
+ )
805
+ else:
806
+ extended_attention_mask = attention_mask[:, None, None, :]
807
+ else:
808
+ raise ValueError(
809
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
810
+ input_shape, attention_mask.shape
811
+ )
812
+ )
813
+
814
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
815
+ # masked positions, this operation will create a tensor which is 0.0 for
816
+ # positions we want to attend and -10000.0 for masked positions.
817
+ # Since we are adding it to the raw scores before the softmax, this is
818
+ # effectively the same as removing these entirely.
819
+ extended_attention_mask = extended_attention_mask.to(
820
+ dtype=self.dtype
821
+ ) # fp16 compatibility
822
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
823
+ return extended_attention_mask
824
+
825
+ def forward(
826
+ self,
827
+ input_ids=None,
828
+ attention_mask=None,
829
+ position_ids=None,
830
+ head_mask=None,
831
+ query_embeds=None,
832
+ encoder_hidden_states=None,
833
+ encoder_attention_mask=None,
834
+ past_key_values=None,
835
+ use_cache=None,
836
+ output_attentions=None,
837
+ output_hidden_states=None,
838
+ return_dict=None,
839
+ is_decoder=False,
840
+ ):
841
+ r"""
842
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
843
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
844
+ the model is configured as a decoder.
845
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
846
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
847
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
848
+ - 1 for tokens that are **not masked**,
849
+ - 0 for tokens that are **masked**.
850
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
851
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
852
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
853
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
854
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
855
+ use_cache (:obj:`bool`, `optional`):
856
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
857
+ decoding (see :obj:`past_key_values`).
858
+ """
859
+ output_attentions = (
860
+ output_attentions
861
+ if output_attentions is not None
862
+ else self.config.output_attentions
863
+ )
864
+ output_hidden_states = (
865
+ output_hidden_states
866
+ if output_hidden_states is not None
867
+ else self.config.output_hidden_states
868
+ )
869
+ return_dict = (
870
+ return_dict if return_dict is not None else self.config.use_return_dict
871
+ )
872
+
873
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
874
+
875
+ if input_ids is None:
876
+ assert (
877
+ query_embeds is not None
878
+ ), "You have to specify query_embeds when input_ids is None"
879
+
880
+ # past_key_values_length
881
+ past_key_values_length = (
882
+ past_key_values[0][0].shape[2] - self.config.query_length
883
+ if past_key_values is not None
884
+ else 0
885
+ )
886
+
887
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
888
+
889
+ embedding_output = self.embeddings(
890
+ input_ids=input_ids,
891
+ position_ids=position_ids,
892
+ query_embeds=query_embeds,
893
+ past_key_values_length=past_key_values_length,
894
+ )
895
+
896
+ input_shape = embedding_output.size()[:-1]
897
+ batch_size, seq_length = input_shape
898
+ device = embedding_output.device
899
+
900
+ if attention_mask is None:
901
+ attention_mask = torch.ones(
902
+ ((batch_size, seq_length + past_key_values_length)), device=device
903
+ )
904
+
905
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
906
+ # ourselves in which case we just need to make it broadcastable to all heads.
907
+ if is_decoder:
908
+ extended_attention_mask = self.get_extended_attention_mask(
909
+ attention_mask,
910
+ input_ids.shape,
911
+ device,
912
+ is_decoder,
913
+ has_query=(query_embeds is not None),
914
+ )
915
+ else:
916
+ extended_attention_mask = self.get_extended_attention_mask(
917
+ attention_mask, input_shape, device, is_decoder
918
+ )
919
+
920
+ # If a 2D or 3D attention mask is provided for the cross-attention
921
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
922
+ if encoder_hidden_states is not None:
923
+ if type(encoder_hidden_states) == list:
924
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
925
+ 0
926
+ ].size()
927
+ else:
928
+ (
929
+ encoder_batch_size,
930
+ encoder_sequence_length,
931
+ _,
932
+ ) = encoder_hidden_states.size()
933
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
934
+
935
+ if type(encoder_attention_mask) == list:
936
+ encoder_extended_attention_mask = [
937
+ self.invert_attention_mask(mask) for mask in encoder_attention_mask
938
+ ]
939
+ elif encoder_attention_mask is None:
940
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
941
+ encoder_extended_attention_mask = self.invert_attention_mask(
942
+ encoder_attention_mask
943
+ )
944
+ else:
945
+ encoder_extended_attention_mask = self.invert_attention_mask(
946
+ encoder_attention_mask
947
+ )
948
+ else:
949
+ encoder_extended_attention_mask = None
950
+
951
+ # Prepare head mask if needed
952
+ # 1.0 in head_mask indicate we keep the head
953
+ # attention_probs has shape bsz x n_heads x N x N
954
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
955
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
956
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
957
+
958
+ encoder_outputs = self.encoder(
959
+ embedding_output,
960
+ attention_mask=extended_attention_mask,
961
+ head_mask=head_mask,
962
+ encoder_hidden_states=encoder_hidden_states,
963
+ encoder_attention_mask=encoder_extended_attention_mask,
964
+ past_key_values=past_key_values,
965
+ use_cache=use_cache,
966
+ output_attentions=output_attentions,
967
+ output_hidden_states=output_hidden_states,
968
+ return_dict=return_dict,
969
+ query_length=query_length,
970
+ )
971
+ sequence_output = encoder_outputs[0]
972
+ pooled_output = (
973
+ self.pooler(sequence_output) if self.pooler is not None else None
974
+ )
975
+
976
+ if not return_dict:
977
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
978
+
979
+ return BaseModelOutputWithPoolingAndCrossAttentions(
980
+ last_hidden_state=sequence_output,
981
+ pooler_output=pooled_output,
982
+ past_key_values=encoder_outputs.past_key_values,
983
+ hidden_states=encoder_outputs.hidden_states,
984
+ attentions=encoder_outputs.attentions,
985
+ cross_attentions=encoder_outputs.cross_attentions,
986
+ )
987
+
988
+
989
+ class BertLMHeadModel(BertPreTrainedModel):
990
+
991
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
992
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
993
+
994
+ def __init__(self, config):
995
+ super().__init__(config)
996
+
997
+ self.bert = BertModel(config, add_pooling_layer=False)
998
+ self.cls = BertOnlyMLMHead(config)
999
+
1000
+ self.init_weights()
1001
+
1002
+ def get_output_embeddings(self):
1003
+ return self.cls.predictions.decoder
1004
+
1005
+ def set_output_embeddings(self, new_embeddings):
1006
+ self.cls.predictions.decoder = new_embeddings
1007
+
1008
+ def forward(
1009
+ self,
1010
+ input_ids=None,
1011
+ attention_mask=None,
1012
+ position_ids=None,
1013
+ head_mask=None,
1014
+ query_embeds=None,
1015
+ encoder_hidden_states=None,
1016
+ encoder_attention_mask=None,
1017
+ labels=None,
1018
+ past_key_values=None,
1019
+ use_cache=True,
1020
+ output_attentions=None,
1021
+ output_hidden_states=None,
1022
+ return_dict=None,
1023
+ return_logits=False,
1024
+ is_decoder=True,
1025
+ reduction="mean",
1026
+ ):
1027
+ r"""
1028
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
1029
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1030
+ the model is configured as a decoder.
1031
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1032
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1033
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
1034
+ - 1 for tokens that are **not masked**,
1035
+ - 0 for tokens that are **masked**.
1036
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1037
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1038
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
1039
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
1040
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1041
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1042
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
1043
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
1044
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
1045
+ use_cache (:obj:`bool`, `optional`):
1046
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
1047
+ decoding (see :obj:`past_key_values`).
1048
+ Returns:
1049
+ Example::
1050
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
1051
+ >>> import torch
1052
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
1053
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
1054
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
1055
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1056
+ >>> outputs = model(**inputs)
1057
+ >>> prediction_logits = outputs.logits
1058
+ """
1059
+ return_dict = (
1060
+ return_dict if return_dict is not None else self.config.use_return_dict
1061
+ )
1062
+ if labels is not None:
1063
+ use_cache = False
1064
+ if past_key_values is not None:
1065
+ query_embeds = None
1066
+
1067
+ outputs = self.bert(
1068
+ input_ids,
1069
+ attention_mask=attention_mask,
1070
+ position_ids=position_ids,
1071
+ head_mask=head_mask,
1072
+ query_embeds=query_embeds,
1073
+ encoder_hidden_states=encoder_hidden_states,
1074
+ encoder_attention_mask=encoder_attention_mask,
1075
+ past_key_values=past_key_values,
1076
+ use_cache=use_cache,
1077
+ output_attentions=output_attentions,
1078
+ output_hidden_states=output_hidden_states,
1079
+ return_dict=return_dict,
1080
+ is_decoder=is_decoder,
1081
+ )
1082
+
1083
+ sequence_output = outputs[0]
1084
+ if query_embeds is not None:
1085
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1086
+
1087
+ prediction_scores = self.cls(sequence_output)
1088
+
1089
+ if return_logits:
1090
+ return prediction_scores[:, :-1, :].contiguous()
1091
+
1092
+ lm_loss = None
1093
+ if labels is not None:
1094
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1095
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1096
+ labels = labels[:, 1:].contiguous()
1097
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
1098
+ lm_loss = loss_fct(
1099
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
1100
+ labels.view(-1),
1101
+ )
1102
+ if reduction == "none":
1103
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
1104
+
1105
+ if not return_dict:
1106
+ output = (prediction_scores,) + outputs[2:]
1107
+ return ((lm_loss,) + output) if lm_loss is not None else output
1108
+
1109
+ return CausalLMOutputWithCrossAttentions(
1110
+ loss=lm_loss,
1111
+ logits=prediction_scores,
1112
+ past_key_values=outputs.past_key_values,
1113
+ hidden_states=outputs.hidden_states,
1114
+ attentions=outputs.attentions,
1115
+ cross_attentions=outputs.cross_attentions,
1116
+ )
1117
+
1118
+ def prepare_inputs_for_generation(
1119
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
1120
+ ):
1121
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1122
+ if attention_mask is None:
1123
+ attention_mask = input_ids.new_ones(input_ids.shape)
1124
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
1125
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
1126
+
1127
+ # cut decoder_input_ids if past is used
1128
+ if past is not None:
1129
+ input_ids = input_ids[:, -1:]
1130
+
1131
+ return {
1132
+ "input_ids": input_ids,
1133
+ "query_embeds": query_embeds,
1134
+ "attention_mask": attention_mask,
1135
+ "past_key_values": past,
1136
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1137
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1138
+ "is_decoder": True,
1139
+ }
1140
+
1141
+ def _reorder_cache(self, past, beam_idx):
1142
+ reordered_past = ()
1143
+ for layer_past in past:
1144
+ reordered_past += (
1145
+ tuple(
1146
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1147
+ ),
1148
+ )
1149
+ return reordered_past
1150
+
1151
+
1152
+ class BertForMaskedLM(BertPreTrainedModel):
1153
+
1154
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1155
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1156
+
1157
+ def __init__(self, config):
1158
+ super().__init__(config)
1159
+
1160
+ self.bert = BertModel(config, add_pooling_layer=False)
1161
+ self.cls = BertOnlyMLMHead(config)
1162
+
1163
+ self.init_weights()
1164
+
1165
+ def get_output_embeddings(self):
1166
+ return self.cls.predictions.decoder
1167
+
1168
+ def set_output_embeddings(self, new_embeddings):
1169
+ self.cls.predictions.decoder = new_embeddings
1170
+
1171
+ def forward(
1172
+ self,
1173
+ input_ids=None,
1174
+ attention_mask=None,
1175
+ position_ids=None,
1176
+ head_mask=None,
1177
+ query_embeds=None,
1178
+ encoder_hidden_states=None,
1179
+ encoder_attention_mask=None,
1180
+ labels=None,
1181
+ output_attentions=None,
1182
+ output_hidden_states=None,
1183
+ return_dict=None,
1184
+ return_logits=False,
1185
+ is_decoder=False,
1186
+ ):
1187
+ r"""
1188
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1189
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1190
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1191
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1192
+ """
1193
+
1194
+ return_dict = (
1195
+ return_dict if return_dict is not None else self.config.use_return_dict
1196
+ )
1197
+
1198
+ outputs = self.bert(
1199
+ input_ids,
1200
+ attention_mask=attention_mask,
1201
+ position_ids=position_ids,
1202
+ head_mask=head_mask,
1203
+ query_embeds=query_embeds,
1204
+ encoder_hidden_states=encoder_hidden_states,
1205
+ encoder_attention_mask=encoder_attention_mask,
1206
+ output_attentions=output_attentions,
1207
+ output_hidden_states=output_hidden_states,
1208
+ return_dict=return_dict,
1209
+ is_decoder=is_decoder,
1210
+ )
1211
+
1212
+ if query_embeds is not None:
1213
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1214
+ prediction_scores = self.cls(sequence_output)
1215
+
1216
+ if return_logits:
1217
+ return prediction_scores
1218
+
1219
+ masked_lm_loss = None
1220
+ if labels is not None:
1221
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1222
+ masked_lm_loss = loss_fct(
1223
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1224
+ )
1225
+
1226
+ if not return_dict:
1227
+ output = (prediction_scores,) + outputs[2:]
1228
+ return (
1229
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1230
+ )
1231
+
1232
+ return MaskedLMOutput(
1233
+ loss=masked_lm_loss,
1234
+ logits=prediction_scores,
1235
+ hidden_states=outputs.hidden_states,
1236
+ attentions=outputs.attentions,
1237
+ )
1238
+
1239
+
1240
+ def build_qformer(num_query_token, vision_width,
1241
+ qformer_hidden_dropout_prob=0.1,
1242
+ qformer_attention_probs_dropout_prob=0.1,
1243
+ qformer_drop_path_rate=0.,
1244
+ bert_type="bert-base-uncased"
1245
+ ):
1246
+ encoder_config = BertConfig.from_pretrained(bert_type)
1247
+ encoder_config.encoder_width = vision_width
1248
+ # insert cross-attention layer every other block
1249
+ encoder_config.add_cross_attention = True
1250
+ encoder_config.cross_attention_freq = 2
1251
+ encoder_config.query_length = num_query_token
1252
+ encoder_config.hidden_dropout_prob = qformer_hidden_dropout_prob
1253
+ encoder_config.attention_probs_dropout_prob = qformer_attention_probs_dropout_prob
1254
+ encoder_config.drop_path_list = [x.item() for x in torch.linspace(0, qformer_drop_path_rate, encoder_config.num_hidden_layers)]
1255
+ logger.info(f"Drop_path:{encoder_config.drop_path_list}")
1256
+ logger.info(encoder_config)
1257
+ Qformer = BertLMHeadModel(encoder_config)
1258
+ query_tokens = nn.Parameter(
1259
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
1260
+ )
1261
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
1262
+ return Qformer, query_tokens
1263
+
modeling_videochat2.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+ import torch
4
+ import torch.utils.checkpoint
5
+ from torch import nn
6
+ from torch.nn import MSELoss
7
+ from transformers.modeling_outputs import (
8
+ CausalLMOutputWithPast,
9
+ )
10
+ from typing import List, Optional, Tuple, Union
11
+ from torch.cuda.amp import autocast as autocast
12
+ from .modeling_base import BaseMLLM
13
+ from .modeling_internvideo2_vit import pretrain_internvideo2_giant_patch14_224_clean, interpolate_pos_embed_internvideo2_new
14
+ from .modeling_qformer import build_qformer
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ IMG_TOKEN = "[<IMG_PLH>]"
19
+ VID_TOKEN = "[<VID_PLH>]"
20
+
21
+ DEFAULT_PAD_TOKEN = "[PAD]"
22
+ DEFAULT_BOS_TOKEN = '<s>'
23
+ DEFAULT_EOS_TOKEN = '</s>'
24
+ DEFAULT_UNK_TOKEN = "<unk>"
25
+
26
+ DEFAULT_IMAGE_TOKEN = "[IMAGETOKEN]"
27
+ DEFAULT_VIDEO_TOKEN = "[VIDEOTOKEN]"
28
+
29
+ DEFAULT_IMG_PLACEHOLDER = "[<IMG_PLH>]"
30
+ DEFAULT_VID_PLACEHOLDER = "[<VID_PLH>]"
31
+
32
+ class InternVideo2_VideoChat2(BaseMLLM):
33
+
34
+ def __init__(
35
+ self,
36
+ config
37
+ ):
38
+ super().__init__(config=config)
39
+
40
+ def forward(
41
+ self,
42
+ input_ids: torch.LongTensor = None,
43
+ attention_mask: Optional[torch.Tensor] = None,
44
+ labels: Optional[torch.LongTensor] = None,
45
+ image: Optional[torch.Tensor] = None,
46
+ video: Optional[torch.Tensor] = None,
47
+ instruction = None,
48
+ video_idx = None,
49
+ image_idx = None,
50
+ ):
51
+ if self.use_vision_regression_loss:
52
+ text_embeds, visual, visual_idx = self.pad_text_embeds(input_ids=input_ids, image=image,video=video, return_visual=True, video_idx=video_idx, image_idx=image_idx, instruction = instruction)
53
+ else:
54
+ text_embeds = self.pad_text_embeds(input_ids=input_ids, image=image, video=video, return_visual=False, video_idx=video_idx, image_idx=image_idx, instruction = instruction)
55
+
56
+ outputs = self.lm(
57
+ inputs_embeds=text_embeds,
58
+ attention_mask=attention_mask,
59
+ labels=labels,
60
+ output_hidden_states=True,
61
+ return_dict=True,
62
+ )
63
+
64
+ return outputs
65
+
66
+ def pad_text_embeds(
67
+ self,
68
+ input_ids: torch.LongTensor = None,
69
+ image: Optional[torch.Tensor] = None,
70
+ video: Optional[torch.Tensor] = None,
71
+ image_idx = None,
72
+ video_idx = None,
73
+ return_visual: bool = False,
74
+ instruction = None,
75
+ ):
76
+ # text_embeds
77
+ text_embeds = self.lm.get_input_embeddings()(input_ids.long()).detach()
78
+
79
+ visual = None
80
+ visual_idx = None
81
+
82
+ if image is not None:
83
+ B, T, C, H, W = image.shape
84
+ image = image.permute(0, 2, 1, 3, 4)
85
+ prompt_image_embeds = self.encode_vision(image, instruction=instruction)
86
+ visual = prompt_image_embeds
87
+ prompt_image_embeds = self.project_up(prompt_image_embeds)
88
+ prompt_image_embeds = prompt_image_embeds.view(-1, prompt_image_embeds.shape[-1])
89
+ visual_idx = image_idx
90
+ text_embeds[image_idx == 1] = text_embeds[image_idx == 1] * 0 + prompt_image_embeds.to(text_embeds.device)
91
+ elif video is not None:
92
+ if len(video.shape) == 5:
93
+ B, T, C, H, W = video.shape
94
+ N = 1
95
+ else:
96
+ B, N, T, C, H, W = video.shape
97
+ video = video.reshape(B*N, T, C, H, W).permute(0, 2, 1, 3, 4)
98
+ prompt_video_embeds = self.encode_vision(video, instruction=instruction)
99
+ visual = prompt_video_embeds
100
+ prompt_video_embeds = self.project_up(prompt_video_embeds)
101
+ prompt_video_embeds = prompt_video_embeds.view(-1, prompt_video_embeds.shape[-1])
102
+ visual_idx = video_idx
103
+ text_embeds[video_idx == 1] = text_embeds[video_idx == 1] * 0 + prompt_video_embeds.to(text_embeds.device).to(text_embeds.dtype)
104
+ else:
105
+ logger.warn(f"don't get visual input, input_ids: {input_ids}")
106
+
107
+ if return_visual:
108
+ return text_embeds, visual, visual_idx
109
+
110
+ return text_embeds
111
+
112
+
113
+ def encode_vision(
114
+ self,
115
+ image,
116
+ instruction
117
+ ):
118
+ device = image.device
119
+ B = image.shape[0]
120
+ T = image.shape[2]
121
+ use_image = True if T == 1 else False
122
+ image_embeds = self.vision_encoder(image, use_image=use_image)
123
+ C = image_embeds.shape[-1]
124
+ image_embeds = image_embeds.reshape(B, -1, C)
125
+ image_embeds = self.vision_layernorm(image_embeds).to(device) # [B, T*L, C]
126
+
127
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device)
128
+ if self.extra_num_query_token > 0:
129
+ query_tokens = torch.cat([self.query_tokens, self.extra_query_tokens], dim=1)
130
+ query_tokens = query_tokens.expand(image_embeds.shape[0], -1, -1)
131
+ if instruction is not None:
132
+ text_Qformer = self.qformer_tokenizer(
133
+ instruction,
134
+ padding='longest',
135
+ truncation=True,
136
+ max_length=512,
137
+ return_tensors="pt",
138
+ ).to(image_embeds.device)
139
+ query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(image_embeds.device)
140
+ Qformer_atts = torch.cat([query_atts, text_Qformer.attention_mask], dim=1)
141
+ query_output = self.qformer.bert(
142
+ text_Qformer.input_ids,
143
+ attention_mask=Qformer_atts,
144
+ query_embeds=query_tokens,
145
+ encoder_hidden_states=image_embeds,
146
+ encoder_attention_mask=image_atts,
147
+ return_dict=True,
148
+ )
149
+ else:
150
+ query_output = self.qformer.bert(
151
+ query_embeds=query_tokens,
152
+ encoder_hidden_states=image_embeds,
153
+ encoder_attention_mask=image_atts,
154
+ return_dict=True,
155
+ )
156
+
157
+ return query_output.last_hidden_state[:, :query_tokens.size(1), :]
158
+
159
+
160
+ def generate_caption(
161
+ self,
162
+ input_ids,
163
+ attention_mask,
164
+ image_idx = None,
165
+ video_idx = None,
166
+ image: Optional[torch.Tensor] = None,
167
+ video: Optional[torch.Tensor] = None,
168
+ num_beams=1,
169
+ max_new_tokens=200,
170
+ do_sample=True,
171
+ top_p=0.9,
172
+ top_k=None,
173
+ temperature=1.0,
174
+ length_penalty=1,
175
+ repetition_penalty=1.0,
176
+ instruction=None
177
+ ):
178
+ text_embeds = self.pad_text_embeds(input_ids=input_ids, image=image, video=video, image_idx=image_idx, video_idx=video_idx,instruction=instruction)
179
+ outputs = self.lm.generate(
180
+ inputs_embeds=text_embeds,
181
+ attention_mask=attention_mask,
182
+ num_beams=num_beams,
183
+ max_new_tokens=max_new_tokens,
184
+ do_sample=do_sample,
185
+ min_length=1,
186
+ top_p=top_p,
187
+ top_k=top_k,
188
+ temperature=temperature,
189
+ length_penalty=length_penalty,
190
+ repetition_penalty=repetition_penalty,
191
+ )
192
+
193
+ return outputs
194
+
195
+ def build_input_ids(
196
+ self,
197
+ tokenizer,
198
+ conversation,
199
+ max_length,
200
+ add_special_tokens,
201
+ truncation,
202
+ image = None,
203
+ video = None,
204
+ padding = "longest",
205
+ return_tensors = "pt",
206
+ image_placeholder: str = DEFAULT_IMG_PLACEHOLDER,
207
+ video_placeholder: str = DEFAULT_VID_PLACEHOLDER,
208
+ ):
209
+ input_ids = []
210
+ indexs = []
211
+ attention_mask = []
212
+ start, total_len = 0, 0
213
+ while True:
214
+ index1 = conversation.find(image_placeholder, start)
215
+ index2 = conversation.find(video_placeholder, start)
216
+ if index1 == -1 and index2 == -1:
217
+ index = -1
218
+ elif index1 == -1:
219
+ index = index2
220
+ elif index2 == -1:
221
+ index = index1
222
+ else:
223
+ index = min(index1, index2)
224
+ assert index != -1
225
+ if index == -1:
226
+ inputs = tokenizer(conversation[start:], max_length=max_length-total_len, truncation=truncation, padding=padding, return_tensors=return_tensors)
227
+ else:
228
+ inputs = tokenizer(conversation[start:index], max_length=max_length, truncation=truncation, padding='longest', return_tensors=return_tensors)
229
+
230
+ input_ids += inputs.input_ids
231
+ attention_mask += inputs.attention_mask
232
+ total_len += inputs.input_ids[0].shape[0]
233
+ indexs += torch.zeros_like(inputs.input_ids)
234
+
235
+ if index != -1:
236
+ input_ids += [torch.zeros(96).long()]
237
+ attention_mask += [torch.ones(96).long()]
238
+ indexs += [torch.ones(96)]
239
+
240
+ if index == -1:
241
+ return {
242
+ 'input_ids': torch.cat(input_ids),
243
+ 'attention_mask': torch.cat(attention_mask),
244
+ 'index': torch.cat(indexs).to(torch.bool),
245
+ }
246
+ start = index + len(DEFAULT_IMG_PLACEHOLDER)
247
+
248
+ def chat(
249
+ self,
250
+ tokenizer,
251
+ msg,
252
+ user_prompt,
253
+ media_type,
254
+ media_tensor,
255
+ instruction=None,
256
+ chat_history =[],
257
+ return_history =False,
258
+ generation_config={}
259
+ ):
260
+ ilen = media_tensor.shape[1]
261
+
262
+ conversation = ""
263
+ if instruction:
264
+ cur_instruction = "<|im_start|>system\n" + instruction+ "<|im_end|>\n"
265
+ conversation += cur_instruction
266
+ conversation += (
267
+ "<|im_start|>user\n"
268
+ )
269
+
270
+ if media_type == 'image':
271
+ conversation +=( "<img>" + IMG_TOKEN + "</img>")*ilen
272
+ else:
273
+ conversation += ("<vid>" + VID_TOKEN + "</vid>")*ilen
274
+
275
+
276
+ conversation += (
277
+ msg.rstrip() + "<|im_end|>\n"
278
+ )
279
+
280
+ for q,a in chat_history:
281
+ conversation += ("<|im_start|>user\n" + q + "<|im_end|>\n")
282
+ conversation += ("<|im_start|>assistant\n" + a + "<|im_end|>\n" + '</s>')
283
+
284
+ conversation += ("<|im_start|>user\n" + user_prompt + "<|im_end|>\n")
285
+ conversation += ("")
286
+
287
+
288
+ total_len = 0
289
+ indexs = []
290
+ tokenized = self.build_input_ids(
291
+ tokenizer,
292
+ conversation,
293
+ max_length=248,
294
+ add_special_tokens=True,
295
+ truncation=False,
296
+ padding=False,
297
+ return_tensors='pt'
298
+ )
299
+ if media_type == 'image':
300
+ generation_output = self.generate_caption(
301
+ tokenized['input_ids'].unsqueeze(0).to(self.device),
302
+ tokenized['attention_mask'].unsqueeze(0).to(self.device),
303
+ image_idx = tokenized['index'].unsqueeze(0),
304
+ image = media_tensor,
305
+ instruction=[instruction]* ilen if instruction else None,
306
+ **generation_config)
307
+ else:
308
+ generation_output = self.generate_caption(
309
+ tokenized['input_ids'].unsqueeze(0).to(self.device),
310
+ tokenized['attention_mask'].unsqueeze(0).to(self.device),
311
+ video_idx = tokenized['index'].unsqueeze(0),
312
+ video = media_tensor,
313
+ instruction=[instruction]* ilen if instruction else None,
314
+ **generation_config)
315
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
316
+ if return_history:
317
+ chat_history.append((user_prompt,response))
318
+ return response, chat_history
319
+ return response
special_tokens_map.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>"
9
+ ],
10
+ "bos_token": {
11
+ "content": "<s>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ "eos_token": {
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": "<unk>",
25
+ "unk_token": {
26
+ "content": "<unk>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ }
32
+ }
tokenization_internlm2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Tokenization classes for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ import sentencepiece as spm
24
+ from transformers.tokenization_utils import PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {}
32
+
33
+
34
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
35
+ class InternLM2Tokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ Path to the vocabulary file.
42
+ """
43
+
44
+ vocab_files_names = VOCAB_FILES_NAMES
45
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
46
+ model_input_names = ["input_ids", "attention_mask"]
47
+ _auto_class = "AutoTokenizer"
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_file,
52
+ unk_token="<unk>",
53
+ bos_token="<s>",
54
+ eos_token="</s>",
55
+ pad_token="</s>",
56
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
57
+ add_bos_token=True,
58
+ add_eos_token=False,
59
+ decode_with_prefix_space=False,
60
+ clean_up_tokenization_spaces=False,
61
+ **kwargs,
62
+ ):
63
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
64
+ self.vocab_file = vocab_file
65
+ self.add_bos_token = add_bos_token
66
+ self.add_eos_token = add_eos_token
67
+ self.decode_with_prefix_space = decode_with_prefix_space
68
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
69
+ self.sp_model.Load(vocab_file)
70
+ self._no_prefix_space_tokens = None
71
+ super().__init__(
72
+ bos_token=bos_token,
73
+ eos_token=eos_token,
74
+ unk_token=unk_token,
75
+ pad_token=pad_token,
76
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
77
+ **kwargs,
78
+ )
79
+
80
+ @property
81
+ def no_prefix_space_tokens(self):
82
+ if self._no_prefix_space_tokens is None:
83
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
84
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
85
+ return self._no_prefix_space_tokens
86
+
87
+ @property
88
+ def vocab_size(self):
89
+ """Returns vocab size"""
90
+ return self.sp_model.get_piece_size()
91
+
92
+ @property
93
+ def bos_token_id(self) -> Optional[int]:
94
+ return self.sp_model.bos_id()
95
+
96
+ @property
97
+ def eos_token_id(self) -> Optional[int]:
98
+ return self.sp_model.eos_id()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def _maybe_add_prefix_space(self, tokens, decoded):
120
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
121
+ return " " + decoded
122
+ else:
123
+ return decoded
124
+
125
+ def convert_tokens_to_string(self, tokens):
126
+ """Converts a sequence of tokens (string) in a single string."""
127
+ current_sub_tokens = []
128
+ out_string = ""
129
+ prev_is_special = False
130
+ for token in tokens:
131
+ # make sure that special tokens are not decoded using sentencepiece model
132
+ if token in self.all_special_tokens:
133
+ if not prev_is_special:
134
+ out_string += " "
135
+ out_string += self.sp_model.decode(current_sub_tokens) + token
136
+ prev_is_special = True
137
+ current_sub_tokens = []
138
+ else:
139
+ current_sub_tokens.append(token)
140
+ prev_is_special = False
141
+ out_string += self.sp_model.decode(current_sub_tokens)
142
+ out_string = self.clean_up_tokenization(out_string)
143
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
144
+ return out_string[1:]
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ out_vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ if self.add_bos_token:
175
+ bos_token_ids = [self.bos_token_id]
176
+ else:
177
+ bos_token_ids = []
178
+
179
+ output = bos_token_ids + token_ids_0
180
+
181
+ if token_ids_1 is not None:
182
+ output = output + token_ids_1
183
+
184
+ if self.add_eos_token:
185
+ output = output + [self.eos_token_id]
186
+
187
+ return output
188
+
189
+ def get_special_tokens_mask(
190
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
191
+ ) -> List[int]:
192
+ """
193
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
194
+ special tokens using the tokenizer `prepare_for_model` method.
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of IDs.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
202
+ Whether or not the token list is already formatted with special tokens for the model.
203
+
204
+ Returns:
205
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
206
+ """
207
+ if already_has_special_tokens:
208
+ return super().get_special_tokens_mask(
209
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
210
+ )
211
+
212
+ if token_ids_1 is None:
213
+ return [1] + ([0] * len(token_ids_0)) + [1]
214
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
215
+
216
+ def create_token_type_ids_from_sequences(
217
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
218
+ ) -> List[int]:
219
+ """
220
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
221
+ use of token type ids, therefore a list of zeros is returned.
222
+
223
+ Args:
224
+ token_ids_0 (`List[int]`):
225
+ List of IDs.
226
+ token_ids_1 (`List[int]`, *optional*):
227
+ Optional second list of IDs for sequence pairs.
228
+
229
+ Returns:
230
+ `List[int]`: List of zeros.
231
+ """
232
+ eos = [self.eos_token_id]
233
+
234
+ if token_ids_1 is None:
235
+ return len(token_ids_0 + eos) * [0]
236
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
3
+ size 1477754
tokenizer_config.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "92538": {
31
+ "content": "<|plugin|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "92539": {
39
+ "content": "<|interpreter|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "92540": {
47
+ "content": "<|action_end|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "92541": {
55
+ "content": "<|action_start|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "92542": {
63
+ "content": "<|im_end|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "92543": {
71
+ "content": "<|im_start|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ }
78
+ },
79
+ "additional_special_tokens": [
80
+ "<|im_start|>",
81
+ "<|im_end|>",
82
+ "<|action_start|>",
83
+ "<|action_end|>",
84
+ "<|interpreter|>",
85
+ "<|plugin|>"
86
+ ],
87
+ "auto_map": {
88
+ "AutoTokenizer": [
89
+ "tokenization_internlm2.InternLM2Tokenizer",
90
+ "tokenization_internlm2_fast.InternLM2TokenizerFast"
91
+ ]
92
+ },
93
+ "bos_token": "<s>",
94
+ "chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
95
+ "clean_up_tokenization_spaces": false,
96
+ "decode_with_prefix_space": false,
97
+ "eos_token": "</s>",
98
+ "legacy": true,
99
+ "model_max_length": 1000000000000000019884624838656,
100
+ "pad_token": "<unk>",
101
+ "sp_model_kwargs": {},
102
+ "spaces_between_special_tokens": false,
103
+ "tokenizer_class": "MultimodalLlamaTokenizer",
104
+ "unk_token": "<unk>",
105
+ "use_default_system_prompt": false
106
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af95123a1bb48882dd552f70c395a2707f7b21b3028ab6be825d220a95c198b9
3
+ size 6456