add missing files
#2
by xenosxiny - opened
- builder.py +105 -0
- configuration_llada.py +175 -0
- llava_arch.py +702 -0
- modeling_llada.py +1950 -0
- siglip_encoder.py +620 -0
builder.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from siglip_encoder import SigLipVisionTower
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
| 9 |
+
vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
|
| 10 |
+
is_absolute_path_exists = os.path.exists(vision_tower)
|
| 11 |
+
use_s2 = getattr(vision_tower_cfg, "s2", False)
|
| 12 |
+
if "siglip" in vision_tower:
|
| 13 |
+
return SigLipVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
|
| 14 |
+
raise ValueError(f"Unknown vision tower: {vision_tower}")
|
| 15 |
+
|
| 16 |
+
def build_vision_resampler(confg, **kwargs):
|
| 17 |
+
'''
|
| 18 |
+
act as place holder, useless in our model
|
| 19 |
+
'''
|
| 20 |
+
print(f'No use of vision_resampler')
|
| 21 |
+
|
| 22 |
+
class IdentityMap(nn.Module):
|
| 23 |
+
def __init__(self):
|
| 24 |
+
super().__init__()
|
| 25 |
+
|
| 26 |
+
def forward(self, x, *args, **kwargs):
|
| 27 |
+
return x
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def config(self):
|
| 31 |
+
return {"mm_projector_type": "identity"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SimpleResBlock(nn.Module):
|
| 35 |
+
def __init__(self, channels):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.pre_norm = nn.LayerNorm(channels)
|
| 38 |
+
|
| 39 |
+
self.proj = nn.Sequential(nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels))
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
x = self.pre_norm(x)
|
| 43 |
+
return x + self.proj(x)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def build_vision_projector(config, delay_load=False, **kwargs):
|
| 47 |
+
projector_type = getattr(config, "mm_projector_type", "linear")
|
| 48 |
+
|
| 49 |
+
if projector_type == "linear": ### this is default
|
| 50 |
+
return nn.Linear(config.mm_hidden_size, config.hidden_size)
|
| 51 |
+
|
| 52 |
+
if projector_type == "pooler":
|
| 53 |
+
return PoolerProjector(config, kwargs["vision_cfg"])
|
| 54 |
+
|
| 55 |
+
mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", projector_type)
|
| 56 |
+
if mlp_gelu_match: ###this is default
|
| 57 |
+
mlp_depth = int(mlp_gelu_match.group(1)) ###mlx2x_gelu ----> 2 projector
|
| 58 |
+
modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)] ### 4096 - 4096 - gelu - 4096
|
| 59 |
+
for _ in range(1, mlp_depth):
|
| 60 |
+
modules.append(nn.GELU())
|
| 61 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 62 |
+
return nn.Sequential(*modules)
|
| 63 |
+
|
| 64 |
+
mlp_gelu_resnet_match = re.match(r"^mlp(\d+)x_res(\d+)x_gelu$", projector_type)
|
| 65 |
+
if mlp_gelu_resnet_match:
|
| 66 |
+
mlp_depth = int(mlp_gelu_resnet_match.group(1))
|
| 67 |
+
res_depth = int(mlp_gelu_resnet_match.group(2))
|
| 68 |
+
modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
|
| 69 |
+
for _ in range(1, mlp_depth):
|
| 70 |
+
modules.append(nn.GELU())
|
| 71 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 72 |
+
for _ in range(res_depth):
|
| 73 |
+
modules.append(SimpleResBlock(config.hidden_size))
|
| 74 |
+
return nn.Sequential(*modules)
|
| 75 |
+
|
| 76 |
+
if projector_type == "identity":
|
| 77 |
+
return IdentityMap()
|
| 78 |
+
|
| 79 |
+
raise ValueError(f"Unknown projector type: {projector_type}")
|
| 80 |
+
|
| 81 |
+
class PoolerProjector(nn.Module):
|
| 82 |
+
def __init__(self, config, vision_cfg):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self._config = config
|
| 85 |
+
self.hw = vision_cfg.image_size // vision_cfg.patch_size
|
| 86 |
+
|
| 87 |
+
self.conv_pool = nn.Conv2d(config.mm_hidden_size, config.hidden_size, kernel_size=2, stride=2)
|
| 88 |
+
|
| 89 |
+
self.proj = nn.Sequential(
|
| 90 |
+
nn.GELU(),
|
| 91 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def forward(self, x, *args, **kwargs):
|
| 95 |
+
height = width = self.hw
|
| 96 |
+
assert height * width == x.shape[1]
|
| 97 |
+
x = x.view(x.shape[0], height, width, -1).permute(0, 3, 1, 2)
|
| 98 |
+
x = self.conv_pool(x)
|
| 99 |
+
x = x.flatten(2).transpose(1, 2)
|
| 100 |
+
x = self.proj(x)
|
| 101 |
+
return x
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def config(self):
|
| 105 |
+
return {"mm_projector_type": "pooler"}
|
configuration_llada.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
""" LLaDA model configuration"""
|
| 21 |
+
|
| 22 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 23 |
+
from transformers.utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
LLaDA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class LLaDAConfig(PretrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
This is the configuration class to store the configuration of a [`LLaDAModel`]. It is used to instantiate an LLaDA
|
| 34 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 35 |
+
defaults will yield a similar configuration to that of the LLaDA-8B.
|
| 36 |
+
|
| 37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 38 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
| 43 |
+
Vocabulary size of the LLaDA model. Defines the number of different tokens that can be represented by the
|
| 44 |
+
`inputs_ids` passed when calling [`LLaDAModel`]
|
| 45 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 46 |
+
Dimension of the hidden representations.
|
| 47 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 48 |
+
Dimension of the MLP representations.
|
| 49 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 50 |
+
Number of hidden layers in the Transformer decoder.
|
| 51 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 52 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 53 |
+
num_key_value_heads (`int`, *optional*):
|
| 54 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 55 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 56 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 57 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 58 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 59 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 60 |
+
`num_attention_heads`.
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the decoder.
|
| 63 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 64 |
+
The maximum sequence length that this model might ever be used with.
|
| 65 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 67 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 68 |
+
The epsilon used by the rms normalization layers.
|
| 69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 71 |
+
relevant if `config.is_decoder=True`.
|
| 72 |
+
pad_token_id (`int`, *optional*):
|
| 73 |
+
Padding token id.
|
| 74 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 75 |
+
Beginning of stream token id.
|
| 76 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 77 |
+
End of stream token id.
|
| 78 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
| 79 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 80 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
|
| 81 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 82 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 83 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Whether to tie weight embeddings
|
| 85 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 86 |
+
The base period of the RoPE embeddings.
|
| 87 |
+
rope_scaling (`Dict`, *optional*):
|
| 88 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 89 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
| 90 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 91 |
+
`max_position_embeddings` to the expected new maximum.
|
| 92 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 93 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 94 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 95 |
+
The dropout ratio for the attention probabilities.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
model_type = "llada"
|
| 99 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
vocab_size=32000,
|
| 104 |
+
hidden_size=4096,
|
| 105 |
+
intermediate_size=11008,
|
| 106 |
+
num_hidden_layers=32,
|
| 107 |
+
num_attention_heads=32,
|
| 108 |
+
num_key_value_heads=None,
|
| 109 |
+
hidden_act="silu",
|
| 110 |
+
max_position_embeddings=2048,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
rms_norm_eps=1e-6,
|
| 113 |
+
use_cache=True,
|
| 114 |
+
pad_token_id=None,
|
| 115 |
+
bos_token_id=1,
|
| 116 |
+
eos_token_id=2,
|
| 117 |
+
pretraining_tp=1,
|
| 118 |
+
tie_word_embeddings=False,
|
| 119 |
+
rope_theta=10000.0,
|
| 120 |
+
rope_scaling=None,
|
| 121 |
+
attention_bias=False,
|
| 122 |
+
attention_dropout=0.0,
|
| 123 |
+
**kwargs,
|
| 124 |
+
):
|
| 125 |
+
self.vocab_size = vocab_size
|
| 126 |
+
self.max_position_embeddings = max_position_embeddings
|
| 127 |
+
self.hidden_size = hidden_size
|
| 128 |
+
self.intermediate_size = intermediate_size
|
| 129 |
+
self.num_hidden_layers = num_hidden_layers
|
| 130 |
+
self.num_attention_heads = num_attention_heads
|
| 131 |
+
|
| 132 |
+
# for backward compatibility
|
| 133 |
+
if num_key_value_heads is None:
|
| 134 |
+
num_key_value_heads = num_attention_heads
|
| 135 |
+
|
| 136 |
+
self.num_key_value_heads = num_key_value_heads
|
| 137 |
+
self.hidden_act = hidden_act
|
| 138 |
+
self.initializer_range = initializer_range
|
| 139 |
+
self.rms_norm_eps = rms_norm_eps
|
| 140 |
+
self.pretraining_tp = pretraining_tp
|
| 141 |
+
self.use_cache = use_cache
|
| 142 |
+
self.rope_theta = rope_theta
|
| 143 |
+
self.rope_scaling = rope_scaling
|
| 144 |
+
self._rope_scaling_validation()
|
| 145 |
+
self.attention_bias = attention_bias
|
| 146 |
+
self.attention_dropout = attention_dropout
|
| 147 |
+
|
| 148 |
+
super().__init__(
|
| 149 |
+
pad_token_id=pad_token_id,
|
| 150 |
+
bos_token_id=bos_token_id,
|
| 151 |
+
eos_token_id=eos_token_id,
|
| 152 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 153 |
+
**kwargs,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
def _rope_scaling_validation(self):
|
| 157 |
+
"""
|
| 158 |
+
Validate the `rope_scaling` configuration.
|
| 159 |
+
"""
|
| 160 |
+
if self.rope_scaling is None:
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
| 166 |
+
f"got {self.rope_scaling}"
|
| 167 |
+
)
|
| 168 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 169 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
| 170 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
| 171 |
+
raise ValueError(
|
| 172 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 173 |
+
)
|
| 174 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 175 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
llava_arch.py
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Haotian Liu
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
import re
|
| 20 |
+
import time
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
from builder import build_vision_tower
|
| 24 |
+
from builder import build_vision_resampler
|
| 25 |
+
from builder import build_vision_projector
|
| 26 |
+
|
| 27 |
+
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 28 |
+
|
| 29 |
+
from llava.mm_utils import get_anyres_image_grid_shape
|
| 30 |
+
from llava.utils import rank0_print, rank_print
|
| 31 |
+
import random
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LlavaMetaModel:
|
| 35 |
+
|
| 36 |
+
def __init__(self, config):
|
| 37 |
+
super(LlavaMetaModel, self).__init__(config)
|
| 38 |
+
|
| 39 |
+
if hasattr(config, "mm_vision_tower"):
|
| 40 |
+
delay_load = getattr(config, "delay_load", False)
|
| 41 |
+
self.vision_tower = build_vision_tower(config, delay_load=delay_load) ### intialize vision_tower and projector
|
| 42 |
+
self.vision_resampler = build_vision_resampler(config, vision_tower=self.vision_tower)
|
| 43 |
+
self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
|
| 44 |
+
|
| 45 |
+
if "unpad" in getattr(config, "mm_patch_merge_type", ""): ## default is flat
|
| 46 |
+
self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
| 47 |
+
|
| 48 |
+
def get_vision_tower(self): ## return the vision_tower item after intialization
|
| 49 |
+
vision_tower = getattr(self, "vision_tower", None)
|
| 50 |
+
if type(vision_tower) is list:
|
| 51 |
+
vision_tower = vision_tower[0]
|
| 52 |
+
return vision_tower
|
| 53 |
+
|
| 54 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
| 55 |
+
vision_tower = model_args.vision_tower
|
| 56 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
| 57 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
| 58 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter ## first step is none / second is pretrained .bin document
|
| 59 |
+
mm_patch_merge_type = model_args.mm_patch_merge_type
|
| 60 |
+
|
| 61 |
+
self.config.mm_vision_tower = vision_tower
|
| 62 |
+
self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
|
| 63 |
+
|
| 64 |
+
if self.get_vision_tower() is None:
|
| 65 |
+
vision_tower = build_vision_tower(model_args)
|
| 66 |
+
vision_resampler = build_vision_resampler(model_args, vision_tower=vision_tower)
|
| 67 |
+
for k, v in vision_resampler.config.items():
|
| 68 |
+
setattr(self.config, k, v)
|
| 69 |
+
|
| 70 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 71 |
+
self.vision_tower = [vision_tower]
|
| 72 |
+
self.vision_resampler = [vision_resampler]
|
| 73 |
+
else:
|
| 74 |
+
self.vision_tower = vision_tower
|
| 75 |
+
self.vision_resampler = vision_resampler
|
| 76 |
+
else:
|
| 77 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 78 |
+
vision_resampler = self.vision_resampler[0]
|
| 79 |
+
vision_tower = self.vision_tower[0]
|
| 80 |
+
else:
|
| 81 |
+
vision_resampler = self.vision_resampler
|
| 82 |
+
vision_tower = self.vision_tower
|
| 83 |
+
vision_tower.load_model() ###it will use the vision_tower path to load the pretrain vision encoder
|
| 84 |
+
|
| 85 |
+
# In case it is frozen by LoRA
|
| 86 |
+
for p in self.vision_resampler.parameters():
|
| 87 |
+
p.requires_grad = True
|
| 88 |
+
|
| 89 |
+
self.config.use_mm_proj = True
|
| 90 |
+
self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
|
| 91 |
+
self.config.mm_hidden_size = getattr(vision_resampler, "hidden_size", vision_tower.hidden_size)
|
| 92 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
| 93 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
| 94 |
+
self.config.mm_patch_merge_type = mm_patch_merge_type
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if not hasattr(self.config, 'add_faster_video'):
|
| 98 |
+
if model_args.add_faster_video:
|
| 99 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
| 100 |
+
self.faster_token = nn.Parameter(
|
| 101 |
+
torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if getattr(self, "mm_projector", None) is None:
|
| 105 |
+
self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
|
| 106 |
+
|
| 107 |
+
if "unpad" in mm_patch_merge_type:
|
| 108 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
| 109 |
+
self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
| 110 |
+
else:
|
| 111 |
+
# In case it is frozen by LoRA
|
| 112 |
+
for p in self.mm_projector.parameters(): ### freeze the vision encoder and open the projector
|
| 113 |
+
p.requires_grad = True
|
| 114 |
+
|
| 115 |
+
### mute this part and load weight after deepseed initialized
|
| 116 |
+
# if pretrain_mm_mlp_adapter is not None:
|
| 117 |
+
# mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
|
| 118 |
+
|
| 119 |
+
# def get_w(weights, keyword):
|
| 120 |
+
# return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
|
| 121 |
+
|
| 122 |
+
# incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
|
| 123 |
+
# rank0_print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
| 124 |
+
# incompatible_keys = self.vision_resampler.load_state_dict(get_w(mm_projector_weights, "vision_resampler"), strict=False)
|
| 125 |
+
# rank0_print(f"Loaded vision resampler weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def unpad_image(tensor, original_size):
|
| 129 |
+
"""
|
| 130 |
+
Unpads a PyTorch tensor of a padded and resized image.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
|
| 134 |
+
original_size (tuple): The original size of the image (height, width).
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
torch.Tensor: The unpadded image tensor.
|
| 138 |
+
"""
|
| 139 |
+
original_width, original_height = original_size
|
| 140 |
+
current_height, current_width = tensor.shape[1:]
|
| 141 |
+
|
| 142 |
+
# Compute aspect ratios
|
| 143 |
+
original_aspect_ratio = original_width / original_height
|
| 144 |
+
current_aspect_ratio = current_width / current_height
|
| 145 |
+
|
| 146 |
+
# Determine padding size and direction
|
| 147 |
+
if original_aspect_ratio > current_aspect_ratio:
|
| 148 |
+
# Padding was added to the height
|
| 149 |
+
scale_factor = current_width / original_width
|
| 150 |
+
new_height = int(original_height * scale_factor)
|
| 151 |
+
padding = (current_height - new_height) // 2
|
| 152 |
+
unpadded_tensor = tensor[:, padding : current_height - padding, :]
|
| 153 |
+
else:
|
| 154 |
+
# Padding was added to the width
|
| 155 |
+
scale_factor = current_height / original_height
|
| 156 |
+
new_width = int(original_width * scale_factor)
|
| 157 |
+
padding = (current_width - new_width) // 2
|
| 158 |
+
unpadded_tensor = tensor[:, :, padding : current_width - padding]
|
| 159 |
+
|
| 160 |
+
return unpadded_tensor
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class LlavaMetaForCausalLM(ABC):
|
| 164 |
+
|
| 165 |
+
@abstractmethod
|
| 166 |
+
def get_model(self):
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
def get_vision_tower(self):
|
| 170 |
+
return self.get_model().get_vision_tower()
|
| 171 |
+
|
| 172 |
+
def get_2dPool(self, image_feature, stride=2):
|
| 173 |
+
height = width = self.get_vision_tower().num_patches_per_side
|
| 174 |
+
num_frames, num_tokens, num_dim = image_feature.shape
|
| 175 |
+
image_feature = image_feature.view(num_frames, height, width, -1)
|
| 176 |
+
image_feature = image_feature.permute(0, 3, 1, 2).contiguous()
|
| 177 |
+
# image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride)
|
| 178 |
+
if self.config.mm_spatial_pool_mode == "average":
|
| 179 |
+
image_feature = nn.functional.avg_pool2d(image_feature, stride)
|
| 180 |
+
elif self.config.mm_spatial_pool_mode == "max":
|
| 181 |
+
image_feature = nn.functional.max_pool2d(image_feature, stride)
|
| 182 |
+
elif self.config.mm_spatial_pool_mode == "bilinear":
|
| 183 |
+
height, width = image_feature.shape[2:]
|
| 184 |
+
scaled_shape = [math.ceil(height / stride), math.ceil(width / stride)]
|
| 185 |
+
image_feature = nn.functional.interpolate(image_feature, size=scaled_shape, mode='bilinear')
|
| 186 |
+
|
| 187 |
+
else:
|
| 188 |
+
raise ValueError(f"Unexpected mm_spatial_pool_mode: {self.config.mm_spatial_pool_mode}")
|
| 189 |
+
image_feature = image_feature.permute(0, 2, 3, 1)
|
| 190 |
+
image_feature = image_feature.view(num_frames, -1, num_dim)
|
| 191 |
+
return image_feature
|
| 192 |
+
|
| 193 |
+
def encode_images(self, images):
|
| 194 |
+
image_features = self.get_model().get_vision_tower()(images)
|
| 195 |
+
# image_features = self.get_model().vision_resampler(image_features, images=images)
|
| 196 |
+
image_features = self.get_model().mm_projector(image_features)
|
| 197 |
+
return image_features
|
| 198 |
+
|
| 199 |
+
def encode_multimodals(self, videos_or_images, video_idx_in_batch, split_sizes=None):
|
| 200 |
+
videos_or_images_features = self.get_model().get_vision_tower()(videos_or_images)
|
| 201 |
+
per_videos_or_images_features = torch.split(videos_or_images_features, split_sizes, dim=0) # tuple, (dim_1, 576, 4096)
|
| 202 |
+
all_videos_or_images_features = []
|
| 203 |
+
all_faster_video_features = []
|
| 204 |
+
cur_mm_spatial_pool_stride = self.config.mm_spatial_pool_stride
|
| 205 |
+
|
| 206 |
+
for idx, feat in enumerate(per_videos_or_images_features):
|
| 207 |
+
|
| 208 |
+
feat = self.get_model().mm_projector(feat)
|
| 209 |
+
faster_video_feature = 0
|
| 210 |
+
slower_img_feat = 0
|
| 211 |
+
if idx in video_idx_in_batch and cur_mm_spatial_pool_stride > 1:
|
| 212 |
+
slower_img_feat = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
|
| 213 |
+
if self.config.add_faster_video:
|
| 214 |
+
cur_mm_spatial_pool_stride = cur_mm_spatial_pool_stride * 2
|
| 215 |
+
faster_video_feature = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
|
| 216 |
+
if slower_img_feat != 0:
|
| 217 |
+
all_videos_or_images_features.append(slower_img_feat)
|
| 218 |
+
else:
|
| 219 |
+
all_videos_or_images_features.append(feat)
|
| 220 |
+
all_faster_video_features.append(faster_video_feature)
|
| 221 |
+
return all_videos_or_images_features,all_faster_video_features
|
| 222 |
+
|
| 223 |
+
def add_token_per_grid(self, image_feature):
|
| 224 |
+
resize_h = int(math.sqrt(image_feature.shape[1]))
|
| 225 |
+
num_frames = image_feature.shape[0]
|
| 226 |
+
feature_dim = image_feature.shape[-1]
|
| 227 |
+
|
| 228 |
+
image_feature = image_feature.view(num_frames, 1, resize_h, resize_h, -1)
|
| 229 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 230 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 231 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 232 |
+
if getattr(self.config, "add_faster_video", False):
|
| 233 |
+
# import pdb; pdb.set_trace()
|
| 234 |
+
# (3584, 832, 14) -> (3584, 64, 13, 14)
|
| 235 |
+
image_feature = image_feature.view(feature_dim, num_frames,resize_h, -1)
|
| 236 |
+
# (3584, 64, 13, 14) -> (64, 13, 14, 3584)
|
| 237 |
+
image_feature = image_feature.permute(1, 2, 3, 0).contiguous()
|
| 238 |
+
# (64, 13, 14, 3584) -> (64, 13*14, 3584)
|
| 239 |
+
image_feature = image_feature.flatten(1, 2)
|
| 240 |
+
# import pdb; pdb.set_trace()
|
| 241 |
+
return image_feature
|
| 242 |
+
# import pdb; pdb.set_trace()
|
| 243 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 244 |
+
return image_feature
|
| 245 |
+
|
| 246 |
+
def add_token_per_frame(self, image_feature):
|
| 247 |
+
image_feature = image_feature.permute(2, 0, 1).contiguous()
|
| 248 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 249 |
+
image_feature = image_feature.permute(1, 2, 0).contiguous()
|
| 250 |
+
return image_feature
|
| 251 |
+
|
| 252 |
+
def generate_conversation_ids(self, labels):
|
| 253 |
+
"""
|
| 254 |
+
Args:
|
| 255 |
+
labels: Label tensor, can be one-dimensional or two-dimensional
|
| 256 |
+
Returns:
|
| 257 |
+
Conversation ID tensor with the same shape as labels
|
| 258 |
+
"""
|
| 259 |
+
# Process input dimensions
|
| 260 |
+
original_shape = labels.shape
|
| 261 |
+
if labels.ndim == 1:
|
| 262 |
+
labels = labels.unsqueeze(0)
|
| 263 |
+
|
| 264 |
+
batch_size, seq_len = labels.shape
|
| 265 |
+
device = labels.device
|
| 266 |
+
conversation_ids = torch.zeros_like(labels)
|
| 267 |
+
|
| 268 |
+
# Special token IDs
|
| 269 |
+
start_header_id = 126346
|
| 270 |
+
eot_id = 126348
|
| 271 |
+
assistant_role_id1 = 598
|
| 272 |
+
|
| 273 |
+
# Process all sequences in batch
|
| 274 |
+
for b in range(batch_size):
|
| 275 |
+
# Pre-search all special token positions to reduce repeated searches
|
| 276 |
+
start_positions = (labels[b] == start_header_id).nonzero(as_tuple=True)[0]
|
| 277 |
+
end_positions = (labels[b] == eot_id).nonzero(as_tuple=True)[0]
|
| 278 |
+
|
| 279 |
+
# If no boundaries are found, continue to the next sequence
|
| 280 |
+
if len(start_positions) == 0 or len(end_positions) == 0:
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
# Pair all message start and end positions
|
| 284 |
+
message_boundaries = []
|
| 285 |
+
for start_pos in start_positions:
|
| 286 |
+
# Find the nearest end position
|
| 287 |
+
end_indices = (end_positions >= start_pos).nonzero(as_tuple=True)[0]
|
| 288 |
+
if len(end_indices) == 0:
|
| 289 |
+
continue
|
| 290 |
+
|
| 291 |
+
end_pos = end_positions[end_indices[0]]
|
| 292 |
+
|
| 293 |
+
# Quickly check if it's an assistant message
|
| 294 |
+
start_idx = start_pos.item()
|
| 295 |
+
is_assistant = (start_idx + 1 < seq_len and
|
| 296 |
+
labels[b, start_idx + 1] == assistant_role_id1)
|
| 297 |
+
|
| 298 |
+
message_boundaries.append((start_idx, end_pos.item(), is_assistant))
|
| 299 |
+
|
| 300 |
+
# Sort by start position
|
| 301 |
+
message_boundaries.sort(key=lambda x: x[0])
|
| 302 |
+
|
| 303 |
+
# Determine if there is a system message
|
| 304 |
+
has_system = len(message_boundaries) > 0 and not message_boundaries[0][2]
|
| 305 |
+
|
| 306 |
+
# Assign conversation turn IDs
|
| 307 |
+
current_turn = 0
|
| 308 |
+
prev_was_assistant = False
|
| 309 |
+
|
| 310 |
+
# Efficiently handle BOS token (usually at the start of the sequence)
|
| 311 |
+
if labels[b, 0] == 126080: # BOS ID
|
| 312 |
+
conversation_ids[b, 0] = 0
|
| 313 |
+
|
| 314 |
+
# Assign IDs to all messages at once
|
| 315 |
+
for i, (start_pos, end_pos, is_assistant) in enumerate(message_boundaries):
|
| 316 |
+
# The first non-assistant message is a system message
|
| 317 |
+
is_system = i == 0 and not is_assistant and has_system
|
| 318 |
+
|
| 319 |
+
if is_system:
|
| 320 |
+
# System message belongs to the first conversation turn
|
| 321 |
+
conversation_ids[b, start_pos:end_pos+1] = 0
|
| 322 |
+
else:
|
| 323 |
+
# If it's a user message and the previous one was an assistant message, increase the turn
|
| 324 |
+
if not is_assistant and prev_was_assistant:
|
| 325 |
+
current_turn += 1
|
| 326 |
+
|
| 327 |
+
# Assign ID to the entire message block at once
|
| 328 |
+
conversation_ids[b, start_pos:end_pos+1] = current_turn
|
| 329 |
+
|
| 330 |
+
prev_was_assistant = is_assistant
|
| 331 |
+
|
| 332 |
+
# Fill gaps between messages - use cumulative max method
|
| 333 |
+
# This is much faster than looping element by element
|
| 334 |
+
for i in range(1, seq_len):
|
| 335 |
+
if conversation_ids[b, i] == 0 and conversation_ids[b, i-1] > 0:
|
| 336 |
+
conversation_ids[b, i] = conversation_ids[b, i-1]
|
| 337 |
+
|
| 338 |
+
# New: Handle end padding
|
| 339 |
+
non_zero_mask = (conversation_ids[b] != 0)
|
| 340 |
+
if non_zero_mask.any():
|
| 341 |
+
last_non_zero_idx = torch.nonzero(non_zero_mask, as_tuple=True)[0][-1]
|
| 342 |
+
last_turn = conversation_ids[b, last_non_zero_idx]
|
| 343 |
+
conversation_ids[b, last_non_zero_idx+1:] = last_turn
|
| 344 |
+
|
| 345 |
+
# Return a tensor with the same dimensions as the input
|
| 346 |
+
if len(original_shape) == 1:
|
| 347 |
+
return conversation_ids.squeeze(0)
|
| 348 |
+
|
| 349 |
+
return conversation_ids
|
| 350 |
+
|
| 351 |
+
def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None, is_llada=False):
|
| 352 |
+
vision_tower = self.get_vision_tower()
|
| 353 |
+
# rank_print(modalities)
|
| 354 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
| 355 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
| 356 |
+
|
| 357 |
+
if isinstance(modalities, str):
|
| 358 |
+
modalities = [modalities]
|
| 359 |
+
|
| 360 |
+
# import pdb; pdb.set_trace()
|
| 361 |
+
if type(images) is list or images.ndim == 5:
|
| 362 |
+
if type(images) is list:
|
| 363 |
+
images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
|
| 364 |
+
|
| 365 |
+
video_idx_in_batch = []
|
| 366 |
+
for _ in range(len(modalities)):
|
| 367 |
+
if modalities[_] == "video":
|
| 368 |
+
video_idx_in_batch.append(_)
|
| 369 |
+
|
| 370 |
+
images_list = []
|
| 371 |
+
for image in images:
|
| 372 |
+
if image.ndim == 4:
|
| 373 |
+
images_list.append(image)
|
| 374 |
+
else:
|
| 375 |
+
images_list.append(image.unsqueeze(0))
|
| 376 |
+
|
| 377 |
+
concat_images = torch.cat([image for image in images_list], dim=0)
|
| 378 |
+
split_sizes = [image.shape[0] for image in images_list]
|
| 379 |
+
encoded_image_features = self.encode_images(concat_images)
|
| 380 |
+
# image_features,all_faster_video_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
|
| 381 |
+
|
| 382 |
+
# This is a list, each element is [num_images, patch * patch, dim]
|
| 383 |
+
# rank_print(f"Concat images : {concat_images.shape}")
|
| 384 |
+
encoded_image_features = torch.split(encoded_image_features, split_sizes)
|
| 385 |
+
image_features = []
|
| 386 |
+
for idx, image_feat in enumerate(encoded_image_features):
|
| 387 |
+
if idx in video_idx_in_batch:
|
| 388 |
+
image_features.append(self.get_2dPool(image_feat))
|
| 389 |
+
else:
|
| 390 |
+
image_features.append(image_feat)
|
| 391 |
+
# image_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
|
| 392 |
+
# rank_print(f"Encoded image feats : {[x.shape for x in image_features]}")
|
| 393 |
+
# image_features = torch.split(image_features, split_sizes, dim=0)
|
| 394 |
+
mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
|
| 395 |
+
image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
|
| 396 |
+
mm_newline_position = getattr(self.config, "mm_newline_position", "one_token")
|
| 397 |
+
|
| 398 |
+
if mm_patch_merge_type == "flat":
|
| 399 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
| 400 |
+
|
| 401 |
+
elif mm_patch_merge_type.startswith("spatial"):
|
| 402 |
+
new_image_features = []
|
| 403 |
+
for image_idx, image_feature in enumerate(image_features):
|
| 404 |
+
# FIXME: now assume the image is square, and split to 2x2 patches
|
| 405 |
+
# num_patches = h * w, where h = w = sqrt(num_patches)
|
| 406 |
+
# currently image_feature is a tensor of shape (4, num_patches, hidden_size)
|
| 407 |
+
# we want to first unflatten it to (2, 2, h, w, hidden_size)
|
| 408 |
+
# rank0_print("At least we are reaching here")
|
| 409 |
+
# import pdb; pdb.set_trace()
|
| 410 |
+
if image_idx in video_idx_in_batch: # video operations
|
| 411 |
+
# rank0_print("Video")
|
| 412 |
+
if mm_newline_position == "grid":
|
| 413 |
+
# Grid-wise
|
| 414 |
+
image_feature = self.add_token_per_grid(image_feature)
|
| 415 |
+
if getattr(self.config, "add_faster_video", False):
|
| 416 |
+
faster_video_feature = self.add_token_per_grid(all_faster_video_features[image_idx])
|
| 417 |
+
# Add a token for each frame
|
| 418 |
+
concat_slow_fater_token = []
|
| 419 |
+
# import pdb; pdb.set_trace()
|
| 420 |
+
for _ in range(image_feature.shape[0]):
|
| 421 |
+
if _ % self.config.faster_token_stride == 0:
|
| 422 |
+
concat_slow_fater_token.append(torch.cat((image_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
|
| 423 |
+
else:
|
| 424 |
+
concat_slow_fater_token.append(torch.cat((faster_video_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
|
| 425 |
+
# import pdb; pdb.set_trace()
|
| 426 |
+
image_feature = torch.cat(concat_slow_fater_token)
|
| 427 |
+
|
| 428 |
+
# print("!!!!!!!!!!!!")
|
| 429 |
+
|
| 430 |
+
new_image_features.append(image_feature)
|
| 431 |
+
elif mm_newline_position == "frame":
|
| 432 |
+
# Frame-wise
|
| 433 |
+
image_feature = self.add_token_per_frame(image_feature)
|
| 434 |
+
|
| 435 |
+
new_image_features.append(image_feature.flatten(0, 1))
|
| 436 |
+
|
| 437 |
+
elif mm_newline_position == "one_token":
|
| 438 |
+
# one-token
|
| 439 |
+
image_feature = image_feature.flatten(0, 1)
|
| 440 |
+
if 'unpad' in mm_patch_merge_type:
|
| 441 |
+
image_feature = torch.cat((
|
| 442 |
+
image_feature,
|
| 443 |
+
self.model.image_newline[None].to(image_feature.device)
|
| 444 |
+
), dim=0)
|
| 445 |
+
new_image_features.append(image_feature)
|
| 446 |
+
elif mm_newline_position == "no_token":
|
| 447 |
+
new_image_features.append(image_feature.flatten(0, 1))
|
| 448 |
+
else:
|
| 449 |
+
raise ValueError(f"Unexpected mm_newline_position: {mm_newline_position}")
|
| 450 |
+
elif image_feature.shape[0] > 1: # multi patches and multi images operations
|
| 451 |
+
# rank0_print("Single-images")
|
| 452 |
+
base_image_feature = image_feature[0]
|
| 453 |
+
image_feature = image_feature[1:]
|
| 454 |
+
height = width = self.get_vision_tower().num_patches_per_side
|
| 455 |
+
assert height * width == base_image_feature.shape[0]
|
| 456 |
+
|
| 457 |
+
if "anyres_max" in image_aspect_ratio:
|
| 458 |
+
matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
|
| 459 |
+
if matched_anyres_max_num_patches:
|
| 460 |
+
max_num_patches = int(matched_anyres_max_num_patches.group(1))
|
| 461 |
+
|
| 462 |
+
if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
|
| 463 |
+
if hasattr(self.get_vision_tower(), "image_size"):
|
| 464 |
+
vision_tower_image_size = self.get_vision_tower().image_size
|
| 465 |
+
else:
|
| 466 |
+
raise ValueError("vision_tower_image_size is not found in the vision tower.")
|
| 467 |
+
try:
|
| 468 |
+
num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size)
|
| 469 |
+
except Exception as e:
|
| 470 |
+
rank0_print(f"Error: {e}")
|
| 471 |
+
num_patch_width, num_patch_height = 2, 2
|
| 472 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
| 473 |
+
else:
|
| 474 |
+
image_feature = image_feature.view(2, 2, height, width, -1)
|
| 475 |
+
|
| 476 |
+
if "maxpool2x2" in mm_patch_merge_type:
|
| 477 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 478 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 479 |
+
image_feature = nn.functional.max_pool2d(image_feature, 2)
|
| 480 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 481 |
+
elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
|
| 482 |
+
unit = image_feature.shape[2]
|
| 483 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 484 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 485 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
| 486 |
+
c, h, w = image_feature.shape
|
| 487 |
+
times = math.sqrt(h * w / (max_num_patches * unit**2))
|
| 488 |
+
if times > 1.1:
|
| 489 |
+
image_feature = image_feature[None]
|
| 490 |
+
image_feature = nn.functional.interpolate(image_feature, [int(h // times), int(w // times)], mode="bilinear")[0]
|
| 491 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 492 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 493 |
+
elif "unpad" in mm_patch_merge_type:
|
| 494 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 495 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 496 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
| 497 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 498 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 499 |
+
else:
|
| 500 |
+
image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
|
| 501 |
+
image_feature = image_feature.flatten(0, 3)
|
| 502 |
+
if "nobase" in mm_patch_merge_type:
|
| 503 |
+
pass
|
| 504 |
+
else:
|
| 505 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
| 506 |
+
new_image_features.append(image_feature)
|
| 507 |
+
else: # single image operations
|
| 508 |
+
image_feature = image_feature[0]
|
| 509 |
+
if "unpad" in mm_patch_merge_type:
|
| 510 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
|
| 511 |
+
|
| 512 |
+
new_image_features.append(image_feature)
|
| 513 |
+
image_features = new_image_features
|
| 514 |
+
else:
|
| 515 |
+
raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
|
| 516 |
+
else:
|
| 517 |
+
image_features = self.encode_images(images)
|
| 518 |
+
|
| 519 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
| 520 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
|
| 521 |
+
raise NotImplementedError
|
| 522 |
+
# rank_print(f"Total images : {len(image_features)}")
|
| 523 |
+
|
| 524 |
+
# Let's just add dummy tensors if they do not exist,
|
| 525 |
+
# it is a headache to deal with None all the time.
|
| 526 |
+
# But it is not ideal, and if you have a better idea,
|
| 527 |
+
# please open an issue / submit a PR, thanks.
|
| 528 |
+
_labels = labels
|
| 529 |
+
_position_ids = position_ids
|
| 530 |
+
_attention_mask = attention_mask
|
| 531 |
+
if attention_mask is None:
|
| 532 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
| 533 |
+
else:
|
| 534 |
+
attention_mask = attention_mask.bool()
|
| 535 |
+
if position_ids is None:
|
| 536 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
| 537 |
+
if labels is None:
|
| 538 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
| 539 |
+
|
| 540 |
+
# remove the padding using attention_mask -- FIXME
|
| 541 |
+
_input_ids = input_ids
|
| 542 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
| 543 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
| 544 |
+
|
| 545 |
+
new_input_embeds = []
|
| 546 |
+
new_labels = []
|
| 547 |
+
cur_image_idx = 0
|
| 548 |
+
# rank_print("Inserting Images embedding")
|
| 549 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
| 550 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
| 551 |
+
# rank0_print(num_images)
|
| 552 |
+
if num_images == 0:
|
| 553 |
+
cur_image_features = image_features[cur_image_idx]
|
| 554 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
| 555 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
| 556 |
+
new_input_embeds.append(cur_input_embeds)
|
| 557 |
+
new_labels.append(labels[batch_idx])
|
| 558 |
+
cur_image_idx += 1
|
| 559 |
+
continue
|
| 560 |
+
|
| 561 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
| 562 |
+
cur_input_ids_noim = []
|
| 563 |
+
cur_labels = labels[batch_idx]
|
| 564 |
+
cur_labels_noim = []
|
| 565 |
+
for i in range(len(image_token_indices) - 1):
|
| 566 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
| 567 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
| 568 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
| 569 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
| 570 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
| 571 |
+
cur_new_input_embeds = []
|
| 572 |
+
cur_new_labels = []
|
| 573 |
+
|
| 574 |
+
for i in range(num_images + 1):
|
| 575 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
| 576 |
+
cur_new_labels.append(cur_labels_noim[i])
|
| 577 |
+
if i < num_images:
|
| 578 |
+
try:
|
| 579 |
+
cur_image_features = image_features[cur_image_idx]
|
| 580 |
+
except IndexError:
|
| 581 |
+
cur_image_features = image_features[cur_image_idx - 1]
|
| 582 |
+
cur_image_idx += 1
|
| 583 |
+
cur_new_input_embeds.append(cur_image_features)
|
| 584 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
| 585 |
+
|
| 586 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
| 587 |
+
|
| 588 |
+
# import pdb; pdb.set_trace()
|
| 589 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
| 590 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
| 591 |
+
|
| 592 |
+
new_input_embeds.append(cur_new_input_embeds)
|
| 593 |
+
new_labels.append(cur_new_labels)
|
| 594 |
+
|
| 595 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
| 596 |
+
tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
|
| 597 |
+
# rank_print("Finishing Inserting")
|
| 598 |
+
|
| 599 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
| 600 |
+
new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
| 601 |
+
# TODO: Hard code for control loss spike
|
| 602 |
+
# if tokenizer_model_max_length is not None:
|
| 603 |
+
# new_input_embeds = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
| 604 |
+
# new_labels = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
| 605 |
+
|
| 606 |
+
# Combine them
|
| 607 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
| 608 |
+
batch_size = len(new_input_embeds)
|
| 609 |
+
|
| 610 |
+
new_input_embeds_padded = []
|
| 611 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
| 612 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
| 613 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
| 614 |
+
# rank0_print("Prepare pos id")
|
| 615 |
+
|
| 616 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
| 617 |
+
cur_len = cur_new_embed.shape[0]
|
| 618 |
+
if getattr(self.config, "tokenizer_padding_side", "right") == "left":
|
| 619 |
+
new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
|
| 620 |
+
if cur_len > 0:
|
| 621 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
| 622 |
+
attention_mask[i, -cur_len:] = True
|
| 623 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 624 |
+
else:
|
| 625 |
+
new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
|
| 626 |
+
if cur_len > 0:
|
| 627 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
| 628 |
+
attention_mask[i, :cur_len] = True
|
| 629 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 630 |
+
|
| 631 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
| 632 |
+
# rank0_print("tokenizer padding")
|
| 633 |
+
|
| 634 |
+
if _labels is None:
|
| 635 |
+
new_labels = None
|
| 636 |
+
else:
|
| 637 |
+
new_labels = new_labels_padded
|
| 638 |
+
|
| 639 |
+
if _attention_mask is None:
|
| 640 |
+
attention_mask = None
|
| 641 |
+
else:
|
| 642 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
| 643 |
+
|
| 644 |
+
if _position_ids is None:
|
| 645 |
+
position_ids = None
|
| 646 |
+
if getattr(self.config, "use_pos_skipping", False) and self.training:
|
| 647 |
+
position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
|
| 648 |
+
split_position = random.randint(0, new_input_embeds.size(1))
|
| 649 |
+
left_add = random.randint(0, self.config.pos_skipping_range)
|
| 650 |
+
right_add = random.randint(left_add, self.config.pos_skipping_range)
|
| 651 |
+
position_ids[:, :split_position] += left_add
|
| 652 |
+
position_ids[:, split_position:] += right_add
|
| 653 |
+
|
| 654 |
+
# add conversation_ids
|
| 655 |
+
if is_llada and attention_mask is not None:
|
| 656 |
+
conversation_ids = self.generate_conversation_ids(new_labels)
|
| 657 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels, conversation_ids
|
| 658 |
+
# import pdb; pdb.set_trace()
|
| 659 |
+
# rank0_print("Finish preparing")
|
| 660 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 661 |
+
|
| 662 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer):
|
| 663 |
+
if model_args.mm_use_im_patch_token:
|
| 664 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 665 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 666 |
+
|
| 667 |
+
if model_args.mm_use_im_start_end:
|
| 668 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 669 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 670 |
+
|
| 671 |
+
if num_new_tokens > 0:
|
| 672 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
| 673 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
| 674 |
+
|
| 675 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 676 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 677 |
+
|
| 678 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 679 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 680 |
+
|
| 681 |
+
if model_args.tune_mm_mlp_adapter:
|
| 682 |
+
for p in self.get_input_embeddings().parameters():
|
| 683 |
+
p.requires_grad = True
|
| 684 |
+
for p in self.get_output_embeddings().parameters():
|
| 685 |
+
p.requires_grad = False
|
| 686 |
+
|
| 687 |
+
if model_args.pretrain_mm_mlp_adapter:
|
| 688 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
|
| 689 |
+
embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
|
| 690 |
+
assert num_new_tokens == 2
|
| 691 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
| 692 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
| 693 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
| 694 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
| 695 |
+
else:
|
| 696 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
| 697 |
+
elif model_args.mm_use_im_patch_token:
|
| 698 |
+
if model_args.tune_mm_mlp_adapter:
|
| 699 |
+
for p in self.get_input_embeddings().parameters():
|
| 700 |
+
p.requires_grad = False
|
| 701 |
+
for p in self.get_output_embeddings().parameters():
|
| 702 |
+
p.requires_grad = False
|
modeling_llada.py
ADDED
|
@@ -0,0 +1,1950 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""PyTorch LLaDA model."""
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
import warnings
|
| 24 |
+
from typing import List, Optional, Tuple, Union
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
from torch import nn
|
| 31 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 32 |
+
|
| 33 |
+
from transformers.activations import ACT2FN
|
| 34 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
| 35 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 36 |
+
from transformers.modeling_outputs import (
|
| 37 |
+
BaseModelOutputWithPast,
|
| 38 |
+
CausalLMOutputWithPast,
|
| 39 |
+
QuestionAnsweringModelOutput,
|
| 40 |
+
SequenceClassifierOutputWithPast,
|
| 41 |
+
)
|
| 42 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 43 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 44 |
+
from transformers.utils import (
|
| 45 |
+
add_start_docstrings,
|
| 46 |
+
add_start_docstrings_to_model_forward,
|
| 47 |
+
is_flash_attn_2_available,
|
| 48 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 49 |
+
logging,
|
| 50 |
+
replace_return_docstrings,
|
| 51 |
+
)
|
| 52 |
+
from .configuration_llada import LLaDAConfig
|
| 53 |
+
from llava.cache import dLLMCache, dLLMCacheConfig
|
| 54 |
+
|
| 55 |
+
if is_flash_attn_2_available():
|
| 56 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 57 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
logger = logging.get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
_CONFIG_FOR_DOC = "LLaDAConfig"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_unpad_data(attention_mask):
|
| 66 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 67 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 68 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 69 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
| 70 |
+
return (
|
| 71 |
+
indices,
|
| 72 |
+
cu_seqlens,
|
| 73 |
+
max_seqlen_in_batch,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class LLaDARMSNorm(nn.Module):
|
| 78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 79 |
+
"""
|
| 80 |
+
LLaDARMSNorm is equivalent to T5LayerNorm
|
| 81 |
+
"""
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 84 |
+
self.variance_epsilon = eps
|
| 85 |
+
|
| 86 |
+
def forward(self, hidden_states):
|
| 87 |
+
input_dtype = hidden_states.dtype
|
| 88 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 91 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
ALL_LAYERNORM_LAYERS.append(LLaDARMSNorm)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class LLaDARotaryEmbedding(nn.Module):
|
| 98 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.scaling_factor = scaling_factor
|
| 101 |
+
self.dim = dim
|
| 102 |
+
self.max_position_embeddings = max_position_embeddings
|
| 103 |
+
self.base = base
|
| 104 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
| 105 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 106 |
+
# For BC we register cos and sin cached
|
| 107 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 108 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
| 109 |
+
t = t / self.scaling_factor
|
| 110 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 111 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 112 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 113 |
+
self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
|
| 114 |
+
self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def sin_cached(self):
|
| 118 |
+
logger.warning_once(
|
| 119 |
+
"The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
|
| 120 |
+
"the forward method of RoPE from now on instead. It is not used in the `LLaDAAttention` class"
|
| 121 |
+
)
|
| 122 |
+
return self._sin_cached
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def cos_cached(self):
|
| 126 |
+
logger.warning_once(
|
| 127 |
+
"The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
|
| 128 |
+
"the forward method of RoPE from now on instead. It is not used in the `LLaDAAttention` class"
|
| 129 |
+
)
|
| 130 |
+
return self._cos_cached
|
| 131 |
+
|
| 132 |
+
@torch.no_grad()
|
| 133 |
+
def forward(self, x, position_ids):
|
| 134 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 135 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 136 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 137 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
| 138 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
| 139 |
+
device_type = x.device.type
|
| 140 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 141 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 142 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 143 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 144 |
+
cos = emb.cos()
|
| 145 |
+
sin = emb.sin()
|
| 146 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class LLaDALinearScalingRotaryEmbedding(LLaDARotaryEmbedding):
|
| 150 |
+
"""LLaDARotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 151 |
+
|
| 152 |
+
def forward(self, x, position_ids):
|
| 153 |
+
# difference to the original RoPE: a scaling factor is aplied to the position ids
|
| 154 |
+
position_ids = position_ids.float() / self.scaling_factor
|
| 155 |
+
cos, sin = super().forward(x, position_ids)
|
| 156 |
+
return cos, sin
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class LLaDADynamicNTKScalingRotaryEmbedding(LLaDARotaryEmbedding):
|
| 160 |
+
"""LLaDARotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 161 |
+
|
| 162 |
+
def forward(self, x, position_ids):
|
| 163 |
+
# difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
|
| 164 |
+
seq_len = torch.max(position_ids) + 1
|
| 165 |
+
if seq_len > self.max_position_embeddings:
|
| 166 |
+
base = self.base * (
|
| 167 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 168 |
+
) ** (self.dim / (self.dim - 2))
|
| 169 |
+
inv_freq = 1.0 / (
|
| 170 |
+
base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
|
| 171 |
+
)
|
| 172 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
|
| 173 |
+
|
| 174 |
+
cos, sin = super().forward(x, position_ids)
|
| 175 |
+
return cos, sin
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def rotate_half(x):
|
| 179 |
+
"""Rotates half the hidden dims of the input."""
|
| 180 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 181 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 182 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 186 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
q (`torch.Tensor`): The query tensor.
|
| 190 |
+
k (`torch.Tensor`): The key tensor.
|
| 191 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 192 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 193 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 194 |
+
Deprecated and unused.
|
| 195 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 196 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 197 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 198 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 199 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 200 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 201 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 202 |
+
Returns:
|
| 203 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 204 |
+
"""
|
| 205 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 206 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 207 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 208 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 209 |
+
return q_embed, k_embed
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class LLaDAMLP(nn.Module):
|
| 213 |
+
def __init__(self, config):
|
| 214 |
+
super().__init__()
|
| 215 |
+
self.config = config
|
| 216 |
+
self.hidden_size = config.hidden_size
|
| 217 |
+
self.intermediate_size = config.intermediate_size
|
| 218 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 219 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 220 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 221 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 222 |
+
|
| 223 |
+
def forward(self, x):
|
| 224 |
+
if self.config.pretraining_tp > 1:
|
| 225 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 226 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 227 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 228 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 229 |
+
|
| 230 |
+
gate_proj = torch.cat(
|
| 231 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 232 |
+
)
|
| 233 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 234 |
+
|
| 235 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 236 |
+
down_proj = [
|
| 237 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 238 |
+
]
|
| 239 |
+
down_proj = sum(down_proj)
|
| 240 |
+
else:
|
| 241 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 242 |
+
|
| 243 |
+
return down_proj
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 247 |
+
"""
|
| 248 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 249 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 250 |
+
"""
|
| 251 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 252 |
+
if n_rep == 1:
|
| 253 |
+
return hidden_states
|
| 254 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 255 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class LLaDAAttention(nn.Module):
|
| 259 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 260 |
+
|
| 261 |
+
def __init__(self, config: LLaDAConfig, layer_idx: Optional[int] = None):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.config = config
|
| 264 |
+
self.layer_idx = layer_idx
|
| 265 |
+
if layer_idx is None:
|
| 266 |
+
logger.warning_once(
|
| 267 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 268 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 269 |
+
"when creating this class."
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
self.attention_dropout = config.attention_dropout
|
| 273 |
+
self.hidden_size = config.hidden_size
|
| 274 |
+
self.num_heads = config.num_attention_heads
|
| 275 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 276 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 277 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 278 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 279 |
+
self.rope_theta = config.rope_theta
|
| 280 |
+
#self.is_causal = True
|
| 281 |
+
# Modify: MDM set causal to False.
|
| 282 |
+
self.is_causal = False
|
| 283 |
+
|
| 284 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 285 |
+
raise ValueError(
|
| 286 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 287 |
+
f" and `num_heads`: {self.num_heads})."
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 291 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 292 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 293 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
|
| 294 |
+
self._init_rope()
|
| 295 |
+
|
| 296 |
+
def _init_rope(self):
|
| 297 |
+
if self.config.rope_scaling is None:
|
| 298 |
+
self.rotary_emb = LLaDARotaryEmbedding(
|
| 299 |
+
self.head_dim,
|
| 300 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 301 |
+
base=self.rope_theta,
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
scaling_type = self.config.rope_scaling["type"]
|
| 305 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
| 306 |
+
if scaling_type == "linear":
|
| 307 |
+
self.rotary_emb = LLaDALinearScalingRotaryEmbedding(
|
| 308 |
+
self.head_dim,
|
| 309 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 310 |
+
scaling_factor=scaling_factor,
|
| 311 |
+
base=self.rope_theta,
|
| 312 |
+
)
|
| 313 |
+
elif scaling_type == "dynamic":
|
| 314 |
+
self.rotary_emb = LLaDADynamicNTKScalingRotaryEmbedding(
|
| 315 |
+
self.head_dim,
|
| 316 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 317 |
+
scaling_factor=scaling_factor,
|
| 318 |
+
base=self.rope_theta,
|
| 319 |
+
)
|
| 320 |
+
else:
|
| 321 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 322 |
+
|
| 323 |
+
def forward(
|
| 324 |
+
self,
|
| 325 |
+
hidden_states: torch.Tensor,
|
| 326 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 327 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 328 |
+
past_key_value: Optional[Cache] = None,
|
| 329 |
+
output_attentions: bool = False,
|
| 330 |
+
use_cache: bool = False,
|
| 331 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 332 |
+
**kwargs,
|
| 333 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 334 |
+
bsz, q_len, _ = hidden_states.size()
|
| 335 |
+
|
| 336 |
+
if self.config.pretraining_tp > 1:
|
| 337 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 338 |
+
query_slices = self.q_proj.weight.split(
|
| 339 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 340 |
+
)
|
| 341 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 342 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 343 |
+
|
| 344 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 345 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 346 |
+
|
| 347 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 348 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 349 |
+
|
| 350 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 351 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 352 |
+
|
| 353 |
+
else:
|
| 354 |
+
query_states = self.q_proj(hidden_states)
|
| 355 |
+
key_states = self.k_proj(hidden_states)
|
| 356 |
+
value_states = self.v_proj(hidden_states)
|
| 357 |
+
|
| 358 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 359 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 360 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 361 |
+
|
| 362 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
| 363 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 364 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 365 |
+
|
| 366 |
+
if past_key_value is not None:
|
| 367 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 368 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 369 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 370 |
+
|
| 371 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 372 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 373 |
+
|
| 374 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 375 |
+
|
| 376 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 377 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 378 |
+
attn_weights = attn_weights + causal_mask
|
| 379 |
+
|
| 380 |
+
# upcast attention to fp32
|
| 381 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 382 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 383 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 384 |
+
|
| 385 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 386 |
+
raise ValueError(
|
| 387 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 388 |
+
f" {attn_output.size()}"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 392 |
+
|
| 393 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 394 |
+
|
| 395 |
+
if self.config.pretraining_tp > 1:
|
| 396 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 397 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 398 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 399 |
+
else:
|
| 400 |
+
attn_output = self.o_proj(attn_output)
|
| 401 |
+
|
| 402 |
+
if not output_attentions:
|
| 403 |
+
attn_weights = None
|
| 404 |
+
|
| 405 |
+
return attn_output, attn_weights, past_key_value
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class LLaDAFlashAttention2(LLaDAAttention):
|
| 409 |
+
"""
|
| 410 |
+
LLaDA flash attention module. This module inherits from `LLaDAAttention` as the weights of the module stays
|
| 411 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 412 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
def __init__(self, *args, **kwargs):
|
| 416 |
+
super().__init__(*args, **kwargs)
|
| 417 |
+
|
| 418 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 419 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 420 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 421 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 422 |
+
|
| 423 |
+
def forward(
|
| 424 |
+
self,
|
| 425 |
+
hidden_states: torch.Tensor,
|
| 426 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 427 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 428 |
+
past_key_value: Optional[Cache] = None,
|
| 429 |
+
output_attentions: bool = False,
|
| 430 |
+
use_cache: bool = False,
|
| 431 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 432 |
+
**kwargs,
|
| 433 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 434 |
+
output_attentions = False
|
| 435 |
+
|
| 436 |
+
bsz, q_len, _ = hidden_states.size()
|
| 437 |
+
|
| 438 |
+
query_states = self.q_proj(hidden_states)
|
| 439 |
+
key_states = self.k_proj(hidden_states)
|
| 440 |
+
value_states = self.v_proj(hidden_states)
|
| 441 |
+
|
| 442 |
+
# Flash attention requires the input to have the shape
|
| 443 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 444 |
+
# therefore we just need to keep the original shape
|
| 445 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 446 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 447 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 448 |
+
|
| 449 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 450 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 451 |
+
|
| 452 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
| 453 |
+
|
| 454 |
+
if past_key_value is not None:
|
| 455 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 456 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 457 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 458 |
+
|
| 459 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
| 460 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 461 |
+
query_states = query_states.transpose(1, 2)
|
| 462 |
+
key_states = key_states.transpose(1, 2)
|
| 463 |
+
value_states = value_states.transpose(1, 2)
|
| 464 |
+
|
| 465 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 466 |
+
|
| 467 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 468 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 469 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 470 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 471 |
+
# in fp32. (LLaDARMSNorm handles it correctly)
|
| 472 |
+
|
| 473 |
+
input_dtype = query_states.dtype
|
| 474 |
+
if input_dtype == torch.float32:
|
| 475 |
+
if torch.is_autocast_enabled():
|
| 476 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 477 |
+
# Handle the case where the model is quantized
|
| 478 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 479 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 480 |
+
else:
|
| 481 |
+
target_dtype = self.q_proj.weight.dtype
|
| 482 |
+
|
| 483 |
+
logger.warning_once(
|
| 484 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 485 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 486 |
+
f" {target_dtype}."
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
query_states = query_states.to(target_dtype)
|
| 490 |
+
key_states = key_states.to(target_dtype)
|
| 491 |
+
value_states = value_states.to(target_dtype)
|
| 492 |
+
|
| 493 |
+
attn_output = self._flash_attention_forward(
|
| 494 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 498 |
+
attn_output = self.o_proj(attn_output)
|
| 499 |
+
|
| 500 |
+
if not output_attentions:
|
| 501 |
+
attn_weights = None
|
| 502 |
+
|
| 503 |
+
return attn_output, attn_weights, past_key_value
|
| 504 |
+
|
| 505 |
+
def _flash_attention_forward(
|
| 506 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
| 507 |
+
):
|
| 508 |
+
"""
|
| 509 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
| 510 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
| 511 |
+
|
| 512 |
+
Args:
|
| 513 |
+
query_states (`torch.Tensor`):
|
| 514 |
+
Input query states to be passed to Flash Attention API
|
| 515 |
+
key_states (`torch.Tensor`):
|
| 516 |
+
Input key states to be passed to Flash Attention API
|
| 517 |
+
value_states (`torch.Tensor`):
|
| 518 |
+
Input value states to be passed to Flash Attention API
|
| 519 |
+
attention_mask (`torch.Tensor`):
|
| 520 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
| 521 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
| 522 |
+
dropout (`float`):
|
| 523 |
+
Attention dropout
|
| 524 |
+
softmax_scale (`float`, *optional*):
|
| 525 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
| 526 |
+
"""
|
| 527 |
+
if not self._flash_attn_uses_top_left_mask:
|
| 528 |
+
causal = self.is_causal
|
| 529 |
+
else:
|
| 530 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LLaDAFlashAttention2 __init__.
|
| 531 |
+
causal = self.is_causal and query_length != 1
|
| 532 |
+
|
| 533 |
+
assert causal is False # Modify: MDM
|
| 534 |
+
|
| 535 |
+
# Contains at least one padding token in the sequence
|
| 536 |
+
if attention_mask is not None:
|
| 537 |
+
batch_size = query_states.shape[0]
|
| 538 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
| 539 |
+
query_states, key_states, value_states, attention_mask, query_length
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 543 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 544 |
+
|
| 545 |
+
attn_output_unpad = flash_attn_varlen_func(
|
| 546 |
+
query_states,
|
| 547 |
+
key_states,
|
| 548 |
+
value_states,
|
| 549 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 550 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 551 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 552 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 553 |
+
dropout_p=dropout,
|
| 554 |
+
softmax_scale=softmax_scale,
|
| 555 |
+
causal=causal,
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
| 559 |
+
else:
|
| 560 |
+
attn_output = flash_attn_func(
|
| 561 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
return attn_output
|
| 565 |
+
|
| 566 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 567 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 568 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 569 |
+
|
| 570 |
+
key_layer = index_first_axis(
|
| 571 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 572 |
+
)
|
| 573 |
+
value_layer = index_first_axis(
|
| 574 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 575 |
+
)
|
| 576 |
+
if query_length == kv_seq_len:
|
| 577 |
+
query_layer = index_first_axis(
|
| 578 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
| 579 |
+
)
|
| 580 |
+
cu_seqlens_q = cu_seqlens_k
|
| 581 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 582 |
+
indices_q = indices_k
|
| 583 |
+
elif query_length == 1:
|
| 584 |
+
max_seqlen_in_batch_q = 1
|
| 585 |
+
cu_seqlens_q = torch.arange(
|
| 586 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 587 |
+
) # There is a memcpy here, that is very bad.
|
| 588 |
+
indices_q = cu_seqlens_q[:-1]
|
| 589 |
+
query_layer = query_layer.squeeze(1)
|
| 590 |
+
else:
|
| 591 |
+
# The -q_len: slice assumes left padding.
|
| 592 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 593 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 594 |
+
|
| 595 |
+
return (
|
| 596 |
+
query_layer,
|
| 597 |
+
key_layer,
|
| 598 |
+
value_layer,
|
| 599 |
+
indices_q,
|
| 600 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 601 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
class LLaDASdpaAttention(LLaDAAttention):
|
| 606 |
+
"""
|
| 607 |
+
LLaDA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 608 |
+
`LLaDAAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 609 |
+
SDPA API.
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
# Adapted from LLaDAAttention.forward
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states: torch.Tensor,
|
| 616 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 617 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 618 |
+
past_key_value: Optional[Cache] = None,
|
| 619 |
+
output_attentions: bool = False,
|
| 620 |
+
use_cache: bool = False,
|
| 621 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 622 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 623 |
+
if output_attentions:
|
| 624 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 625 |
+
logger.warning_once(
|
| 626 |
+
"LLaDAModel is using LLaDASdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 627 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 628 |
+
)
|
| 629 |
+
return super().forward(
|
| 630 |
+
hidden_states=hidden_states,
|
| 631 |
+
attention_mask=attention_mask,
|
| 632 |
+
position_ids=position_ids,
|
| 633 |
+
past_key_value=past_key_value,
|
| 634 |
+
output_attentions=output_attentions,
|
| 635 |
+
use_cache=use_cache,
|
| 636 |
+
cache_position=cache_position,
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
bsz, q_len, _ = hidden_states.size()
|
| 640 |
+
|
| 641 |
+
query_states = self.q_proj(hidden_states)
|
| 642 |
+
key_states = self.k_proj(hidden_states)
|
| 643 |
+
value_states = self.v_proj(hidden_states)
|
| 644 |
+
|
| 645 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 646 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 647 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 648 |
+
|
| 649 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 650 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 651 |
+
|
| 652 |
+
# In case static cache is used, it is an instance attribute.
|
| 653 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
| 654 |
+
|
| 655 |
+
if past_key_value is not None:
|
| 656 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 657 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 658 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 659 |
+
|
| 660 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 661 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 662 |
+
|
| 663 |
+
causal_mask = attention_mask
|
| 664 |
+
# if attention_mask is not None and cache_position is not None:
|
| 665 |
+
if attention_mask is not None:
|
| 666 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 667 |
+
|
| 668 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 669 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 670 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
| 671 |
+
query_states = query_states.contiguous()
|
| 672 |
+
key_states = key_states.contiguous()
|
| 673 |
+
value_states = value_states.contiguous()
|
| 674 |
+
|
| 675 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 676 |
+
query_states,
|
| 677 |
+
key_states,
|
| 678 |
+
value_states,
|
| 679 |
+
attn_mask=causal_mask,
|
| 680 |
+
is_causal=False, # Modify: MDM
|
| 681 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 685 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 686 |
+
|
| 687 |
+
attn_output = self.o_proj(attn_output)
|
| 688 |
+
|
| 689 |
+
return attn_output, None, past_key_value
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
LLaDA_ATTENTION_CLASSES = {
|
| 693 |
+
"eager": LLaDAAttention,
|
| 694 |
+
"flash_attention_2": LLaDAFlashAttention2,
|
| 695 |
+
"sdpa": LLaDASdpaAttention,
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
class LLaDADecoderLayer(nn.Module):
|
| 700 |
+
def __init__(self, config: LLaDAConfig, layer_idx: int):
|
| 701 |
+
super().__init__()
|
| 702 |
+
self.hidden_size = config.hidden_size
|
| 703 |
+
|
| 704 |
+
self.self_attn = LLaDA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 705 |
+
|
| 706 |
+
self.mlp = LLaDAMLP(config)
|
| 707 |
+
self.input_layernorm = LLaDARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 708 |
+
self.post_attention_layernorm = LLaDARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 709 |
+
|
| 710 |
+
def forward(
|
| 711 |
+
self,
|
| 712 |
+
hidden_states: torch.Tensor,
|
| 713 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 714 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 715 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 716 |
+
output_attentions: Optional[bool] = False,
|
| 717 |
+
use_cache: Optional[bool] = False,
|
| 718 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 719 |
+
**kwargs,
|
| 720 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 721 |
+
"""
|
| 722 |
+
Args:
|
| 723 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 724 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 725 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 726 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 727 |
+
output_attentions (`bool`, *optional*):
|
| 728 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 729 |
+
returned tensors for more detail.
|
| 730 |
+
use_cache (`bool`, *optional*):
|
| 731 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 732 |
+
(see `past_key_values`).
|
| 733 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 734 |
+
"""
|
| 735 |
+
if "padding_mask" in kwargs:
|
| 736 |
+
warnings.warn(
|
| 737 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
residual = hidden_states
|
| 741 |
+
|
| 742 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 743 |
+
|
| 744 |
+
# Self Attention
|
| 745 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 746 |
+
hidden_states=hidden_states,
|
| 747 |
+
attention_mask=attention_mask,
|
| 748 |
+
position_ids=position_ids,
|
| 749 |
+
past_key_value=past_key_value,
|
| 750 |
+
output_attentions=output_attentions,
|
| 751 |
+
use_cache=use_cache,
|
| 752 |
+
cache_position=cache_position,
|
| 753 |
+
**kwargs,
|
| 754 |
+
)
|
| 755 |
+
hidden_states = residual + hidden_states
|
| 756 |
+
|
| 757 |
+
# Fully Connected
|
| 758 |
+
residual = hidden_states
|
| 759 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 760 |
+
hidden_states = self.mlp(hidden_states)
|
| 761 |
+
hidden_states = residual + hidden_states
|
| 762 |
+
|
| 763 |
+
outputs = (hidden_states,)
|
| 764 |
+
|
| 765 |
+
if output_attentions:
|
| 766 |
+
outputs += (self_attn_weights,)
|
| 767 |
+
|
| 768 |
+
if use_cache:
|
| 769 |
+
outputs += (present_key_value,)
|
| 770 |
+
|
| 771 |
+
return outputs
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
LLaDA_START_DOCSTRING = r"""
|
| 775 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 776 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 777 |
+
etc.)
|
| 778 |
+
|
| 779 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 780 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 781 |
+
and behavior.
|
| 782 |
+
|
| 783 |
+
Parameters:
|
| 784 |
+
config ([`LLaDAConfig`]):
|
| 785 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 786 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 787 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 788 |
+
"""
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
@add_start_docstrings(
|
| 792 |
+
"The bare LLaDA Model outputting raw hidden-states without any specific head on top.",
|
| 793 |
+
LLaDA_START_DOCSTRING,
|
| 794 |
+
)
|
| 795 |
+
class LLaDAPreTrainedModel(PreTrainedModel):
|
| 796 |
+
config_class = LLaDAConfig
|
| 797 |
+
base_model_prefix = "model"
|
| 798 |
+
supports_gradient_checkpointing = True
|
| 799 |
+
_no_split_modules = ["LLaDADecoderLayer"]
|
| 800 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 801 |
+
_supports_flash_attn_2 = True
|
| 802 |
+
_supports_sdpa = True
|
| 803 |
+
_supports_cache_class = True
|
| 804 |
+
|
| 805 |
+
def _init_weights(self, module):
|
| 806 |
+
std = self.config.initializer_range
|
| 807 |
+
if isinstance(module, nn.Linear):
|
| 808 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 809 |
+
if module.bias is not None:
|
| 810 |
+
module.bias.data.zero_()
|
| 811 |
+
elif isinstance(module, nn.Embedding):
|
| 812 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 813 |
+
if module.padding_idx is not None:
|
| 814 |
+
module.weight.data[module.padding_idx].zero_()
|
| 815 |
+
|
| 816 |
+
def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
|
| 817 |
+
if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
|
| 818 |
+
raise ValueError(
|
| 819 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
| 820 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
for layer in self.model.layers:
|
| 824 |
+
device = layer.input_layernorm.weight.device
|
| 825 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
| 826 |
+
dtype = self.config._pre_quantization_dtype
|
| 827 |
+
else:
|
| 828 |
+
dtype = layer.self_attn.o_proj.weight.dtype
|
| 829 |
+
layer.self_attn.past_key_value = cache_cls(
|
| 830 |
+
self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
def _reset_cache(self):
|
| 834 |
+
for layer in self.model.layers:
|
| 835 |
+
layer.self_attn.past_key_value = None
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
LLaDA_INPUTS_DOCSTRING = r"""
|
| 839 |
+
Args:
|
| 840 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 841 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 842 |
+
it.
|
| 843 |
+
|
| 844 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 845 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 846 |
+
|
| 847 |
+
[What are input IDs?](../glossary#input-ids)
|
| 848 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 849 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 850 |
+
|
| 851 |
+
- 1 for tokens that are **not masked**,
|
| 852 |
+
- 0 for tokens that are **masked**.
|
| 853 |
+
|
| 854 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 855 |
+
|
| 856 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 857 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 858 |
+
|
| 859 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 860 |
+
`past_key_values`).
|
| 861 |
+
|
| 862 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 863 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 864 |
+
information on the default strategy.
|
| 865 |
+
|
| 866 |
+
- 1 indicates the head is **not masked**,
|
| 867 |
+
- 0 indicates the head is **masked**.
|
| 868 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 869 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 870 |
+
config.n_positions - 1]`.
|
| 871 |
+
|
| 872 |
+
[What are position IDs?](../glossary#position-ids)
|
| 873 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 874 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 875 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 876 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 877 |
+
|
| 878 |
+
Two formats are allowed:
|
| 879 |
+
- a [`~cache_utils.Cache`] instance;
|
| 880 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 881 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 882 |
+
cache format.
|
| 883 |
+
|
| 884 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 885 |
+
legacy cache format will be returned.
|
| 886 |
+
|
| 887 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 888 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 889 |
+
of shape `(batch_size, sequence_length)`.
|
| 890 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 891 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 892 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 893 |
+
model's internal embedding lookup matrix.
|
| 894 |
+
use_cache (`bool`, *optional*):
|
| 895 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 896 |
+
`past_key_values`).
|
| 897 |
+
output_attentions (`bool`, *optional*):
|
| 898 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 899 |
+
tensors for more detail.
|
| 900 |
+
output_hidden_states (`bool`, *optional*):
|
| 901 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 902 |
+
more detail.
|
| 903 |
+
return_dict (`bool`, *optional*):
|
| 904 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 905 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 906 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 907 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 908 |
+
the complete sequence length.
|
| 909 |
+
"""
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
@add_start_docstrings(
|
| 913 |
+
"The bare LLaDA Model outputting raw hidden-states without any specific head on top.",
|
| 914 |
+
LLaDA_START_DOCSTRING,
|
| 915 |
+
)
|
| 916 |
+
class LLaDAModel(LLaDAPreTrainedModel):
|
| 917 |
+
"""
|
| 918 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LLaDADecoderLayer`]
|
| 919 |
+
|
| 920 |
+
Args:
|
| 921 |
+
config: LLaDAConfig
|
| 922 |
+
"""
|
| 923 |
+
|
| 924 |
+
def __init__(self, config: LLaDAConfig):
|
| 925 |
+
super().__init__(config)
|
| 926 |
+
self.padding_idx = config.pad_token_id
|
| 927 |
+
self.vocab_size = config.vocab_size
|
| 928 |
+
|
| 929 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 930 |
+
self.layers = nn.ModuleList(
|
| 931 |
+
[LLaDADecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 932 |
+
)
|
| 933 |
+
self.norm = LLaDARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 934 |
+
self.gradient_checkpointing = False
|
| 935 |
+
|
| 936 |
+
# Initialize weights and apply final processing
|
| 937 |
+
self.post_init()
|
| 938 |
+
|
| 939 |
+
def get_input_embeddings(self):
|
| 940 |
+
return self.embed_tokens
|
| 941 |
+
|
| 942 |
+
def set_input_embeddings(self, value):
|
| 943 |
+
self.embed_tokens = value
|
| 944 |
+
|
| 945 |
+
@add_start_docstrings_to_model_forward(LLaDA_INPUTS_DOCSTRING)
|
| 946 |
+
def forward(
|
| 947 |
+
self,
|
| 948 |
+
input_ids: torch.LongTensor = None,
|
| 949 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 950 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 951 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 952 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 953 |
+
use_cache: Optional[bool] = None,
|
| 954 |
+
output_attentions: Optional[bool] = None,
|
| 955 |
+
output_hidden_states: Optional[bool] = None,
|
| 956 |
+
return_dict: Optional[bool] = None,
|
| 957 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 958 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 959 |
+
# Add Basic MDM Model config check
|
| 960 |
+
assert (past_key_values is None and not use_cache), "The kvcache is not suppotred for MDM."
|
| 961 |
+
|
| 962 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 963 |
+
output_hidden_states = (
|
| 964 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 965 |
+
)
|
| 966 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 967 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 968 |
+
|
| 969 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 970 |
+
raise ValueError(
|
| 971 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
| 972 |
+
)
|
| 973 |
+
|
| 974 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 975 |
+
logger.warning_once(
|
| 976 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 977 |
+
)
|
| 978 |
+
use_cache = False
|
| 979 |
+
|
| 980 |
+
if inputs_embeds is None:
|
| 981 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 982 |
+
|
| 983 |
+
past_seen_tokens = 0
|
| 984 |
+
if use_cache: # kept for BC (cache positions)
|
| 985 |
+
if not isinstance(past_key_values, StaticCache):
|
| 986 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
| 987 |
+
past_seen_tokens = past_key_values.get_seq_length()
|
| 988 |
+
|
| 989 |
+
if cache_position is None:
|
| 990 |
+
if isinstance(past_key_values, StaticCache):
|
| 991 |
+
raise ValueError("cache_position is a required argument when using StaticCache.")
|
| 992 |
+
cache_position = torch.arange(
|
| 993 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
if position_ids is None:
|
| 997 |
+
position_ids = cache_position.unsqueeze(0)
|
| 998 |
+
|
| 999 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, is_causal=False) # Modify: MDM
|
| 1000 |
+
|
| 1001 |
+
# embed positions
|
| 1002 |
+
hidden_states = inputs_embeds
|
| 1003 |
+
|
| 1004 |
+
# decoder layers
|
| 1005 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1006 |
+
all_self_attns = () if output_attentions else None
|
| 1007 |
+
next_decoder_cache = None
|
| 1008 |
+
|
| 1009 |
+
for decoder_layer in self.layers:
|
| 1010 |
+
if output_hidden_states:
|
| 1011 |
+
all_hidden_states += (hidden_states,)
|
| 1012 |
+
|
| 1013 |
+
if self.gradient_checkpointing and self.training:
|
| 1014 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1015 |
+
decoder_layer.__call__,
|
| 1016 |
+
hidden_states,
|
| 1017 |
+
causal_mask,
|
| 1018 |
+
position_ids,
|
| 1019 |
+
past_key_values,
|
| 1020 |
+
output_attentions,
|
| 1021 |
+
use_cache,
|
| 1022 |
+
cache_position,
|
| 1023 |
+
)
|
| 1024 |
+
else:
|
| 1025 |
+
layer_outputs = decoder_layer(
|
| 1026 |
+
hidden_states,
|
| 1027 |
+
attention_mask=causal_mask,
|
| 1028 |
+
position_ids=position_ids,
|
| 1029 |
+
past_key_value=past_key_values,
|
| 1030 |
+
output_attentions=output_attentions,
|
| 1031 |
+
use_cache=use_cache,
|
| 1032 |
+
cache_position=cache_position,
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
hidden_states = layer_outputs[0]
|
| 1036 |
+
|
| 1037 |
+
if use_cache:
|
| 1038 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 1039 |
+
|
| 1040 |
+
if output_attentions:
|
| 1041 |
+
all_self_attns += (layer_outputs[1],)
|
| 1042 |
+
|
| 1043 |
+
hidden_states = self.norm(hidden_states)
|
| 1044 |
+
|
| 1045 |
+
# add hidden states from the last decoder layer
|
| 1046 |
+
if output_hidden_states:
|
| 1047 |
+
all_hidden_states += (hidden_states,)
|
| 1048 |
+
|
| 1049 |
+
next_cache = None
|
| 1050 |
+
if use_cache:
|
| 1051 |
+
next_cache = (
|
| 1052 |
+
next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
|
| 1053 |
+
)
|
| 1054 |
+
if not return_dict:
|
| 1055 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 1056 |
+
return BaseModelOutputWithPast(
|
| 1057 |
+
last_hidden_state=hidden_states,
|
| 1058 |
+
past_key_values=next_cache,
|
| 1059 |
+
hidden_states=all_hidden_states,
|
| 1060 |
+
attentions=all_self_attns,
|
| 1061 |
+
)
|
| 1062 |
+
|
| 1063 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
| 1064 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
| 1065 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
| 1066 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
| 1067 |
+
def _update_causal_mask(self, attention_mask, input_tensor, cache_position, is_causal=True):
|
| 1068 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 1069 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
| 1070 |
+
return attention_mask
|
| 1071 |
+
return None
|
| 1072 |
+
|
| 1073 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 1074 |
+
min_dtype = torch.finfo(dtype).min
|
| 1075 |
+
sequence_length = input_tensor.shape[1]
|
| 1076 |
+
if hasattr(self.layers[0].self_attn, "past_key_value"): # static cache
|
| 1077 |
+
target_length = self.config.max_position_embeddings
|
| 1078 |
+
else: # dynamic cache
|
| 1079 |
+
target_length = (
|
| 1080 |
+
attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else cache_position[-1] + 1
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
| 1084 |
+
if sequence_length != 1:
|
| 1085 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 1086 |
+
|
| 1087 |
+
if is_causal == False:
|
| 1088 |
+
causal_mask = torch.zeros((sequence_length, target_length), dtype=dtype, device=device)
|
| 1089 |
+
|
| 1090 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 1091 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
| 1092 |
+
if attention_mask is not None:
|
| 1093 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 1094 |
+
if attention_mask.dim() == 2:
|
| 1095 |
+
# The position with 1 in attention_mask represents the place to be attended to, so here we need to mask the place where attention_mask is 0
|
| 1096 |
+
mask_length = attention_mask.shape[-1]
|
| 1097 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
|
| 1098 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
|
| 1099 |
+
elif attention_mask.dim() == 4:
|
| 1100 |
+
# The position with 1 in attention_mask represents the place to be attended to, so here we need to mask the place where attention_mask is 0
|
| 1101 |
+
# backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
|
| 1102 |
+
# cache. In that case, the 4D attention mask attends to the newest tokens only.
|
| 1103 |
+
if attention_mask.shape[-2] < cache_position[0] + sequence_length:
|
| 1104 |
+
offset = cache_position[0]
|
| 1105 |
+
else:
|
| 1106 |
+
offset = 0
|
| 1107 |
+
mask_shape = attention_mask.shape
|
| 1108 |
+
mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
|
| 1109 |
+
causal_mask[
|
| 1110 |
+
: mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
|
| 1111 |
+
] = mask_slice
|
| 1112 |
+
|
| 1113 |
+
if (
|
| 1114 |
+
self.config._attn_implementation == "sdpa"
|
| 1115 |
+
and attention_mask is not None
|
| 1116 |
+
and attention_mask.device.type == "cuda"
|
| 1117 |
+
):
|
| 1118 |
+
# TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
|
| 1119 |
+
is_tracing = (
|
| 1120 |
+
torch.jit.is_tracing()
|
| 1121 |
+
or isinstance(input_tensor, torch.fx.Proxy)
|
| 1122 |
+
or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
|
| 1123 |
+
)
|
| 1124 |
+
if not is_tracing and torch.any(attention_mask != 1):
|
| 1125 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 1126 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 1127 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 1128 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 1129 |
+
|
| 1130 |
+
return causal_mask
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
class LLaDAModelLM(LLaDAPreTrainedModel):
|
| 1134 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1135 |
+
|
| 1136 |
+
def __init__(self, config):
|
| 1137 |
+
super().__init__(config)
|
| 1138 |
+
self.model = LLaDAModel(config)
|
| 1139 |
+
self.vocab_size = config.vocab_size
|
| 1140 |
+
self.lm_head = 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.embed_tokens
|
| 1147 |
+
|
| 1148 |
+
def set_input_embeddings(self, value):
|
| 1149 |
+
self.model.embed_tokens = value
|
| 1150 |
+
|
| 1151 |
+
def get_output_embeddings(self):
|
| 1152 |
+
return self.lm_head
|
| 1153 |
+
|
| 1154 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1155 |
+
self.lm_head = 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 |
+
def _build_conversation_mask_optimized(self, conversation_ids):
|
| 1164 |
+
# Reshape conversation_ids for broadcasting
|
| 1165 |
+
ids_i = conversation_ids.unsqueeze(-1) # [batch_size, seq_len, 1]
|
| 1166 |
+
ids_j = conversation_ids.unsqueeze(-2) # [batch_size, 1, seq_len]
|
| 1167 |
+
|
| 1168 |
+
# Use broadcasting to compare all pairs of conversation IDs
|
| 1169 |
+
conv_mask = (ids_j <= ids_i) # [batch_size, seq_len, seq_len]
|
| 1170 |
+
|
| 1171 |
+
# Add the attention head dimension
|
| 1172 |
+
return conv_mask.unsqueeze(1) # [batch_size, 1, seq_len, seq_len]
|
| 1173 |
+
|
| 1174 |
+
@staticmethod
|
| 1175 |
+
def add_gumbel_noise(logits, temperature):
|
| 1176 |
+
'''
|
| 1177 |
+
The Gumbel max is a method for sampling categorical distributions.
|
| 1178 |
+
According to arXiv:2409.02908, for MDM, low-precision Gumbel Max improves perplexity score but reduces generation quality.
|
| 1179 |
+
Thus, we use float64.
|
| 1180 |
+
'''
|
| 1181 |
+
if temperature == 0:
|
| 1182 |
+
# When temperature=0, we can directly return the original logits.
|
| 1183 |
+
# without any noise or transformation
|
| 1184 |
+
return logits
|
| 1185 |
+
|
| 1186 |
+
# use float64 for more stable computation
|
| 1187 |
+
logits = logits.to(torch.float64)
|
| 1188 |
+
noise = torch.rand_like(logits, dtype=torch.float64)
|
| 1189 |
+
gumbel_noise = (- torch.log(noise)) ** temperature
|
| 1190 |
+
return logits.exp() / gumbel_noise
|
| 1191 |
+
|
| 1192 |
+
@staticmethod
|
| 1193 |
+
def get_num_transfer_tokens(mask_index, steps):
|
| 1194 |
+
'''
|
| 1195 |
+
Precompute the number of tokens to transition at each step.
|
| 1196 |
+
Optimized to be more efficient.
|
| 1197 |
+
'''
|
| 1198 |
+
mask_num = mask_index.sum(dim=1, keepdim=True)
|
| 1199 |
+
base = mask_num // steps
|
| 1200 |
+
remainder = mask_num % steps
|
| 1201 |
+
|
| 1202 |
+
# Create tensor once and modify in-place (via clone)
|
| 1203 |
+
num_transfer_tokens = base.expand(-1, steps).clone()
|
| 1204 |
+
|
| 1205 |
+
# Handle remainder more efficiently
|
| 1206 |
+
if remainder.sum() > 0: # Optimization: only proceed if there are remainders
|
| 1207 |
+
indices = torch.arange(steps, device=mask_index.device)
|
| 1208 |
+
# Create mask using broadcasting
|
| 1209 |
+
# indices shape: [steps] -> [1, steps]
|
| 1210 |
+
# remainder shape: [batch_size, 1]
|
| 1211 |
+
# mask shape: [batch_size, steps]
|
| 1212 |
+
mask = indices.unsqueeze(0) < remainder
|
| 1213 |
+
num_transfer_tokens[mask] += 1
|
| 1214 |
+
|
| 1215 |
+
return num_transfer_tokens.to(torch.int64)
|
| 1216 |
+
|
| 1217 |
+
@staticmethod
|
| 1218 |
+
def get_masked_indices_from_embeds(noisy_embeds, masked_embed):
|
| 1219 |
+
# Get shape information
|
| 1220 |
+
b, l, d = noisy_embeds.shape
|
| 1221 |
+
# Expand masked_embed to the same shape as noisy_embeds [b, l, d]
|
| 1222 |
+
masked_embed_expanded = masked_embed.expand(b, l, d)
|
| 1223 |
+
# Calculate absolute difference
|
| 1224 |
+
abs_diff = torch.abs(noisy_embeds - masked_embed_expanded)
|
| 1225 |
+
# Calculate tolerance boundary (atol + rtol * abs(masked_embed))
|
| 1226 |
+
tolerance = 1e-5 + 1e-5 * torch.abs(masked_embed_expanded)
|
| 1227 |
+
# Check if all dimensions at each position are within tolerance
|
| 1228 |
+
# all(dim=-1) ensures all dimensions of each embedding meet the condition
|
| 1229 |
+
masked_indices = (abs_diff <= tolerance).all(dim=-1)
|
| 1230 |
+
|
| 1231 |
+
return masked_indices
|
| 1232 |
+
|
| 1233 |
+
@torch.no_grad()
|
| 1234 |
+
def generate(self, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
|
| 1235 |
+
cfg_scale=0., remasking='low_confidence', mask_id=126336):
|
| 1236 |
+
'''
|
| 1237 |
+
Args:
|
| 1238 |
+
prompt: A tensor of shape (1, l).
|
| 1239 |
+
steps: Sampling steps, less than or equal to gen_length.
|
| 1240 |
+
gen_length: Generated answer length.
|
| 1241 |
+
block_length: Block length, less than or equal to gen_length. If less than gen_length, it means using semi_autoregressive remasking.
|
| 1242 |
+
temperature: Categorical distribution sampling temperature.
|
| 1243 |
+
cfg_scale: Unsupervised classifier-free guidance scale.
|
| 1244 |
+
remasking: Remasking strategy. 'low_confidence' or 'random'.
|
| 1245 |
+
mask_id: The toke id of [MASK] is 126336.
|
| 1246 |
+
'''
|
| 1247 |
+
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(prompt.device)
|
| 1248 |
+
x[:, :prompt.shape[1]] = prompt.clone()
|
| 1249 |
+
|
| 1250 |
+
prompt_index = (x != mask_id)
|
| 1251 |
+
|
| 1252 |
+
assert gen_length % block_length == 0
|
| 1253 |
+
num_blocks = gen_length // block_length
|
| 1254 |
+
|
| 1255 |
+
assert steps % num_blocks == 0
|
| 1256 |
+
steps = steps // num_blocks
|
| 1257 |
+
|
| 1258 |
+
for num_block in range(num_blocks):
|
| 1259 |
+
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
|
| 1260 |
+
num_transfer_tokens = self.get_num_transfer_tokens(block_mask_index, steps)
|
| 1261 |
+
for i in range(steps):
|
| 1262 |
+
mask_index = (x == mask_id)
|
| 1263 |
+
if cfg_scale > 0.:
|
| 1264 |
+
un_x = x.clone()
|
| 1265 |
+
un_x[prompt_index] = mask_id
|
| 1266 |
+
x_ = torch.cat([x, un_x], dim=0)
|
| 1267 |
+
logits = self.model(x_).logits
|
| 1268 |
+
logits, un_logits = torch.chunk(logits, 2, dim=0)
|
| 1269 |
+
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
|
| 1270 |
+
else:
|
| 1271 |
+
logits = self.model(x).logits
|
| 1272 |
+
|
| 1273 |
+
logits_with_noise = self.add_gumbel_noise(logits, temperature=temperature)
|
| 1274 |
+
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
|
| 1275 |
+
|
| 1276 |
+
if remasking == 'low_confidence':
|
| 1277 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 1278 |
+
x0_p = torch.squeeze(
|
| 1279 |
+
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
|
| 1280 |
+
elif remasking == 'random':
|
| 1281 |
+
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
|
| 1282 |
+
else:
|
| 1283 |
+
raise NotImplementedError(remasking)
|
| 1284 |
+
|
| 1285 |
+
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
|
| 1286 |
+
|
| 1287 |
+
x0 = torch.where(mask_index, x0, x)
|
| 1288 |
+
confidence = torch.where(mask_index, x0_p, -np.inf)
|
| 1289 |
+
|
| 1290 |
+
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
|
| 1291 |
+
for j in range(confidence.shape[0]):
|
| 1292 |
+
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
|
| 1293 |
+
transfer_index[j, select_index] = True
|
| 1294 |
+
x[transfer_index] = x0[transfer_index]
|
| 1295 |
+
|
| 1296 |
+
return x
|
| 1297 |
+
|
| 1298 |
+
@torch.no_grad()
|
| 1299 |
+
def generate_with_embeds(self, inputs_embeds, steps=128, gen_length=128, block_length=128, temperature=0.,
|
| 1300 |
+
cfg_scale=0., remasking='low_confidence', mask_id=126336, tokenizer=None, stopping_criteria=None, generation_suffix=None, **kwargs):
|
| 1301 |
+
'''
|
| 1302 |
+
Args:
|
| 1303 |
+
inputs_embeds: A tensor of shape (1, l, d).
|
| 1304 |
+
steps: Sampling steps, less than or equal to gen_length.
|
| 1305 |
+
gen_length: Generated answer length.
|
| 1306 |
+
block_length: Block length, less than or equal to gen_length. If less than gen_length, it means using semi_autoregressive remasking (tokens number/ block).
|
| 1307 |
+
temperature: Categorical distribution sampling temperature.
|
| 1308 |
+
cfg_scale: Unsupervised classifier-free guidance scale.
|
| 1309 |
+
remasking: Remasking strategy. 'low_confidence' or 'random'.
|
| 1310 |
+
mask_id: The toke id of [MASK] is 126336.
|
| 1311 |
+
generation_suffix: (str or None) Generation suffix, such as "The answer is xxx", will be appended to the end
|
| 1312 |
+
'''
|
| 1313 |
+
# Use mixed precision for faster computation
|
| 1314 |
+
with torch.cuda.amp.autocast(enabled=True):
|
| 1315 |
+
# Handle generation suffix
|
| 1316 |
+
suffix_embeds = None
|
| 1317 |
+
suffix_token_ids = None
|
| 1318 |
+
suffix_len = 0 ## the forced generation end
|
| 1319 |
+
if generation_suffix is not None and tokenizer is not None and len(generation_suffix) > 0:
|
| 1320 |
+
# Encode as token id
|
| 1321 |
+
suffix_token_ids = tokenizer.encode(generation_suffix, add_special_tokens=False)
|
| 1322 |
+
suffix_token_ids = torch.tensor(suffix_token_ids, dtype=torch.long, device=inputs_embeds.device).unsqueeze(0) # (1, s)
|
| 1323 |
+
# Convert to embedding
|
| 1324 |
+
suffix_embeds = self.model.embed_tokens(suffix_token_ids) # (1, s, d)
|
| 1325 |
+
suffix_len = suffix_embeds.shape[1]
|
| 1326 |
+
else:
|
| 1327 |
+
suffix_len = 0
|
| 1328 |
+
|
| 1329 |
+
'''
|
| 1330 |
+
Initialize x_embeds with [MASK] tokens.
|
| 1331 |
+
Overwrite beginning with inputs_embeds.
|
| 1332 |
+
If suffix exists, embed it at the end.
|
| 1333 |
+
'''
|
| 1334 |
+
# Create input in embedding space
|
| 1335 |
+
total_length = inputs_embeds.shape[1] + gen_length + suffix_len
|
| 1336 |
+
masked_embed = self.model.embed_tokens(torch.tensor([mask_id]).to(inputs_embeds.device)) # shape (1, d)
|
| 1337 |
+
x_embeds = masked_embed.repeat(1, total_length, 1).to(inputs_embeds.device) # shape (1, l + gen_length + suffix_len, d)
|
| 1338 |
+
x_embeds[:, :inputs_embeds.shape[1]] = inputs_embeds.clone()
|
| 1339 |
+
if suffix_embeds is not None:
|
| 1340 |
+
x_embeds[:, -suffix_len:] = suffix_embeds
|
| 1341 |
+
|
| 1342 |
+
'''
|
| 1343 |
+
x tracks token ids: starts as all [MASK], then fill in suffix.
|
| 1344 |
+
'''
|
| 1345 |
+
# Create a tracking tensor for token IDs for final output
|
| 1346 |
+
x = torch.full((1, total_length), mask_id, dtype=torch.long, device=inputs_embeds.device)
|
| 1347 |
+
if suffix_token_ids is not None:
|
| 1348 |
+
x[:, -suffix_len:] = suffix_token_ids
|
| 1349 |
+
|
| 1350 |
+
'''
|
| 1351 |
+
Tracks which parts are prompt (not to be modified).
|
| 1352 |
+
'''
|
| 1353 |
+
# prompt_index: A tensor of shape (1, l + gen_length + suffix_len) where the first l elements are 1 (representing the prompt)
|
| 1354 |
+
# and the remaining gen_length+suffix_len elements are 0 (representing the generated part)
|
| 1355 |
+
prompt_index = torch.zeros((1, total_length), dtype=torch.bool, device=inputs_embeds.device)
|
| 1356 |
+
prompt_index[:, :inputs_embeds.shape[1]] = 1 # shape (1, l + gen_length + suffix_len)
|
| 1357 |
+
|
| 1358 |
+
'''
|
| 1359 |
+
block_length: token number / block
|
| 1360 |
+
steps: denoising steps / block
|
| 1361 |
+
gen_length: total generation length
|
| 1362 |
+
'''
|
| 1363 |
+
|
| 1364 |
+
assert gen_length % block_length == 0
|
| 1365 |
+
num_blocks = gen_length // block_length
|
| 1366 |
+
|
| 1367 |
+
assert steps % num_blocks == 0
|
| 1368 |
+
steps = steps // num_blocks
|
| 1369 |
+
|
| 1370 |
+
# New: Initialize stop position variable (default to maximum length)
|
| 1371 |
+
stop_position = inputs_embeds.shape[1] + gen_length
|
| 1372 |
+
found_stop_seq = False
|
| 1373 |
+
|
| 1374 |
+
stop_tokens = []
|
| 1375 |
+
if stopping_criteria is not None:
|
| 1376 |
+
assert tokenizer is not None, "tokenizer is required when stopping_criteria is not None"
|
| 1377 |
+
for stop_str in stopping_criteria:
|
| 1378 |
+
# Use tokenizer to convert stop words to token IDs
|
| 1379 |
+
tokens = tokenizer.encode(stop_str, add_special_tokens=False)
|
| 1380 |
+
stop_tokens.append(tokens)
|
| 1381 |
+
|
| 1382 |
+
feature_cache = dLLMCache()
|
| 1383 |
+
feature_cache.reset_cache(inputs_embeds.shape[1])
|
| 1384 |
+
|
| 1385 |
+
for num_block in range(num_blocks):
|
| 1386 |
+
# Create mask index for the current block
|
| 1387 |
+
block_start = inputs_embeds.shape[1] + num_block * block_length
|
| 1388 |
+
block_end = inputs_embeds.shape[1] + (num_block + 1) * block_length
|
| 1389 |
+
|
| 1390 |
+
# If a stop word is found and the stop word position is before the current block, do not process the current block
|
| 1391 |
+
if found_stop_seq and stop_position <= block_start:
|
| 1392 |
+
break
|
| 1393 |
+
|
| 1394 |
+
block_embeds = x_embeds[:, block_start:block_end]
|
| 1395 |
+
block_mask_index = torch.all(torch.abs(block_embeds - masked_embed) < 1e-5, dim=2) #Find [MASK] tokens in the current block.
|
| 1396 |
+
|
| 1397 |
+
num_transfer_tokens = self.get_num_transfer_tokens(block_mask_index, steps) ###determine how many need to be modified
|
| 1398 |
+
|
| 1399 |
+
for i in range(steps):
|
| 1400 |
+
# Determine which positions are mask embeddings
|
| 1401 |
+
mask_index = torch.all(torch.abs(x_embeds - masked_embed) < 1e-5, dim=2)
|
| 1402 |
+
|
| 1403 |
+
# If a stop word has been found, check if the masks before the stop word are all filled
|
| 1404 |
+
if found_stop_seq:
|
| 1405 |
+
# Get the mask state before the stop word
|
| 1406 |
+
pre_stop_masks = mask_index[0, inputs_embeds.shape[1]:stop_position]
|
| 1407 |
+
# If the masks before the stop word are all filled, exit generation
|
| 1408 |
+
if not pre_stop_masks.any():
|
| 1409 |
+
break
|
| 1410 |
+
|
| 1411 |
+
# Check if there are any masks left to fill in the current block
|
| 1412 |
+
current_block_masks = mask_index[0, block_start:block_end]
|
| 1413 |
+
if not current_block_masks.any():
|
| 1414 |
+
break
|
| 1415 |
+
|
| 1416 |
+
# Handle CFG
|
| 1417 |
+
if cfg_scale > 0.:
|
| 1418 |
+
un_embeds = x_embeds.clone() # shape (1, l + gen_length + suffix_len, d)
|
| 1419 |
+
un_mask = prompt_index.unsqueeze(-1).expand_as(x_embeds) # shape (1, l + gen_length + suffix_len, d)
|
| 1420 |
+
un_embeds[un_mask] = masked_embed.repeat(x_embeds.shape[0],x_embeds.shape[1],1)[un_mask] # Use repeat to avoid the complexity of expand_as
|
| 1421 |
+
combined_embeds = torch.cat([x_embeds, un_embeds], dim=0)
|
| 1422 |
+
|
| 1423 |
+
# Forward pass
|
| 1424 |
+
outputs = self.model(inputs_embeds=combined_embeds)
|
| 1425 |
+
logits = self.lm_head(outputs[0]).float()
|
| 1426 |
+
|
| 1427 |
+
# Split and apply CFG
|
| 1428 |
+
logits, un_logits = torch.chunk(logits, 2, dim=0)
|
| 1429 |
+
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
|
| 1430 |
+
else:
|
| 1431 |
+
# Forward pass
|
| 1432 |
+
outputs = self.model(inputs_embeds=x_embeds)
|
| 1433 |
+
logits = self.lm_head(outputs[0]).float()
|
| 1434 |
+
|
| 1435 |
+
for token_id in [126081, 126080, 126346, 126347]:
|
| 1436 |
+
logits[:, :, token_id] = torch.where(mask_index, -float('inf'), logits[:, :, token_id])
|
| 1437 |
+
|
| 1438 |
+
# Add noise and get the most likely token
|
| 1439 |
+
logits_with_noise = self.add_gumbel_noise(logits, temperature=temperature) # shape (1, l + gen_length + suffix_len, vocab_size)
|
| 1440 |
+
x0 = torch.argmax(logits_with_noise, dim=-1) # 1, l + gen_length + suffix_len
|
| 1441 |
+
|
| 1442 |
+
# Get confidence scores
|
| 1443 |
+
if remasking == 'low_confidence':
|
| 1444 |
+
p = F.softmax(logits.to(torch.float64), dim=-1) # shape (1, l + gen_length + suffix_len, vocab_size)
|
| 1445 |
+
x0_p = torch.squeeze(
|
| 1446 |
+
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # 1, l + gen_length + suffix_len represents the confidence of each x0
|
| 1447 |
+
elif remasking == 'random':
|
| 1448 |
+
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
|
| 1449 |
+
else:
|
| 1450 |
+
raise NotImplementedError(remasking)
|
| 1451 |
+
|
| 1452 |
+
# If a stop word is found, only process positions before the stop word
|
| 1453 |
+
if found_stop_seq:
|
| 1454 |
+
x0_p[:, stop_position:] = -np.inf
|
| 1455 |
+
else:
|
| 1456 |
+
# Prevent processing future blocks
|
| 1457 |
+
x0_p[:, block_end:] = -np.inf
|
| 1458 |
+
|
| 1459 |
+
# Do not allow the generated suffix part to be overwritten
|
| 1460 |
+
if suffix_len > 0:
|
| 1461 |
+
x0_p[:, -suffix_len:] = -np.inf
|
| 1462 |
+
|
| 1463 |
+
# Update predictions only at mask positions
|
| 1464 |
+
x0_embeds = self.model.embed_tokens(x0) # shape (1, l + gen_length + suffix_len, d)
|
| 1465 |
+
x0_embeds = torch.where(mask_index.unsqueeze(-1).expand_as(x_embeds), x0_embeds, x_embeds)
|
| 1466 |
+
x0 = torch.where(mask_index, x0, x) # shape (1, l + gen_length + suffix_len)
|
| 1467 |
+
|
| 1468 |
+
# Calculate confidence and determine transfer index
|
| 1469 |
+
confidence = torch.where(mask_index, x0_p, -np.inf)
|
| 1470 |
+
|
| 1471 |
+
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
|
| 1472 |
+
for j in range(confidence.shape[0]):
|
| 1473 |
+
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
|
| 1474 |
+
transfer_index[j, select_index] = True
|
| 1475 |
+
|
| 1476 |
+
# Update embeddings and token IDs
|
| 1477 |
+
x_embeds[transfer_index] = x0_embeds[transfer_index]
|
| 1478 |
+
x[transfer_index] = x0[transfer_index]
|
| 1479 |
+
|
| 1480 |
+
# New: Check for stop words after each update
|
| 1481 |
+
if stopping_criteria is not None:
|
| 1482 |
+
# Only check the generated part (excluding the suffix)
|
| 1483 |
+
generated_part = x[0, inputs_embeds.shape[1]:inputs_embeds.shape[1]+gen_length]
|
| 1484 |
+
current_stop_position = None
|
| 1485 |
+
|
| 1486 |
+
for stop_seq in stop_tokens:
|
| 1487 |
+
if not isinstance(stop_seq, list):
|
| 1488 |
+
stop_seq = [stop_seq]
|
| 1489 |
+
# Check if the generated sequence contains stop words
|
| 1490 |
+
for start_idx in range(generated_part.size(0) - len(stop_seq) + 1):
|
| 1491 |
+
if torch.all(generated_part[start_idx:start_idx + len(stop_seq)] == torch.tensor(stop_seq, device=x.device)):
|
| 1492 |
+
# Calculate the position of the currently found stop word
|
| 1493 |
+
current_position = inputs_embeds.shape[1] + start_idx
|
| 1494 |
+
# If it is the first time a stop word is found, or this stop word is earlier than the previously found one
|
| 1495 |
+
if not found_stop_seq or current_position < stop_position:
|
| 1496 |
+
stop_position = current_position
|
| 1497 |
+
found_stop_seq = True
|
| 1498 |
+
break
|
| 1499 |
+
if found_stop_seq and current_stop_position is None:
|
| 1500 |
+
break
|
| 1501 |
+
|
| 1502 |
+
# Return the generated result, up to stop_position, and append the suffix
|
| 1503 |
+
if found_stop_seq:
|
| 1504 |
+
if suffix_len > 0:
|
| 1505 |
+
return torch.cat([
|
| 1506 |
+
x[:, inputs_embeds.shape[1]:stop_position],
|
| 1507 |
+
x[:, -suffix_len:]
|
| 1508 |
+
], dim=1)
|
| 1509 |
+
else:
|
| 1510 |
+
return x[:, inputs_embeds.shape[1]:stop_position]
|
| 1511 |
+
else:
|
| 1512 |
+
if suffix_len > 0:
|
| 1513 |
+
return torch.cat([
|
| 1514 |
+
x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1]+gen_length],
|
| 1515 |
+
x[:, -suffix_len:]
|
| 1516 |
+
], dim=1)
|
| 1517 |
+
else:
|
| 1518 |
+
return x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1]+gen_length]
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
@add_start_docstrings_to_model_forward(LLaDA_INPUTS_DOCSTRING)
|
| 1522 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1523 |
+
def forward(
|
| 1524 |
+
self,
|
| 1525 |
+
input_ids: torch.LongTensor = None,
|
| 1526 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1527 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1528 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1529 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1530 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1531 |
+
use_cache: Optional[bool] = None,
|
| 1532 |
+
output_attentions: Optional[bool] = None,
|
| 1533 |
+
output_hidden_states: Optional[bool] = None,
|
| 1534 |
+
return_dict: Optional[bool] = None,
|
| 1535 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1536 |
+
conversation_ids: Optional[torch.LongTensor] = None,
|
| 1537 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1538 |
+
r"""
|
| 1539 |
+
Args:
|
| 1540 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1541 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1542 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1543 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1544 |
+
|
| 1545 |
+
Returns:
|
| 1546 |
+
|
| 1547 |
+
Example:
|
| 1548 |
+
|
| 1549 |
+
```python
|
| 1550 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1551 |
+
```"""
|
| 1552 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1553 |
+
output_hidden_states = (
|
| 1554 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1555 |
+
)
|
| 1556 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1557 |
+
|
| 1558 |
+
|
| 1559 |
+
def forward_process_embeds(input_embeds, labels, eps=1e-3):
|
| 1560 |
+
b, l, d = input_embeds.shape
|
| 1561 |
+
t = torch.rand(b, device=input_embeds.device)
|
| 1562 |
+
p_mask = (1 - eps) * t + eps
|
| 1563 |
+
p_mask = p_mask[:, None].repeat(1, l)
|
| 1564 |
+
|
| 1565 |
+
masked_indices = torch.rand((b, l), device=input_embeds.device) < p_mask
|
| 1566 |
+
# Add label condition filtering
|
| 1567 |
+
valid_mask = (labels != -100) # Create valid encoding
|
| 1568 |
+
masked_indices = masked_indices & valid_mask # Combine random encoding and valid encoding
|
| 1569 |
+
# Magic number 126336 stands for the tokenizer special token,
|
| 1570 |
+
# Magic embeddings, which is used for [MASK] token here,
|
| 1571 |
+
masked_embed = self.model.embed_tokens(torch.tensor([126336]).to(input_embeds.device))
|
| 1572 |
+
noisy_embeds = torch.where(masked_indices.unsqueeze(-1), masked_embed, input_embeds)
|
| 1573 |
+
|
| 1574 |
+
return noisy_embeds, p_mask, masked_embed
|
| 1575 |
+
|
| 1576 |
+
noisy_embeds, p_mask, masked_embed = forward_process_embeds(inputs_embeds, labels)
|
| 1577 |
+
|
| 1578 |
+
masked_indices = self.get_masked_indices_from_embeds(noisy_embeds, masked_embed) # shape (b, l)
|
| 1579 |
+
prompt_index = (labels == -100).to(torch.int64) # shape (b, l)
|
| 1580 |
+
|
| 1581 |
+
noisy_data_length = torch.sum((1-prompt_index), dim=-1, keepdim=True) # shape (b, 1)
|
| 1582 |
+
noisy_data_length = noisy_data_length.repeat(1, noisy_embeds.shape[1]) # shape (b, l)
|
| 1583 |
+
|
| 1584 |
+
if conversation_ids is not None:
|
| 1585 |
+
conversation_mask = self._build_conversation_mask_optimized(conversation_ids)
|
| 1586 |
+
if attention_mask is not None:
|
| 1587 |
+
# 1. Dimension expansion
|
| 1588 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # (batch, length) -> (batch, 1, 1, length)
|
| 1589 |
+
attention_mask = attention_mask.expand_as(conversation_mask) # (batch, 1, 1, length) -> (batch, 1, length, length)
|
| 1590 |
+
# 2. Mask combination (element-wise multiplication)
|
| 1591 |
+
combined_mask = conversation_mask * attention_mask
|
| 1592 |
+
else:
|
| 1593 |
+
# If attention_mask is None, directly use conversation_mask
|
| 1594 |
+
combined_mask = conversation_mask
|
| 1595 |
+
attention_mask = combined_mask
|
| 1596 |
+
|
| 1597 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1598 |
+
outputs = self.model(
|
| 1599 |
+
input_ids=input_ids,
|
| 1600 |
+
attention_mask=attention_mask,
|
| 1601 |
+
position_ids=position_ids,
|
| 1602 |
+
past_key_values=past_key_values,
|
| 1603 |
+
inputs_embeds=noisy_embeds,
|
| 1604 |
+
use_cache=use_cache,
|
| 1605 |
+
output_attentions=output_attentions,
|
| 1606 |
+
output_hidden_states=output_hidden_states,
|
| 1607 |
+
return_dict=return_dict,
|
| 1608 |
+
cache_position=cache_position,
|
| 1609 |
+
)
|
| 1610 |
+
|
| 1611 |
+
hidden_states = outputs[0]
|
| 1612 |
+
if self.config.pretraining_tp > 1:
|
| 1613 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 1614 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 1615 |
+
logits = torch.cat(logits, dim=-1)
|
| 1616 |
+
else:
|
| 1617 |
+
logits = self.lm_head(hidden_states)
|
| 1618 |
+
logits = logits.float()
|
| 1619 |
+
|
| 1620 |
+
loss = None
|
| 1621 |
+
if labels is not None:
|
| 1622 |
+
# Change for MDM
|
| 1623 |
+
token_loss = F.cross_entropy(logits[masked_indices], labels[masked_indices], ignore_index=-100,
|
| 1624 |
+
reduction='none') / p_mask[masked_indices]
|
| 1625 |
+
loss = torch.sum(token_loss / noisy_data_length[masked_indices]) / labels.shape[0]
|
| 1626 |
+
|
| 1627 |
+
if not return_dict:
|
| 1628 |
+
output = (logits,) + outputs[1:]
|
| 1629 |
+
return (loss,) + output if loss is not None else output
|
| 1630 |
+
|
| 1631 |
+
return CausalLMOutputWithPast(
|
| 1632 |
+
loss=loss,
|
| 1633 |
+
logits=logits,
|
| 1634 |
+
past_key_values=outputs.past_key_values,
|
| 1635 |
+
hidden_states=outputs.hidden_states,
|
| 1636 |
+
attentions=outputs.attentions,
|
| 1637 |
+
)
|
| 1638 |
+
|
| 1639 |
+
def prepare_inputs_for_generation(
|
| 1640 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
|
| 1641 |
+
):
|
| 1642 |
+
# With static cache, the `past_key_values` is None
|
| 1643 |
+
# TODO joao: standardize interface for the different Cache classes and remove of this if
|
| 1644 |
+
has_static_cache = False
|
| 1645 |
+
if past_key_values is None:
|
| 1646 |
+
past_key_values = getattr(self.model.layers[0].self_attn, "past_key_value", None)
|
| 1647 |
+
has_static_cache = past_key_values is not None
|
| 1648 |
+
|
| 1649 |
+
past_length = 0
|
| 1650 |
+
if past_key_values is not None:
|
| 1651 |
+
if isinstance(past_key_values, Cache):
|
| 1652 |
+
past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
|
| 1653 |
+
max_cache_length = (
|
| 1654 |
+
torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
|
| 1655 |
+
if past_key_values.get_max_length() is not None
|
| 1656 |
+
else None
|
| 1657 |
+
)
|
| 1658 |
+
cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
|
| 1659 |
+
# TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
|
| 1660 |
+
else:
|
| 1661 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
| 1662 |
+
max_cache_length = None
|
| 1663 |
+
|
| 1664 |
+
# Keep only the unprocessed tokens:
|
| 1665 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
| 1666 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
| 1667 |
+
# input)
|
| 1668 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
| 1669 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
| 1670 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
| 1671 |
+
# input_ids based on the past_length.
|
| 1672 |
+
elif past_length < input_ids.shape[1]:
|
| 1673 |
+
input_ids = input_ids[:, past_length:]
|
| 1674 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
| 1675 |
+
|
| 1676 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
| 1677 |
+
if (
|
| 1678 |
+
max_cache_length is not None
|
| 1679 |
+
and attention_mask is not None
|
| 1680 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
| 1681 |
+
):
|
| 1682 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
| 1683 |
+
|
| 1684 |
+
position_ids = kwargs.get("position_ids", None)
|
| 1685 |
+
if attention_mask is not None and position_ids is None:
|
| 1686 |
+
# create position_ids on the fly for batch generation
|
| 1687 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1688 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1689 |
+
if past_key_values:
|
| 1690 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 1691 |
+
|
| 1692 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1693 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 1694 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 1695 |
+
else:
|
| 1696 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
| 1697 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
| 1698 |
+
# TODO: use `next_tokens` directly instead.
|
| 1699 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
| 1700 |
+
|
| 1701 |
+
input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
|
| 1702 |
+
if cache_position is None:
|
| 1703 |
+
cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
|
| 1704 |
+
else:
|
| 1705 |
+
cache_position = cache_position[-input_length:]
|
| 1706 |
+
|
| 1707 |
+
if has_static_cache:
|
| 1708 |
+
past_key_values = None
|
| 1709 |
+
|
| 1710 |
+
model_inputs.update(
|
| 1711 |
+
{
|
| 1712 |
+
"position_ids": position_ids,
|
| 1713 |
+
"cache_position": cache_position,
|
| 1714 |
+
"past_key_values": past_key_values,
|
| 1715 |
+
"use_cache": kwargs.get("use_cache"),
|
| 1716 |
+
"attention_mask": attention_mask,
|
| 1717 |
+
}
|
| 1718 |
+
)
|
| 1719 |
+
return model_inputs
|
| 1720 |
+
|
| 1721 |
+
@staticmethod
|
| 1722 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1723 |
+
reordered_past = ()
|
| 1724 |
+
for layer_past in past_key_values:
|
| 1725 |
+
reordered_past += (
|
| 1726 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1727 |
+
)
|
| 1728 |
+
return reordered_past
|
| 1729 |
+
|
| 1730 |
+
|
| 1731 |
+
@add_start_docstrings(
|
| 1732 |
+
"""
|
| 1733 |
+
The LLaDA Model transformer with a sequence classification head on top (linear layer).
|
| 1734 |
+
|
| 1735 |
+
[`LLaDAForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 1736 |
+
(e.g. GPT-2) do.
|
| 1737 |
+
|
| 1738 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1739 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1740 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1741 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1742 |
+
each row of the batch).
|
| 1743 |
+
""",
|
| 1744 |
+
LLaDA_START_DOCSTRING,
|
| 1745 |
+
)
|
| 1746 |
+
class LLaDAForSequenceClassification(LLaDAPreTrainedModel):
|
| 1747 |
+
def __init__(self, config):
|
| 1748 |
+
super().__init__(config)
|
| 1749 |
+
self.num_labels = config.num_labels
|
| 1750 |
+
self.model = LLaDAModel(config)
|
| 1751 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1752 |
+
|
| 1753 |
+
# Initialize weights and apply final processing
|
| 1754 |
+
self.post_init()
|
| 1755 |
+
|
| 1756 |
+
def get_input_embeddings(self):
|
| 1757 |
+
return self.model.embed_tokens
|
| 1758 |
+
|
| 1759 |
+
def set_input_embeddings(self, value):
|
| 1760 |
+
self.model.embed_tokens = value
|
| 1761 |
+
|
| 1762 |
+
@add_start_docstrings_to_model_forward(LLaDA_INPUTS_DOCSTRING)
|
| 1763 |
+
def forward(
|
| 1764 |
+
self,
|
| 1765 |
+
input_ids: torch.LongTensor = None,
|
| 1766 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1767 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1768 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1769 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1770 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1771 |
+
use_cache: Optional[bool] = None,
|
| 1772 |
+
output_attentions: Optional[bool] = None,
|
| 1773 |
+
output_hidden_states: Optional[bool] = None,
|
| 1774 |
+
return_dict: Optional[bool] = None,
|
| 1775 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1776 |
+
r"""
|
| 1777 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1778 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1779 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1780 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1781 |
+
"""
|
| 1782 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1783 |
+
|
| 1784 |
+
transformer_outputs = self.model(
|
| 1785 |
+
input_ids,
|
| 1786 |
+
attention_mask=attention_mask,
|
| 1787 |
+
position_ids=position_ids,
|
| 1788 |
+
past_key_values=past_key_values,
|
| 1789 |
+
inputs_embeds=inputs_embeds,
|
| 1790 |
+
use_cache=use_cache,
|
| 1791 |
+
output_attentions=output_attentions,
|
| 1792 |
+
output_hidden_states=output_hidden_states,
|
| 1793 |
+
return_dict=return_dict,
|
| 1794 |
+
)
|
| 1795 |
+
hidden_states = transformer_outputs[0]
|
| 1796 |
+
logits = self.score(hidden_states)
|
| 1797 |
+
|
| 1798 |
+
if input_ids is not None:
|
| 1799 |
+
batch_size = input_ids.shape[0]
|
| 1800 |
+
else:
|
| 1801 |
+
batch_size = inputs_embeds.shape[0]
|
| 1802 |
+
|
| 1803 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1804 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1805 |
+
if self.config.pad_token_id is None:
|
| 1806 |
+
sequence_lengths = -1
|
| 1807 |
+
else:
|
| 1808 |
+
if input_ids is not None:
|
| 1809 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1810 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1811 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1812 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1813 |
+
else:
|
| 1814 |
+
sequence_lengths = -1
|
| 1815 |
+
|
| 1816 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1817 |
+
|
| 1818 |
+
loss = None
|
| 1819 |
+
if labels is not None:
|
| 1820 |
+
labels = labels.to(logits.device)
|
| 1821 |
+
if self.config.problem_type is None:
|
| 1822 |
+
if self.num_labels == 1:
|
| 1823 |
+
self.config.problem_type = "regression"
|
| 1824 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1825 |
+
self.config.problem_type = "single_label_classification"
|
| 1826 |
+
else:
|
| 1827 |
+
self.config.problem_type = "multi_label_classification"
|
| 1828 |
+
|
| 1829 |
+
if self.config.problem_type == "regression":
|
| 1830 |
+
loss_fct = MSELoss()
|
| 1831 |
+
if self.num_labels == 1:
|
| 1832 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1833 |
+
else:
|
| 1834 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1835 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1836 |
+
loss_fct = CrossEntropyLoss()
|
| 1837 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1838 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1839 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1840 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1841 |
+
if not return_dict:
|
| 1842 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1843 |
+
return ((loss,) + output) if loss is not None else output
|
| 1844 |
+
|
| 1845 |
+
return SequenceClassifierOutputWithPast(
|
| 1846 |
+
loss=loss,
|
| 1847 |
+
logits=pooled_logits,
|
| 1848 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1849 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1850 |
+
attentions=transformer_outputs.attentions,
|
| 1851 |
+
)
|
| 1852 |
+
|
| 1853 |
+
|
| 1854 |
+
@add_start_docstrings(
|
| 1855 |
+
"""
|
| 1856 |
+
The LLaDA Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1857 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1858 |
+
""",
|
| 1859 |
+
LLaDA_START_DOCSTRING,
|
| 1860 |
+
)
|
| 1861 |
+
class LLaDAForQuestionAnswering(LLaDAPreTrainedModel):
|
| 1862 |
+
base_model_prefix = "transformer"
|
| 1863 |
+
|
| 1864 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->LLaDA
|
| 1865 |
+
def __init__(self, config):
|
| 1866 |
+
super().__init__(config)
|
| 1867 |
+
self.transformer = LLaDAModel(config)
|
| 1868 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1869 |
+
|
| 1870 |
+
# Initialize weights and apply final processing
|
| 1871 |
+
self.post_init()
|
| 1872 |
+
|
| 1873 |
+
def get_input_embeddings(self):
|
| 1874 |
+
return self.transformer.embed_tokens
|
| 1875 |
+
|
| 1876 |
+
def set_input_embeddings(self, value):
|
| 1877 |
+
self.transformer.embed_tokens = value
|
| 1878 |
+
|
| 1879 |
+
@add_start_docstrings_to_model_forward(LLaDA_INPUTS_DOCSTRING)
|
| 1880 |
+
def forward(
|
| 1881 |
+
self,
|
| 1882 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1883 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1884 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1885 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1886 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1887 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1888 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1889 |
+
output_attentions: Optional[bool] = None,
|
| 1890 |
+
output_hidden_states: Optional[bool] = None,
|
| 1891 |
+
return_dict: Optional[bool] = None,
|
| 1892 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1893 |
+
r"""
|
| 1894 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1895 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1896 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1897 |
+
are not taken into account for computing the loss.
|
| 1898 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1899 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1900 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1901 |
+
are not taken into account for computing the loss.
|
| 1902 |
+
"""
|
| 1903 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1904 |
+
|
| 1905 |
+
outputs = self.transformer(
|
| 1906 |
+
input_ids,
|
| 1907 |
+
attention_mask=attention_mask,
|
| 1908 |
+
position_ids=position_ids,
|
| 1909 |
+
past_key_values=past_key_values,
|
| 1910 |
+
inputs_embeds=inputs_embeds,
|
| 1911 |
+
output_attentions=output_attentions,
|
| 1912 |
+
output_hidden_states=output_hidden_states,
|
| 1913 |
+
return_dict=return_dict,
|
| 1914 |
+
)
|
| 1915 |
+
|
| 1916 |
+
sequence_output = outputs[0]
|
| 1917 |
+
|
| 1918 |
+
logits = self.qa_outputs(sequence_output)
|
| 1919 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1920 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1921 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1922 |
+
|
| 1923 |
+
total_loss = None
|
| 1924 |
+
if start_positions is not None and end_positions is not None:
|
| 1925 |
+
# If we are on multi-GPU, split add a dimension
|
| 1926 |
+
if len(start_positions.size()) > 1:
|
| 1927 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
| 1928 |
+
if len(end_positions.size()) > 1:
|
| 1929 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
| 1930 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1931 |
+
ignored_index = start_logits.size(1)
|
| 1932 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1933 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1934 |
+
|
| 1935 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1936 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1937 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1938 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1939 |
+
|
| 1940 |
+
if not return_dict:
|
| 1941 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1942 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1943 |
+
|
| 1944 |
+
return QuestionAnsweringModelOutput(
|
| 1945 |
+
loss=total_loss,
|
| 1946 |
+
start_logits=start_logits,
|
| 1947 |
+
end_logits=end_logits,
|
| 1948 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
# Adapted from https://huggingface.co/MILVLG/imp-v1-3b/blob/main/vision_encoder.py
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional, Tuple, Union, Dict
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from functools import partial, reduce
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import torch
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from torch import nn
|
| 12 |
+
import os
|
| 13 |
+
from transformers.image_processing_utils import BatchFeature, get_size_dict
|
| 14 |
+
from transformers.image_transforms import (
|
| 15 |
+
convert_to_rgb,
|
| 16 |
+
normalize,
|
| 17 |
+
rescale,
|
| 18 |
+
resize,
|
| 19 |
+
to_channel_dimension_format,
|
| 20 |
+
)
|
| 21 |
+
from transformers.image_utils import (
|
| 22 |
+
ChannelDimension,
|
| 23 |
+
PILImageResampling,
|
| 24 |
+
to_numpy_array,
|
| 25 |
+
)
|
| 26 |
+
from transformers.activations import ACT2FN
|
| 27 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 28 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 29 |
+
from transformers import PretrainedConfig
|
| 30 |
+
from transformers.utils import ModelOutput
|
| 31 |
+
from llava.utils import rank0_print
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SigLipImageProcessor:
|
| 35 |
+
def __init__(self, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), size=(384, 384), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
|
| 36 |
+
crop_size = crop_size if crop_size is not None else {"height": 384, "width": 384}
|
| 37 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
| 38 |
+
|
| 39 |
+
self.image_mean = image_mean
|
| 40 |
+
self.image_std = image_std
|
| 41 |
+
self.size = size
|
| 42 |
+
self.resample = resample
|
| 43 |
+
self.rescale_factor = rescale_factor
|
| 44 |
+
self.data_format = data_format
|
| 45 |
+
self.crop_size = crop_size
|
| 46 |
+
|
| 47 |
+
def preprocess(self, images, return_tensors):
|
| 48 |
+
if isinstance(images, Image.Image):
|
| 49 |
+
images = [images]
|
| 50 |
+
else:
|
| 51 |
+
# to adapt video data
|
| 52 |
+
images = [to_numpy_array(image) for image in images]
|
| 53 |
+
assert isinstance(images, list)
|
| 54 |
+
|
| 55 |
+
transforms = [
|
| 56 |
+
convert_to_rgb,
|
| 57 |
+
to_numpy_array,
|
| 58 |
+
partial(resize, size=self.size, resample=self.resample, data_format=self.data_format),
|
| 59 |
+
partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
|
| 60 |
+
partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
|
| 61 |
+
partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
images = reduce(lambda x, f: [*map(f, x)], transforms, images)
|
| 65 |
+
data = {"pixel_values": images}
|
| 66 |
+
|
| 67 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class SigLipVisionConfig(PretrainedConfig):
|
| 71 |
+
model_type = "siglip_vision_model"
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
hidden_size=1152,
|
| 76 |
+
image_mean=(0.5, 0.5, 0.5),
|
| 77 |
+
intermediate_size=4304,
|
| 78 |
+
num_hidden_layers=27,
|
| 79 |
+
num_attention_heads=16,
|
| 80 |
+
num_channels=3,
|
| 81 |
+
image_size=384,
|
| 82 |
+
patch_size=14,
|
| 83 |
+
hidden_act="gelu_pytorch_tanh",
|
| 84 |
+
layer_norm_eps=1e-6,
|
| 85 |
+
attention_dropout=0.0,
|
| 86 |
+
**kwargs,
|
| 87 |
+
):
|
| 88 |
+
super().__init__(**kwargs)
|
| 89 |
+
|
| 90 |
+
self.hidden_size = hidden_size
|
| 91 |
+
self.intermediate_size = intermediate_size
|
| 92 |
+
self.num_hidden_layers = num_hidden_layers
|
| 93 |
+
self.num_attention_heads = num_attention_heads
|
| 94 |
+
self.num_channels = num_channels
|
| 95 |
+
self.patch_size = patch_size
|
| 96 |
+
self.image_size = image_size
|
| 97 |
+
self.attention_dropout = attention_dropout
|
| 98 |
+
self.layer_norm_eps = layer_norm_eps
|
| 99 |
+
self.hidden_act = hidden_act
|
| 100 |
+
self.image_mean = image_mean
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 104 |
+
cls._set_token_in_kwargs(kwargs)
|
| 105 |
+
|
| 106 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 107 |
+
|
| 108 |
+
# get the vision config dict if we are loading from SigLipConfig
|
| 109 |
+
if config_dict.get("model_type") == "siglip":
|
| 110 |
+
config_dict = config_dict["vision_config"]
|
| 111 |
+
|
| 112 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 113 |
+
print(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
|
| 114 |
+
|
| 115 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dataclass
|
| 119 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->SigLip
|
| 120 |
+
class SigLipVisionModelOutput(ModelOutput):
|
| 121 |
+
"""
|
| 122 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 126 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 127 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 128 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 129 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 130 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 131 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 132 |
+
|
| 133 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 134 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 135 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 136 |
+
sequence_length)`.
|
| 137 |
+
|
| 138 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 139 |
+
heads.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 143 |
+
last_hidden_state: torch.FloatTensor = None
|
| 144 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 145 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class SigLipVisionEmbeddings(nn.Module):
|
| 149 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.config = config
|
| 152 |
+
self.embed_dim = config.hidden_size
|
| 153 |
+
self.image_size = config.image_size
|
| 154 |
+
self.patch_size = config.patch_size
|
| 155 |
+
|
| 156 |
+
self.patch_embedding = nn.Conv2d(
|
| 157 |
+
in_channels=config.num_channels,
|
| 158 |
+
out_channels=self.embed_dim,
|
| 159 |
+
kernel_size=self.patch_size,
|
| 160 |
+
stride=self.patch_size,
|
| 161 |
+
padding="valid",
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 165 |
+
self.num_positions = self.num_patches
|
| 166 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 167 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 168 |
+
|
| 169 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 170 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
| 171 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
| 172 |
+
|
| 173 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 174 |
+
return embeddings
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SigLipAttention(nn.Module):
|
| 178 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 179 |
+
|
| 180 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
|
| 181 |
+
def __init__(self, config):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.config = config
|
| 184 |
+
self.embed_dim = config.hidden_size
|
| 185 |
+
self.num_heads = config.num_attention_heads
|
| 186 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 187 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 188 |
+
raise ValueError(f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads}).")
|
| 189 |
+
self.scale = self.head_dim**-0.5
|
| 190 |
+
self.dropout = config.attention_dropout
|
| 191 |
+
|
| 192 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 193 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 194 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 195 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 196 |
+
|
| 197 |
+
def forward(
|
| 198 |
+
self,
|
| 199 |
+
hidden_states: torch.Tensor,
|
| 200 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 201 |
+
output_attentions: Optional[bool] = False,
|
| 202 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 203 |
+
"""Input shape: Batch x Time x Channel"""
|
| 204 |
+
|
| 205 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 206 |
+
|
| 207 |
+
query_states = self.q_proj(hidden_states)
|
| 208 |
+
key_states = self.k_proj(hidden_states)
|
| 209 |
+
value_states = self.v_proj(hidden_states)
|
| 210 |
+
|
| 211 |
+
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 212 |
+
key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 213 |
+
value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 214 |
+
|
| 215 |
+
k_v_seq_len = key_states.shape[-2]
|
| 216 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
|
| 217 |
+
|
| 218 |
+
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
|
| 219 |
+
raise ValueError(f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is" f" {attn_weights.size()}")
|
| 220 |
+
|
| 221 |
+
if attention_mask is not None:
|
| 222 |
+
if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
|
| 223 |
+
raise ValueError(f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}")
|
| 224 |
+
attn_weights = attn_weights + attention_mask
|
| 225 |
+
|
| 226 |
+
# upcast attention to fp32
|
| 227 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 228 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 229 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 230 |
+
|
| 231 |
+
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
|
| 232 |
+
raise ValueError(f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}")
|
| 233 |
+
|
| 234 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 235 |
+
attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
|
| 236 |
+
|
| 237 |
+
attn_output = self.out_proj(attn_output)
|
| 238 |
+
|
| 239 |
+
return attn_output, attn_weights
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->SigLip
|
| 243 |
+
class SigLipMLP(nn.Module):
|
| 244 |
+
def __init__(self, config):
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.config = config
|
| 247 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 248 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 249 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 250 |
+
|
| 251 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 252 |
+
hidden_states = self.fc1(hidden_states)
|
| 253 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 254 |
+
hidden_states = self.fc2(hidden_states)
|
| 255 |
+
return hidden_states
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->SigLip
|
| 259 |
+
class SigLipEncoderLayer(nn.Module):
|
| 260 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 261 |
+
super().__init__()
|
| 262 |
+
self.embed_dim = config.hidden_size
|
| 263 |
+
self.self_attn = SigLipAttention(config)
|
| 264 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 265 |
+
self.mlp = SigLipMLP(config)
|
| 266 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 267 |
+
|
| 268 |
+
# Ignore copy
|
| 269 |
+
def forward(
|
| 270 |
+
self,
|
| 271 |
+
hidden_states: torch.Tensor,
|
| 272 |
+
attention_mask: torch.Tensor,
|
| 273 |
+
output_attentions: Optional[bool] = False,
|
| 274 |
+
) -> Tuple[torch.FloatTensor]:
|
| 275 |
+
"""
|
| 276 |
+
Args:
|
| 277 |
+
hidden_states (`torch.FloatTensor`):
|
| 278 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 279 |
+
attention_mask (`torch.FloatTensor`):
|
| 280 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 281 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 282 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 283 |
+
returned tensors for more detail.
|
| 284 |
+
"""
|
| 285 |
+
residual = hidden_states
|
| 286 |
+
|
| 287 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 288 |
+
hidden_states, attn_weights = self.self_attn(
|
| 289 |
+
hidden_states=hidden_states,
|
| 290 |
+
attention_mask=attention_mask,
|
| 291 |
+
output_attentions=output_attentions,
|
| 292 |
+
)
|
| 293 |
+
hidden_states = residual + hidden_states
|
| 294 |
+
|
| 295 |
+
residual = hidden_states
|
| 296 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 297 |
+
hidden_states = self.mlp(hidden_states)
|
| 298 |
+
hidden_states = residual + hidden_states
|
| 299 |
+
|
| 300 |
+
outputs = (hidden_states,)
|
| 301 |
+
|
| 302 |
+
if output_attentions:
|
| 303 |
+
outputs += (attn_weights,)
|
| 304 |
+
|
| 305 |
+
return outputs
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class SigLipPreTrainedModel(PreTrainedModel):
|
| 309 |
+
"""
|
| 310 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 311 |
+
models.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
config_class = SigLipVisionConfig
|
| 315 |
+
base_model_prefix = "siglip"
|
| 316 |
+
supports_gradient_checkpointing = True
|
| 317 |
+
|
| 318 |
+
def _init_weights(self, module):
|
| 319 |
+
"""Initialize the weights"""
|
| 320 |
+
pass
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->SigLip
|
| 324 |
+
class SigLipEncoder(nn.Module):
|
| 325 |
+
"""
|
| 326 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 327 |
+
[`SigLipEncoderLayer`].
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
config: SigLipVisionConfig
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 334 |
+
super().__init__()
|
| 335 |
+
self.config = config
|
| 336 |
+
self.layers = nn.ModuleList([SigLipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 337 |
+
self.gradient_checkpointing = False
|
| 338 |
+
|
| 339 |
+
# Ignore copy
|
| 340 |
+
def forward(
|
| 341 |
+
self,
|
| 342 |
+
inputs_embeds,
|
| 343 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 344 |
+
output_attentions: Optional[bool] = None,
|
| 345 |
+
output_hidden_states: Optional[bool] = None,
|
| 346 |
+
return_dict: Optional[bool] = None,
|
| 347 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 348 |
+
r"""
|
| 349 |
+
Args:
|
| 350 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 351 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 352 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 353 |
+
than the model's internal embedding lookup matrix.
|
| 354 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 355 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 356 |
+
|
| 357 |
+
- 1 for tokens that are **not masked**,
|
| 358 |
+
- 0 for tokens that are **masked**.
|
| 359 |
+
|
| 360 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 361 |
+
output_attentions (`bool`, *optional*):
|
| 362 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 363 |
+
returned tensors for more detail.
|
| 364 |
+
output_hidden_states (`bool`, *optional*):
|
| 365 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 366 |
+
for more detail.
|
| 367 |
+
return_dict (`bool`, *optional*):
|
| 368 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 369 |
+
"""
|
| 370 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 371 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 372 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 373 |
+
|
| 374 |
+
encoder_states = () if output_hidden_states else None
|
| 375 |
+
all_attentions = () if output_attentions else None
|
| 376 |
+
|
| 377 |
+
hidden_states = inputs_embeds
|
| 378 |
+
for encoder_layer in self.layers:
|
| 379 |
+
if output_hidden_states:
|
| 380 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 381 |
+
if self.gradient_checkpointing and self.training:
|
| 382 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 383 |
+
encoder_layer.__call__,
|
| 384 |
+
hidden_states,
|
| 385 |
+
attention_mask,
|
| 386 |
+
output_attentions,
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
layer_outputs = encoder_layer(
|
| 390 |
+
hidden_states,
|
| 391 |
+
attention_mask,
|
| 392 |
+
output_attentions=output_attentions,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
hidden_states = layer_outputs[0]
|
| 396 |
+
|
| 397 |
+
if output_attentions:
|
| 398 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 399 |
+
|
| 400 |
+
if output_hidden_states:
|
| 401 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 402 |
+
|
| 403 |
+
if not return_dict:
|
| 404 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 405 |
+
return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class SigLipVisionTransformer(nn.Module):
|
| 409 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.config = config
|
| 412 |
+
embed_dim = config.hidden_size
|
| 413 |
+
|
| 414 |
+
self.embeddings = SigLipVisionEmbeddings(config)
|
| 415 |
+
self.encoder = SigLipEncoder(config)
|
| 416 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 417 |
+
self.head = SigLipMultiheadAttentionPoolingHead(config)
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
pixel_values,
|
| 422 |
+
output_attentions: Optional[bool] = None,
|
| 423 |
+
output_hidden_states: Optional[bool] = None,
|
| 424 |
+
return_dict: Optional[bool] = None,
|
| 425 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 426 |
+
r"""
|
| 427 |
+
Returns:
|
| 428 |
+
|
| 429 |
+
"""
|
| 430 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 431 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 432 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 433 |
+
|
| 434 |
+
hidden_states = self.embeddings(pixel_values)
|
| 435 |
+
|
| 436 |
+
encoder_outputs = self.encoder(
|
| 437 |
+
inputs_embeds=hidden_states,
|
| 438 |
+
output_attentions=output_attentions,
|
| 439 |
+
output_hidden_states=output_hidden_states,
|
| 440 |
+
return_dict=return_dict,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
last_hidden_state = encoder_outputs[0]
|
| 444 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 445 |
+
|
| 446 |
+
pooled_output = self.head(last_hidden_state)
|
| 447 |
+
|
| 448 |
+
if not return_dict:
|
| 449 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 450 |
+
|
| 451 |
+
return BaseModelOutputWithPooling(
|
| 452 |
+
last_hidden_state=last_hidden_state,
|
| 453 |
+
pooler_output=pooled_output,
|
| 454 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 455 |
+
attentions=encoder_outputs.attentions,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class SigLipMultiheadAttentionPoolingHead(nn.Module):
|
| 460 |
+
"""Multihead Attention Pooling."""
|
| 461 |
+
|
| 462 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 463 |
+
super().__init__()
|
| 464 |
+
|
| 465 |
+
self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 466 |
+
self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
|
| 467 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 468 |
+
self.mlp = SigLipMLP(config)
|
| 469 |
+
|
| 470 |
+
def forward(self, hidden_state):
|
| 471 |
+
batch_size = hidden_state.shape[0]
|
| 472 |
+
probe = self.probe.repeat(batch_size, 1, 1)
|
| 473 |
+
|
| 474 |
+
hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
|
| 475 |
+
|
| 476 |
+
residual = hidden_state
|
| 477 |
+
hidden_state = self.layernorm(hidden_state)
|
| 478 |
+
hidden_state = residual + self.mlp(hidden_state)
|
| 479 |
+
|
| 480 |
+
return hidden_state[:, 0]
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class SigLipVisionModel(SigLipPreTrainedModel):
|
| 484 |
+
config_class = SigLipVisionConfig
|
| 485 |
+
main_input_name = "pixel_values"
|
| 486 |
+
_no_split_modules = ["SigLipEncoderLayer"]
|
| 487 |
+
|
| 488 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 489 |
+
super().__init__(config)
|
| 490 |
+
|
| 491 |
+
self.vision_model = SigLipVisionTransformer(config)
|
| 492 |
+
|
| 493 |
+
# Initialize weights and apply final processing
|
| 494 |
+
self.post_init()
|
| 495 |
+
|
| 496 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 497 |
+
return self.vision_model.embeddings.patch_embedding
|
| 498 |
+
|
| 499 |
+
def forward(
|
| 500 |
+
self,
|
| 501 |
+
pixel_values,
|
| 502 |
+
output_attentions: Optional[bool] = None,
|
| 503 |
+
output_hidden_states: Optional[bool] = None,
|
| 504 |
+
return_dict: Optional[bool] = None,
|
| 505 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 506 |
+
r"""
|
| 507 |
+
Returns:
|
| 508 |
+
|
| 509 |
+
Examples:
|
| 510 |
+
|
| 511 |
+
```python
|
| 512 |
+
>>> from PIL import Image
|
| 513 |
+
>>> import requests
|
| 514 |
+
>>> from transformers import AutoProcessor, SigLipVisionModel
|
| 515 |
+
|
| 516 |
+
>>> model = SigLipVisionModel.from_pretrained("google/siglip-base-patch16-224")
|
| 517 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 518 |
+
|
| 519 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 520 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 521 |
+
|
| 522 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 523 |
+
|
| 524 |
+
>>> outputs = model(**inputs)
|
| 525 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 526 |
+
>>> pooled_output = outputs.pooler_output # pooled features
|
| 527 |
+
```"""
|
| 528 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 529 |
+
|
| 530 |
+
return self.vision_model(
|
| 531 |
+
pixel_values=pixel_values,
|
| 532 |
+
output_attentions=output_attentions,
|
| 533 |
+
output_hidden_states=output_hidden_states,
|
| 534 |
+
return_dict=return_dict,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class SigLipVisionTower(nn.Module):
|
| 539 |
+
def __init__(self, vision_tower, vision_tower_cfg, delay_load=False):
|
| 540 |
+
super().__init__()
|
| 541 |
+
|
| 542 |
+
self.is_loaded = False
|
| 543 |
+
|
| 544 |
+
self.config = SigLipVisionConfig()
|
| 545 |
+
|
| 546 |
+
self.vision_tower_name = vision_tower
|
| 547 |
+
|
| 548 |
+
self.image_processor = SigLipImageProcessor()
|
| 549 |
+
|
| 550 |
+
if not delay_load:
|
| 551 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 552 |
+
self.load_model()
|
| 553 |
+
elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
|
| 554 |
+
# TODO: better detector is needed.
|
| 555 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 556 |
+
self.load_model()
|
| 557 |
+
elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
|
| 558 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 559 |
+
self.load_model()
|
| 560 |
+
else:
|
| 561 |
+
self.cfg_only = self.config
|
| 562 |
+
|
| 563 |
+
def load_model(self, device_map=None):
|
| 564 |
+
if self.is_loaded:
|
| 565 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 566 |
+
return
|
| 567 |
+
|
| 568 |
+
self.vision_tower = SigLipVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 569 |
+
|
| 570 |
+
del self.vision_tower.vision_model.encoder.layers[-1:]
|
| 571 |
+
self.vision_tower.vision_model.head = nn.Identity()
|
| 572 |
+
self.vision_tower.requires_grad_(False)
|
| 573 |
+
|
| 574 |
+
self.is_loaded = True
|
| 575 |
+
|
| 576 |
+
def forward(self, images):
|
| 577 |
+
if type(images) is list:
|
| 578 |
+
image_features = []
|
| 579 |
+
for image in images:
|
| 580 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 581 |
+
image_feature = image_forward_out.hidden_states[-1].to(image.dtype)
|
| 582 |
+
assert image_features.shape[-2] == 729
|
| 583 |
+
image_features.append(image_feature)
|
| 584 |
+
else:
|
| 585 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 586 |
+
image_features = image_forward_outs.hidden_states[-1].to(images.dtype)
|
| 587 |
+
assert image_features.shape[-2] == 729
|
| 588 |
+
|
| 589 |
+
return image_features
|
| 590 |
+
|
| 591 |
+
@property
|
| 592 |
+
def dummy_feature(self):
|
| 593 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 594 |
+
|
| 595 |
+
@property
|
| 596 |
+
def dtype(self):
|
| 597 |
+
for p in self.vision_tower.parameters():
|
| 598 |
+
return p.dtype
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
def device(self):
|
| 602 |
+
for p in self.vision_tower.parameters():
|
| 603 |
+
return p.device
|
| 604 |
+
|
| 605 |
+
@property
|
| 606 |
+
def hidden_size(self):
|
| 607 |
+
return self.config.hidden_size
|
| 608 |
+
|
| 609 |
+
@property
|
| 610 |
+
def num_patches(self):
|
| 611 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 612 |
+
|
| 613 |
+
@property
|
| 614 |
+
def num_patches_per_side(self):
|
| 615 |
+
return self.config.image_size // self.config.patch_size
|
| 616 |
+
# return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]
|
| 617 |
+
|
| 618 |
+
@property
|
| 619 |
+
def image_size(self):
|
| 620 |
+
return self.config.image_size
|