Upload 5 files
Browse files- configuration_friday.py +5 -0
- configuration_phi3.py +226 -0
- friday_map.py +4 -0
- modeling_friday.py +1248 -0
- modeling_phi3.py +1181 -0
configuration_friday.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .modeling_friday import FridayConfig
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
"FridayConfig",
|
| 5 |
+
]
|
configuration_phi3.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""Phi-3 model configuration"""
|
| 17 |
+
|
| 18 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 19 |
+
from transformers.utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Phi3Config(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
|
| 28 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 29 |
+
defaults will yield a similar configuration to that of the
|
| 30 |
+
[microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 32064):
|
| 37 |
+
Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`Phi3Model`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 3072):
|
| 40 |
+
Dimension of the hidden representations.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
| 42 |
+
Dimension of the MLP representations.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 44 |
+
Number of hidden layers in the Transformer decoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 47 |
+
num_key_value_heads (`int`, *optional*):
|
| 48 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 49 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 50 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 51 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 52 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 53 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 54 |
+
`num_attention_heads`.
|
| 55 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
| 56 |
+
Dropout probability for mlp outputs.
|
| 57 |
+
embd_pdrop (`int`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout ratio for the embeddings.
|
| 59 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio after computing the attention scores.
|
| 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 4096):
|
| 64 |
+
The maximum sequence length that this model might ever be used with.
|
| 65 |
+
original_max_position_embeddings (`int`, *optional*, defaults to 4096):
|
| 66 |
+
The maximum sequence length that this model was trained with. This is used to determine the size of the
|
| 67 |
+
original RoPE embeddings when using long scaling.
|
| 68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 69 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 70 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 71 |
+
The epsilon value used for the RMSNorm.
|
| 72 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 74 |
+
relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
|
| 75 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether to tie weight embeddings
|
| 77 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 78 |
+
The base period of the RoPE embeddings.
|
| 79 |
+
rope_scaling (`dict`, *optional*):
|
| 80 |
+
The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
|
| 81 |
+
contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
|
| 82 |
+
the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
|
| 83 |
+
divided by the number of attention heads divided by 2.
|
| 84 |
+
partial_rotary_factor (`float`, *optional*, defaults to 1.0):
|
| 85 |
+
Percentage of the query and keys which will have rotary embedding. Must be between 0.0 and 1.0.
|
| 86 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 87 |
+
The id of the "beginning-of-sequence" token.
|
| 88 |
+
eos_token_id (`int`, *optional*, defaults to 32000):
|
| 89 |
+
The id of the "end-of-sequence" token.
|
| 90 |
+
pad_token_id (`int`, *optional*, defaults to 32000):
|
| 91 |
+
The id of the padding token.
|
| 92 |
+
sliding_window (`int`, *optional*):
|
| 93 |
+
Sliding window attention window size. If `None`, no sliding window is applied.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import Phi3Model, Phi3Config
|
| 99 |
+
|
| 100 |
+
>>> # Initializing a Phi-3 style configuration
|
| 101 |
+
>>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
| 102 |
+
|
| 103 |
+
>>> # Initializing a model from the configuration
|
| 104 |
+
>>> model = Phi3Model(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```"""
|
| 109 |
+
|
| 110 |
+
model_type = "phi3"
|
| 111 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_size=32064,
|
| 116 |
+
hidden_size=3072,
|
| 117 |
+
intermediate_size=8192,
|
| 118 |
+
num_hidden_layers=32,
|
| 119 |
+
num_attention_heads=32,
|
| 120 |
+
num_key_value_heads=None,
|
| 121 |
+
resid_pdrop=0.0,
|
| 122 |
+
embd_pdrop=0.0,
|
| 123 |
+
attention_dropout=0.0,
|
| 124 |
+
hidden_act="silu",
|
| 125 |
+
max_position_embeddings=4096,
|
| 126 |
+
original_max_position_embeddings=4096,
|
| 127 |
+
initializer_range=0.02,
|
| 128 |
+
rms_norm_eps=1e-5,
|
| 129 |
+
use_cache=True,
|
| 130 |
+
tie_word_embeddings=False,
|
| 131 |
+
rope_theta=10000.0,
|
| 132 |
+
rope_scaling=None,
|
| 133 |
+
partial_rotary_factor=1.0,
|
| 134 |
+
bos_token_id=1,
|
| 135 |
+
eos_token_id=32000,
|
| 136 |
+
pad_token_id=32000,
|
| 137 |
+
sliding_window=None,
|
| 138 |
+
**kwargs,
|
| 139 |
+
):
|
| 140 |
+
self.vocab_size = vocab_size
|
| 141 |
+
self.hidden_size = hidden_size
|
| 142 |
+
self.intermediate_size = intermediate_size
|
| 143 |
+
self.num_hidden_layers = num_hidden_layers
|
| 144 |
+
self.num_attention_heads = num_attention_heads
|
| 145 |
+
|
| 146 |
+
if num_key_value_heads is None:
|
| 147 |
+
num_key_value_heads = num_attention_heads
|
| 148 |
+
|
| 149 |
+
self.num_key_value_heads = num_key_value_heads
|
| 150 |
+
self.resid_pdrop = resid_pdrop
|
| 151 |
+
self.embd_pdrop = embd_pdrop
|
| 152 |
+
self.attention_dropout = attention_dropout
|
| 153 |
+
self.hidden_act = hidden_act
|
| 154 |
+
self.max_position_embeddings = max_position_embeddings
|
| 155 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
| 156 |
+
self.initializer_range = initializer_range
|
| 157 |
+
self.rms_norm_eps = rms_norm_eps
|
| 158 |
+
self.use_cache = use_cache
|
| 159 |
+
self.rope_theta = rope_theta
|
| 160 |
+
self.rope_scaling = rope_scaling
|
| 161 |
+
self.partial_rotary_factor = partial_rotary_factor
|
| 162 |
+
self._rope_scaling_adjustment()
|
| 163 |
+
self._rope_scaling_validation()
|
| 164 |
+
self.sliding_window = sliding_window
|
| 165 |
+
|
| 166 |
+
super().__init__(
|
| 167 |
+
bos_token_id=bos_token_id,
|
| 168 |
+
eos_token_id=eos_token_id,
|
| 169 |
+
pad_token_id=pad_token_id,
|
| 170 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 171 |
+
**kwargs,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def _rope_scaling_adjustment(self):
|
| 175 |
+
"""
|
| 176 |
+
Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
|
| 177 |
+
"""
|
| 178 |
+
if self.rope_scaling is None:
|
| 179 |
+
return
|
| 180 |
+
|
| 181 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 182 |
+
|
| 183 |
+
# For backward compatibility if previous version used "su" or "yarn"
|
| 184 |
+
if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
|
| 185 |
+
self.rope_scaling["type"] = "longrope"
|
| 186 |
+
|
| 187 |
+
def _rope_scaling_validation(self):
|
| 188 |
+
"""
|
| 189 |
+
Validate the `rope_scaling` configuration.
|
| 190 |
+
"""
|
| 191 |
+
if self.rope_scaling is None:
|
| 192 |
+
return
|
| 193 |
+
|
| 194 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
|
| 195 |
+
raise ValueError(
|
| 196 |
+
"`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
|
| 197 |
+
f"got {self.rope_scaling}"
|
| 198 |
+
)
|
| 199 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 200 |
+
rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
|
| 201 |
+
rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
|
| 202 |
+
if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
|
| 203 |
+
raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
|
| 204 |
+
if not (
|
| 205 |
+
isinstance(rope_scaling_short_factor, list)
|
| 206 |
+
and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
|
| 207 |
+
):
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
|
| 210 |
+
)
|
| 211 |
+
rotary_ndims = int(self.hidden_size // self.num_attention_heads * self.partial_rotary_factor)
|
| 212 |
+
if not len(rope_scaling_short_factor) == rotary_ndims // 2:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"`rope_scaling`'s short_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_short_factor)}"
|
| 215 |
+
)
|
| 216 |
+
if not (
|
| 217 |
+
isinstance(rope_scaling_long_factor, list)
|
| 218 |
+
and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
|
| 219 |
+
):
|
| 220 |
+
raise ValueError(
|
| 221 |
+
f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
|
| 222 |
+
)
|
| 223 |
+
if not len(rope_scaling_long_factor) == rotary_ndims // 2:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"`rope_scaling`'s long_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_long_factor)}"
|
| 226 |
+
)
|
friday_map.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .configuration_friday import FridayConfig # your real class
|
| 2 |
+
from .modeling_friday import FridayForCausalLM
|
| 3 |
+
|
| 4 |
+
__all__ = ["FridayForCausalLM", "FridayConfig"]
|
modeling_friday.py
ADDED
|
@@ -0,0 +1,1248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
# Model Constants
|
| 4 |
+
IMAGE_TOKEN = "<image>"
|
| 5 |
+
IMG_START_TOKEN = "<img_start>"
|
| 6 |
+
IMG_END_TOKEN = "<img_end>"
|
| 7 |
+
IGNORE_INDEX = -100
|
| 8 |
+
PAD_FOR_EOS = -300
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
def mask_token_segment(
|
| 23 |
+
start_id: int,
|
| 24 |
+
end_id: int,
|
| 25 |
+
input_ids: torch.Tensor,
|
| 26 |
+
fill_value: int = -100):
|
| 27 |
+
"""
|
| 28 |
+
Replace *every* token from each `start_id` **through** its matching `end_id`
|
| 29 |
+
(boundaries included) with `fill_value`. Any spans that start with some
|
| 30 |
+
other token are left untouched.
|
| 31 |
+
|
| 32 |
+
Works on CUDA, TorchScript, batched via vmap, etc.—no Python loops.
|
| 33 |
+
"""
|
| 34 |
+
if input_ids.dim() != 1:
|
| 35 |
+
raise ValueError("`input_ids` must be 1-D")
|
| 36 |
+
|
| 37 |
+
device = input_ids.device
|
| 38 |
+
n = input_ids.size(0)
|
| 39 |
+
|
| 40 |
+
# where the *target* start-tokens and end-tokens sit
|
| 41 |
+
start_pos = (input_ids == start_id).nonzero(as_tuple=True)[0] # ascending
|
| 42 |
+
end_pos = (input_ids == end_id).nonzero(as_tuple=True)[0] # ascending
|
| 43 |
+
|
| 44 |
+
if start_pos.numel() == 0:
|
| 45 |
+
return input_ids.clone()
|
| 46 |
+
|
| 47 |
+
# ── pair every start with the first end that comes *after* it ────────────────
|
| 48 |
+
# searchsorted gives the insertion index into the (sorted) end positions
|
| 49 |
+
idx_in_end = torch.searchsorted(end_pos, start_pos, right=False)
|
| 50 |
+
|
| 51 |
+
have_match = idx_in_end < end_pos.size(0) # safety: drop unmatched
|
| 52 |
+
start_pos = start_pos[have_match]
|
| 53 |
+
end_pos = end_pos[idx_in_end[have_match]]
|
| 54 |
+
|
| 55 |
+
# (rare) guard against pathological orderings
|
| 56 |
+
keep = end_pos > start_pos
|
| 57 |
+
start_pos, end_pos = start_pos[keep], end_pos[keep]
|
| 58 |
+
|
| 59 |
+
if start_pos.numel() == 0:
|
| 60 |
+
return input_ids
|
| 61 |
+
|
| 62 |
+
# ── differential “scan-line” trick to build the span mask in O(N) ───────────
|
| 63 |
+
# +1 at each start index, -1 at the element *after* each end
|
| 64 |
+
delta = torch.zeros(n + 1, dtype=torch.int8, device=device)
|
| 65 |
+
delta[start_pos] += 1
|
| 66 |
+
delta[end_pos + 1] -= 1 # +1 is safe because delta is length n+1
|
| 67 |
+
|
| 68 |
+
inside = torch.cumsum(delta[:-1], dim=0) > 0 # boolean mask, incl. boundaries
|
| 69 |
+
|
| 70 |
+
# ── apply ────────────────────────────────────────────────────────────────────
|
| 71 |
+
out = input_ids.clone()
|
| 72 |
+
out[inside] = fill_value
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
| 78 |
+
from deepspeed import zero
|
| 79 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
| 80 |
+
if hasattr(param, "ds_id"):
|
| 81 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
| 82 |
+
if not ignore_status:
|
| 83 |
+
print(name, 'no ignore status')
|
| 84 |
+
with zero.GatheredParameters([param]):
|
| 85 |
+
param = param.data.detach().cpu().clone()
|
| 86 |
+
else:
|
| 87 |
+
param = param.detach().cpu().clone()
|
| 88 |
+
return param
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# Borrowed from peft.util.get_peft_model_state_dict
|
| 92 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
| 93 |
+
if bias == "none":
|
| 94 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
| 95 |
+
elif bias == "all":
|
| 96 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
| 97 |
+
elif bias == "lora_only":
|
| 98 |
+
to_return = {}
|
| 99 |
+
maybe_lora_bias = {}
|
| 100 |
+
lora_bias_names = set()
|
| 101 |
+
for k, t in named_params:
|
| 102 |
+
if "lora_" in k:
|
| 103 |
+
to_return[k] = t
|
| 104 |
+
bias_name = k.split("lora_")[0] + "bias"
|
| 105 |
+
lora_bias_names.add(bias_name)
|
| 106 |
+
elif "bias" in k:
|
| 107 |
+
maybe_lora_bias[k] = t
|
| 108 |
+
for k, t in maybe_lora_bias:
|
| 109 |
+
if bias_name in lora_bias_names:
|
| 110 |
+
to_return[bias_name] = t
|
| 111 |
+
else:
|
| 112 |
+
raise NotImplementedError
|
| 113 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
|
| 114 |
+
return to_return
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
| 118 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
| 119 |
+
if require_grad_only:
|
| 120 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
| 121 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
| 122 |
+
return to_return
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def find_all_linear_names(modules):
|
| 126 |
+
lora_module_names = set()
|
| 127 |
+
for name, module in modules():
|
| 128 |
+
if isinstance(module, torch.nn.Linear):
|
| 129 |
+
names = name.split('.')
|
| 130 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
|
| 131 |
+
|
| 132 |
+
if 'lm_head' in lora_module_names: # needed for 16-bit
|
| 133 |
+
lora_module_names.remove('lm_head')
|
| 134 |
+
return list(lora_module_names)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def expand2square(pil_img, background_color):
|
| 138 |
+
width, height = pil_img.size
|
| 139 |
+
if width == height:
|
| 140 |
+
return pil_img
|
| 141 |
+
elif width > height:
|
| 142 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 143 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 144 |
+
return result
|
| 145 |
+
else:
|
| 146 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 147 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
def pad_and_stack(img_list, pad_value=0.0):
|
| 151 |
+
"""
|
| 152 |
+
img_list : list[Tensor] each (C, H, W) already *normalised*
|
| 153 |
+
pad_value: float or tuple/list of 3 floats (one per channel)
|
| 154 |
+
Use 0.0 if your processor has already centred to mean 0.
|
| 155 |
+
Returns
|
| 156 |
+
-------
|
| 157 |
+
batch : Tensor (B, C, H_max, W_max)
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
# 1. target square size ---------------------------------------------------
|
| 161 |
+
h_max = max(t.shape[1] for t in img_list)
|
| 162 |
+
w_max = max(t.shape[2] for t in img_list)
|
| 163 |
+
H, W = max(h_max, w_max), max(h_max, w_max)
|
| 164 |
+
|
| 165 |
+
# 2. create padded copies -------------------------------------------------
|
| 166 |
+
padded = []
|
| 167 |
+
for img in img_list:
|
| 168 |
+
c, h, w = img.shape
|
| 169 |
+
canvas = img.new_full((c, H, W), pad_value) # filled with mean/zeros
|
| 170 |
+
canvas[:, :h, :w] = img # top-left corner
|
| 171 |
+
padded.append(canvas)
|
| 172 |
+
|
| 173 |
+
return torch.stack(padded, 0) # (B,C,H,W)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ------------------------------------------------------------------------------------------
|
| 180 |
+
# Copyright (c) 2024 Baifeng Shi.
|
| 181 |
+
# All rights reserved.
|
| 182 |
+
#
|
| 183 |
+
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
|
| 184 |
+
# ------------------------------------------------------------------------------------------
|
| 185 |
+
|
| 186 |
+
import torch
|
| 187 |
+
|
| 188 |
+
def split_chessboard(x, num_split):
|
| 189 |
+
"""
|
| 190 |
+
x: b * c * h * w
|
| 191 |
+
Deividing x into num_split**2 sub-squares, and concatenate all the sub-squares on the batch dimension
|
| 192 |
+
"""
|
| 193 |
+
B, C, H, W = x.shape
|
| 194 |
+
assert H % num_split == 0 and W % num_split == 0
|
| 195 |
+
h, w = H // num_split, W // num_split
|
| 196 |
+
x_split = torch.cat([x[:, :, i*h:(i+1)*h, j*w:(j+1)*w] for i in range(num_split) for j in range(num_split)], dim=0)
|
| 197 |
+
return x_split
|
| 198 |
+
|
| 199 |
+
def merge_chessboard(x, num_split):
|
| 200 |
+
"""
|
| 201 |
+
x: b * c * h * w
|
| 202 |
+
Assuming x contains num_split**2 sub-squares concatenated along batch dimension, merge the sub-squares back to the original whole square.
|
| 203 |
+
(inverse of split_chessboard)
|
| 204 |
+
"""
|
| 205 |
+
B, C, H, W = x.shape
|
| 206 |
+
assert B % (num_split**2) == 0
|
| 207 |
+
b = B // (num_split**2)
|
| 208 |
+
x_merge = torch.cat([torch.cat([x[(i*num_split + j)*b:(i*num_split + j + 1)*b] for j in range(num_split)], dim=-1)
|
| 209 |
+
for i in range(num_split)], dim=-2)
|
| 210 |
+
return x_merge
|
| 211 |
+
|
| 212 |
+
def batched_forward(model, x, batch_size=-1):
|
| 213 |
+
if batch_size == -1:
|
| 214 |
+
return model(x)
|
| 215 |
+
else:
|
| 216 |
+
x_batched = x.split(batch_size)
|
| 217 |
+
outs = [model(x) for x in x_batched]
|
| 218 |
+
return torch.cat(outs, dim=0)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# ------------------------------------------------------------------------------------------
|
| 227 |
+
# Copyright (c) 2024 Baifeng Shi.
|
| 228 |
+
# All rights reserved.
|
| 229 |
+
#
|
| 230 |
+
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
|
| 231 |
+
# ------------------------------------------------------------------------------------------
|
| 232 |
+
|
| 233 |
+
import math
|
| 234 |
+
import torch
|
| 235 |
+
import torch.nn.functional as F
|
| 236 |
+
from einops import rearrange
|
| 237 |
+
|
| 238 |
+
def multiscale_forward(model, input, scales=None, img_sizes=None, max_split_size=None, resize_output_to_idx=0, num_prefix_token=0,
|
| 239 |
+
output_shape='bnc', split_forward=False):
|
| 240 |
+
|
| 241 |
+
# print(f"Input shape: {input.shape}")
|
| 242 |
+
|
| 243 |
+
assert input.dim() == 4, "Input image must be in the shape of BxCxHxW."
|
| 244 |
+
assert input.shape[2] == input.shape[3], "Currently only square images are supported."
|
| 245 |
+
assert output_shape in ['bnc', 'bchw'], "Output shape should be either BxNxC (e.g., ViT) or BxCxHxW (e.g., ConvNet)."
|
| 246 |
+
assert output_shape == 'bnc' or num_prefix_token == 0, "For ConvNet there shouldn't be any prefix token."
|
| 247 |
+
|
| 248 |
+
b, c, input_size, _ = input.shape
|
| 249 |
+
|
| 250 |
+
# image size for each scale
|
| 251 |
+
assert scales is not None or img_sizes is not None, "Please assign either scales or img_sizes."
|
| 252 |
+
img_sizes = img_sizes or [int(input_size * scale) for scale in scales]
|
| 253 |
+
|
| 254 |
+
# prepare multiscale inputs
|
| 255 |
+
max_split_size = max_split_size or input_size # The maximum size of each split of image. Set as the input size by default
|
| 256 |
+
num_splits = [math.ceil(size / max_split_size) for size in img_sizes] # number of splits each scale
|
| 257 |
+
input_multiscale = []
|
| 258 |
+
for size, num_split in zip(img_sizes, num_splits):
|
| 259 |
+
x = F.interpolate(input.to(torch.float32), size=size, mode='bicubic').to(input.dtype)
|
| 260 |
+
x = split_chessboard(x, num_split=num_split)
|
| 261 |
+
input_multiscale.append(x)
|
| 262 |
+
|
| 263 |
+
# run feedforward on each scale
|
| 264 |
+
outs_multiscale = [batched_forward(model, x, b) if split_forward else model(x) for x in input_multiscale]
|
| 265 |
+
if num_prefix_token > 0:
|
| 266 |
+
outs_prefix_multiscale = [out[:, :num_prefix_token] for out in outs_multiscale]
|
| 267 |
+
outs_multiscale = [out[:, num_prefix_token:] for out in outs_multiscale]
|
| 268 |
+
if output_shape == 'bnc':
|
| 269 |
+
outs_multiscale = [rearrange(out, 'b (h w) c -> b c h w', h=int(out.shape[1] ** 0.5), w=int(out.shape[1] ** 0.5))
|
| 270 |
+
for out in outs_multiscale]
|
| 271 |
+
|
| 272 |
+
# merge outputs of different splits for each scale separately
|
| 273 |
+
outs_multiscale = [merge_chessboard(out, num_split=num_split) for num_split, out in zip(num_splits, outs_multiscale)]
|
| 274 |
+
|
| 275 |
+
# interpolate outputs from different scales and concat together
|
| 276 |
+
output_size = outs_multiscale[resize_output_to_idx].shape[-2]
|
| 277 |
+
out = torch.cat([F.interpolate(outs_multiscale[i].to(torch.float32), size=output_size,
|
| 278 |
+
mode='area').to(outs_multiscale[i].dtype)
|
| 279 |
+
for i in range(len(outs_multiscale))], dim=1)
|
| 280 |
+
if output_shape == 'bnc':
|
| 281 |
+
out = rearrange(out, 'b c h w -> b (h w) c')
|
| 282 |
+
if num_prefix_token > 0:
|
| 283 |
+
# take the mean of prefix tokens from different splits for each scale
|
| 284 |
+
outs_prefix_multiscale = [torch.stack(out.split(b, dim=0), dim=0).mean(dim=0) for out in outs_prefix_multiscale]
|
| 285 |
+
out_prefix_multiscale = torch.cat(outs_prefix_multiscale, dim=-1)
|
| 286 |
+
out = torch.cat([out_prefix_multiscale, out], dim=1)
|
| 287 |
+
|
| 288 |
+
return out
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
import torch
|
| 295 |
+
import torch.nn as nn
|
| 296 |
+
|
| 297 |
+
class MLPAdapter(nn.Module):
|
| 298 |
+
|
| 299 |
+
def __init__(self, input_dim, hidden_dim, output_dim, num_layers=2, activation='gelu', checkpoint_path=None, device=None, **kwargs):
|
| 300 |
+
"""
|
| 301 |
+
Initialize the MLPAdapter with the given dimensions and activation function.
|
| 302 |
+
|
| 303 |
+
Args:
|
| 304 |
+
input_dim (int): Input dimension.
|
| 305 |
+
hidden_dim (int): Hidden dimension.
|
| 306 |
+
output_dim (int): Output dimension.
|
| 307 |
+
layers (int): Number of layers in the MLP.
|
| 308 |
+
activation (str): Activation function to use ('gelu' or 'relu').
|
| 309 |
+
"""
|
| 310 |
+
super().__init__()
|
| 311 |
+
self.num_layers = num_layers
|
| 312 |
+
self.activation = activation
|
| 313 |
+
self.output_dim = output_dim
|
| 314 |
+
|
| 315 |
+
# Define the first layer
|
| 316 |
+
layers_list = [nn.Linear(input_dim, hidden_dim, device=device)]
|
| 317 |
+
if activation == 'gelu':
|
| 318 |
+
layers_list.append(nn.GELU())
|
| 319 |
+
elif activation == 'relu':
|
| 320 |
+
layers_list.append(nn.ReLU())
|
| 321 |
+
else:
|
| 322 |
+
raise ValueError("Unsupported activation function. Use 'gelu' or 'relu'.")
|
| 323 |
+
|
| 324 |
+
# Define the subsequent layers
|
| 325 |
+
for _ in range(1, num_layers):
|
| 326 |
+
layers_list.append(nn.Linear(hidden_dim, hidden_dim, device=device))
|
| 327 |
+
if activation == 'gelu':
|
| 328 |
+
layers_list.append(nn.GELU())
|
| 329 |
+
elif activation == 'relu':
|
| 330 |
+
layers_list.append(nn.ReLU())
|
| 331 |
+
|
| 332 |
+
# Define the final output layer
|
| 333 |
+
layers_list.append(nn.Linear(hidden_dim, output_dim, device=device))
|
| 334 |
+
self.mlp = nn.Sequential(*layers_list)
|
| 335 |
+
|
| 336 |
+
# Load checkpoint if provided
|
| 337 |
+
if checkpoint_path:
|
| 338 |
+
self.load_state_dict(torch.load(checkpoint_path, map_location=device), strict=False)
|
| 339 |
+
print(f"Loaded MLPAdapter from {checkpoint_path}")
|
| 340 |
+
|
| 341 |
+
if device:
|
| 342 |
+
self.to(device)
|
| 343 |
+
|
| 344 |
+
def forward(self, x):
|
| 345 |
+
"""
|
| 346 |
+
Forward pass through the MLPAdapter.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
x (torch.Tensor): Input tensor.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
torch.Tensor: Output tensor after passing through the MLP.
|
| 353 |
+
"""
|
| 354 |
+
return self.mlp(x)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
import torch
|
| 360 |
+
import torch.nn as nn
|
| 361 |
+
import torch.nn.functional as F
|
| 362 |
+
|
| 363 |
+
import PIL.Image
|
| 364 |
+
from typing import List
|
| 365 |
+
|
| 366 |
+
from transformers import AutoModel, AutoImageProcessor
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class FastVitVisionTower(nn.Module):
|
| 370 |
+
def __init__(self, pretrained_model_name_or_path, model_params={}, pad_to_square=True, **kwargs):
|
| 371 |
+
super().__init__()
|
| 372 |
+
|
| 373 |
+
self.is_loaded = False
|
| 374 |
+
self.pretrained_model_name_or_path = pretrained_model_name_or_path
|
| 375 |
+
self.model_params = model_params
|
| 376 |
+
self.pad_to_square = pad_to_square
|
| 377 |
+
self.load_model()
|
| 378 |
+
|
| 379 |
+
@property
|
| 380 |
+
def output_dim(self):
|
| 381 |
+
return self.vision_tower.config.embed_dim if self.vision_tower else None
|
| 382 |
+
|
| 383 |
+
def load_model(self):
|
| 384 |
+
if self.is_loaded:
|
| 385 |
+
return
|
| 386 |
+
self.image_processor = AutoImageProcessor.from_pretrained(self.pretrained_model_name_or_path)
|
| 387 |
+
self.image_processor.crop_size = self.image_processor.size
|
| 388 |
+
self.vision_tower = AutoModel.from_pretrained(
|
| 389 |
+
self.pretrained_model_name_or_path,
|
| 390 |
+
**self.model_params,
|
| 391 |
+
)
|
| 392 |
+
self.vision_tower.requires_grad_(False)
|
| 393 |
+
|
| 394 |
+
self.is_loaded = True
|
| 395 |
+
|
| 396 |
+
def preprocess_images(self, imgs: List[PIL.Image.Image], pad_and_stack_tensors=True) -> torch.Tensor:
|
| 397 |
+
img_mean = tuple(int(x * 255) for x in self.image_processor.image_mean)
|
| 398 |
+
if self.pad_to_square:
|
| 399 |
+
imgs = [expand2square(img, img_mean) for img in imgs]
|
| 400 |
+
|
| 401 |
+
imgs = [self.image_processor(img, do_resize=True, do_center_crop=False, return_tensors="pt")['pixel_values'][0] for img in imgs]
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
if pad_and_stack_tensors:
|
| 405 |
+
imgs = pad_and_stack(imgs, pad_value=0.0)
|
| 406 |
+
imgs = imgs.to(dtype=torch.float32, device=self.device)
|
| 407 |
+
|
| 408 |
+
return imgs
|
| 409 |
+
|
| 410 |
+
def forward(self, images):
|
| 411 |
+
if type(images) is list:
|
| 412 |
+
image_features = []
|
| 413 |
+
for image in images:
|
| 414 |
+
image_feature = self.vision_tower(
|
| 415 |
+
image.to(device=self.device, dtype=self.dtype).unsqueeze(0)
|
| 416 |
+
)
|
| 417 |
+
image_features.append(image_feature)
|
| 418 |
+
else:
|
| 419 |
+
image_features = self.vision_tower(
|
| 420 |
+
images.to(device=self.device, dtype=self.dtype),
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
return image_features
|
| 424 |
+
|
| 425 |
+
@property
|
| 426 |
+
def dummy_feature(self):
|
| 427 |
+
return torch.zeros(1, self.embed_dim, device=self.device, dtype=self.dtype)
|
| 428 |
+
|
| 429 |
+
@property
|
| 430 |
+
def dtype(self):
|
| 431 |
+
return self.vision_tower.dtype
|
| 432 |
+
|
| 433 |
+
@property
|
| 434 |
+
def device(self):
|
| 435 |
+
return self.vision_tower.device
|
| 436 |
+
|
| 437 |
+
@property
|
| 438 |
+
def config(self):
|
| 439 |
+
if self.is_loaded:
|
| 440 |
+
return self.vision_tower.config
|
| 441 |
+
else:
|
| 442 |
+
return self.cfg_only
|
| 443 |
+
|
| 444 |
+
@property
|
| 445 |
+
def hidden_size(self):
|
| 446 |
+
return self.config.embed_dim
|
| 447 |
+
|
| 448 |
+
@property
|
| 449 |
+
def num_patches(self):
|
| 450 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class FastVitVisionTowerS2(FastVitVisionTower):
|
| 454 |
+
def __init__(self, pretrained_model_name_or_path, s2_scales, model_params={}, **kwargs):
|
| 455 |
+
self.s2_scales = list(map(int, s2_scales.split(',')))
|
| 456 |
+
self.s2_scales.sort()
|
| 457 |
+
self.s2_split_size = self.s2_scales[0]
|
| 458 |
+
self.s2_image_size = self.s2_scales[-1]
|
| 459 |
+
|
| 460 |
+
super().__init__(pretrained_model_name_or_path, model_params)
|
| 461 |
+
|
| 462 |
+
self.multiscale_forward = multiscale_forward
|
| 463 |
+
|
| 464 |
+
@property
|
| 465 |
+
def output_dim(self):
|
| 466 |
+
return (2*self.vision_tower.config.embed_dim) if self.vision_tower else None
|
| 467 |
+
|
| 468 |
+
def load_model(self):
|
| 469 |
+
if self.is_loaded:
|
| 470 |
+
return
|
| 471 |
+
|
| 472 |
+
super().load_model()
|
| 473 |
+
self.image_processor.size = self.image_processor.crop_size = {
|
| 474 |
+
"height": self.s2_image_size,
|
| 475 |
+
"width": self.s2_image_size
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
def forward_feature(self, images):
|
| 479 |
+
image_size = self.vision_tower.config.image_size
|
| 480 |
+
if images.shape[2] != image_size or images.shape[3] != image_size:
|
| 481 |
+
images = F.interpolate(
|
| 482 |
+
images,
|
| 483 |
+
size=(image_size, image_size),
|
| 484 |
+
mode="bilinear",
|
| 485 |
+
align_corners=False,
|
| 486 |
+
antialias=True
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
return self.vision_tower(
|
| 490 |
+
images.to(device=self.device, dtype=self.dtype),
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
def forward(self, images):
|
| 494 |
+
if type(images) is list:
|
| 495 |
+
image_features = []
|
| 496 |
+
for image in images:
|
| 497 |
+
image_feature = self.multiscale_forward(
|
| 498 |
+
self.forward_feature,
|
| 499 |
+
image.unsqueeze(0),
|
| 500 |
+
img_sizes=self.s2_scales,
|
| 501 |
+
max_split_size=self.s2_split_size
|
| 502 |
+
)
|
| 503 |
+
image_features.append(image_feature)
|
| 504 |
+
else:
|
| 505 |
+
image_features = self.multiscale_forward(
|
| 506 |
+
self.forward_feature,
|
| 507 |
+
images,
|
| 508 |
+
img_sizes=self.s2_scales,
|
| 509 |
+
max_split_size=self.s2_split_size
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
return image_features
|
| 513 |
+
|
| 514 |
+
@property
|
| 515 |
+
def hidden_size(self):
|
| 516 |
+
return self.config.embed_dim * len(self.s2_scales)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
import torch
|
| 523 |
+
import torch.nn as nn
|
| 524 |
+
|
| 525 |
+
import PIL.Image
|
| 526 |
+
from typing import List
|
| 527 |
+
|
| 528 |
+
from transformers import SiglipVisionModel, SiglipImageProcessor, SiglipVisionConfig
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class SiglipVisionTower(nn.Module):
|
| 532 |
+
def __init__(self, pretrained_model_name_or_path, model_params={}, pad_to_square=True, **kwargs):
|
| 533 |
+
super().__init__()
|
| 534 |
+
|
| 535 |
+
self.is_loaded = False
|
| 536 |
+
self.pretrained_model_name_or_path = pretrained_model_name_or_path
|
| 537 |
+
self.model_params = model_params
|
| 538 |
+
self.pad_to_square = pad_to_square
|
| 539 |
+
self.select_layer = -2
|
| 540 |
+
self.load_model()
|
| 541 |
+
|
| 542 |
+
@property
|
| 543 |
+
def output_dim(self):
|
| 544 |
+
return self.vision_tower.config.hidden_size if self.vision_tower else None
|
| 545 |
+
|
| 546 |
+
def load_model(self):
|
| 547 |
+
if self.is_loaded:
|
| 548 |
+
return
|
| 549 |
+
self.image_processor = SiglipImageProcessor.from_pretrained(self.pretrained_model_name_or_path)
|
| 550 |
+
self.image_processor.crop_size = self.image_processor.size
|
| 551 |
+
self.vision_tower = SiglipVisionModel.from_pretrained(
|
| 552 |
+
self.pretrained_model_name_or_path,
|
| 553 |
+
**self.model_params,
|
| 554 |
+
)
|
| 555 |
+
self.vision_tower.requires_grad_(False)
|
| 556 |
+
|
| 557 |
+
self.is_loaded = True
|
| 558 |
+
|
| 559 |
+
def preprocess_images(self, imgs: List[PIL.Image.Image], pad_and_stack_tensors=True) -> torch.Tensor:
|
| 560 |
+
img_mean = tuple(int(x * 255) for x in self.image_processor.image_mean)
|
| 561 |
+
if self.pad_to_square:
|
| 562 |
+
imgs = [expand2square(img, img_mean) for img in imgs]
|
| 563 |
+
imgs = [self.image_processor(img, return_tensors="pt")['pixel_values'][0] for img in imgs]
|
| 564 |
+
|
| 565 |
+
if pad_and_stack_tensors:
|
| 566 |
+
imgs = pad_and_stack(imgs, pad_value=0.0)
|
| 567 |
+
imgs = imgs.to(dtype=torch.float32, device=self.device)
|
| 568 |
+
|
| 569 |
+
return imgs
|
| 570 |
+
|
| 571 |
+
def feature_select(self, image_forward_outs):
|
| 572 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 573 |
+
|
| 574 |
+
return image_features
|
| 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),
|
| 581 |
+
output_hidden_states=True)
|
| 582 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 583 |
+
image_features.append(image_feature)
|
| 584 |
+
else:
|
| 585 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype),
|
| 586 |
+
output_hidden_states=True)
|
| 587 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 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 |
+
return self.vision_tower.dtype
|
| 598 |
+
|
| 599 |
+
@property
|
| 600 |
+
def device(self):
|
| 601 |
+
return self.vision_tower.device
|
| 602 |
+
|
| 603 |
+
@property
|
| 604 |
+
def config(self):
|
| 605 |
+
if self.is_loaded:
|
| 606 |
+
return self.vision_tower.config
|
| 607 |
+
else:
|
| 608 |
+
return self.cfg_only
|
| 609 |
+
|
| 610 |
+
@property
|
| 611 |
+
def hidden_size(self):
|
| 612 |
+
return self.config.hidden_size
|
| 613 |
+
|
| 614 |
+
@property
|
| 615 |
+
def num_patches(self):
|
| 616 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class SiglipVisionTowerS2(SiglipVisionTower):
|
| 620 |
+
def __init__(self, pretrained_model_name_or_path, s2_scales, model_params={}, **kwargs):
|
| 621 |
+
self.s2_scales = list(map(int, s2_scales.split(',')))
|
| 622 |
+
self.s2_scales.sort()
|
| 623 |
+
self.s2_split_size = self.s2_scales[0]
|
| 624 |
+
self.s2_image_size = self.s2_scales[-1]
|
| 625 |
+
|
| 626 |
+
super().__init__(pretrained_model_name_or_path, model_params)
|
| 627 |
+
|
| 628 |
+
self.multiscale_forward = multiscale_forward
|
| 629 |
+
|
| 630 |
+
self.image_processor.size['height'] = self.image_processor.size['width'] = self.s2_image_size
|
| 631 |
+
self.image_processor.crop_size['height'] = self.image_processor.crop_size['width'] = self.s2_image_size
|
| 632 |
+
|
| 633 |
+
@property
|
| 634 |
+
def output_dim(self):
|
| 635 |
+
return (2*self.vision_tower.config.hidden_size) if self.vision_tower else None
|
| 636 |
+
|
| 637 |
+
def load_model(self):
|
| 638 |
+
if self.is_loaded:
|
| 639 |
+
return
|
| 640 |
+
|
| 641 |
+
super().load_model()
|
| 642 |
+
self.image_processor.size['height'] = self.image_processor.size['width'] = self.s2_image_size
|
| 643 |
+
self.image_processor.crop_size['height'] = self.image_processor.crop_size['width'] = self.s2_image_size
|
| 644 |
+
|
| 645 |
+
def forward_feature(self, images):
|
| 646 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype),
|
| 647 |
+
output_hidden_states=True)
|
| 648 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 649 |
+
return image_features
|
| 650 |
+
|
| 651 |
+
def forward(self, images):
|
| 652 |
+
if type(images) is list:
|
| 653 |
+
image_features = []
|
| 654 |
+
for image in images:
|
| 655 |
+
image_feature = self.multiscale_forward(
|
| 656 |
+
self.forward_feature,
|
| 657 |
+
image.unsqueeze(0),
|
| 658 |
+
img_sizes=self.s2_scales,
|
| 659 |
+
max_split_size=self.s2_split_size
|
| 660 |
+
)
|
| 661 |
+
image_features.append(image_feature)
|
| 662 |
+
else:
|
| 663 |
+
image_features = self.multiscale_forward(
|
| 664 |
+
self.forward_feature,
|
| 665 |
+
images,
|
| 666 |
+
img_sizes=self.s2_scales,
|
| 667 |
+
max_split_size=self.s2_split_size
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
return image_features
|
| 671 |
+
|
| 672 |
+
@property
|
| 673 |
+
def hidden_size(self):
|
| 674 |
+
return self.config.hidden_size * len(self.s2_scales)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
import torch
|
| 683 |
+
import torch.nn as nn
|
| 684 |
+
import torch.nn.functional as F
|
| 685 |
+
from torchvision import transforms
|
| 686 |
+
|
| 687 |
+
from typing import List, Tuple, Optional, Union
|
| 688 |
+
|
| 689 |
+
import PIL
|
| 690 |
+
|
| 691 |
+
from transformers import AutoTokenizer, AutoConfig
|
| 692 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 693 |
+
|
| 694 |
+
from .configuration_phi3 import Phi3Config
|
| 695 |
+
from .modeling_phi3 import Phi3Model, Phi3ForCausalLM
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
DEFAULT_CFG_SPECIAL_TOKENS = {
|
| 699 |
+
"image_token_id": 200029,
|
| 700 |
+
"image_start_token_id": 200030,
|
| 701 |
+
"image_end_token_id": 200031,
|
| 702 |
+
}
|
| 703 |
+
DEFAULT_CFG_VISION_TOWER = {
|
| 704 |
+
"pretrained_model_name_or_path": "kevin510/fast-vit-hd",
|
| 705 |
+
"type": "fastvit",
|
| 706 |
+
"s2_scales": "512,1024",
|
| 707 |
+
"use_s2": True,
|
| 708 |
+
"pad_to_square": True,
|
| 709 |
+
"freeze": False,
|
| 710 |
+
"model_params": { "trust_remote_code": True }
|
| 711 |
+
}
|
| 712 |
+
DEFAULT_CFG_VISION_ADAPTER = {
|
| 713 |
+
"input_dim": 6144,
|
| 714 |
+
"hidden_dim": 3072,
|
| 715 |
+
"output_dim": 3072,
|
| 716 |
+
"layers": 2,
|
| 717 |
+
"activation": "gelu",
|
| 718 |
+
"freeze": False,
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class FridayConfig(Phi3Config):
|
| 723 |
+
model_type = "friday"
|
| 724 |
+
|
| 725 |
+
def __init__(self,
|
| 726 |
+
base_model_name_or_path: str | None = "microsoft/Phi-4-mini-reasoning",
|
| 727 |
+
delay_load=False,
|
| 728 |
+
tokenizer_model_max_length=None,
|
| 729 |
+
**kwargs
|
| 730 |
+
):
|
| 731 |
+
base_kwargs = {}
|
| 732 |
+
if base_model_name_or_path is not None:
|
| 733 |
+
base_cfg = AutoConfig.from_pretrained(
|
| 734 |
+
base_model_name_or_path,
|
| 735 |
+
trust_remote_code=True, # Phi‑4 uses custom code in the repo
|
| 736 |
+
)
|
| 737 |
+
base_kwargs = base_cfg.to_dict()
|
| 738 |
+
|
| 739 |
+
merged = {**base_kwargs, **kwargs}
|
| 740 |
+
self.delay_load = delay_load
|
| 741 |
+
self.tokenizer_model_max_length = tokenizer_model_max_length
|
| 742 |
+
|
| 743 |
+
self._cfg_vision_tower = DEFAULT_CFG_VISION_TOWER.copy()
|
| 744 |
+
if "cfg_vision_tower" in kwargs:
|
| 745 |
+
self._cfg_vision_tower.update(kwargs["cfg_vision_tower"])
|
| 746 |
+
|
| 747 |
+
self._cfg_vision_adapter = DEFAULT_CFG_VISION_ADAPTER.copy()
|
| 748 |
+
if "cfg_vision_adapter" in kwargs:
|
| 749 |
+
self._cfg_vision_adapter.update(kwargs["cfg_vision_adapter"])
|
| 750 |
+
|
| 751 |
+
self._cfg_special_tokens = DEFAULT_CFG_SPECIAL_TOKENS.copy()
|
| 752 |
+
if "cfg_special_tokens" in kwargs:
|
| 753 |
+
self._cfg_special_tokens.update(kwargs["cfg_special_tokens"])
|
| 754 |
+
|
| 755 |
+
super().__init__(**merged)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
@property
|
| 759 |
+
def cfg_vision_tower(self):
|
| 760 |
+
return self._cfg_vision_tower
|
| 761 |
+
|
| 762 |
+
@cfg_vision_tower.setter
|
| 763 |
+
def cfg_vision_tower(self, value):
|
| 764 |
+
if not value:
|
| 765 |
+
raise ValueError("Name cannot be empty")
|
| 766 |
+
self._cfg_vision_tower.update(value)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@property
|
| 770 |
+
def cfg_vision_adapter(self):
|
| 771 |
+
return self._cfg_vision_adapter
|
| 772 |
+
|
| 773 |
+
@cfg_vision_adapter.setter
|
| 774 |
+
def cfg_vision_adapter(self, value):
|
| 775 |
+
if not value:
|
| 776 |
+
raise ValueError("Name cannot be empty")
|
| 777 |
+
self._cfg_vision_adapter.update(value)
|
| 778 |
+
|
| 779 |
+
@property
|
| 780 |
+
def cfg_special_tokens(self):
|
| 781 |
+
return self._cfg_special_tokens
|
| 782 |
+
|
| 783 |
+
@cfg_special_tokens.setter
|
| 784 |
+
def cfg_special_tokens(self, value):
|
| 785 |
+
if not value:
|
| 786 |
+
raise ValueError("Name cannot be empty")
|
| 787 |
+
self._cfg_special_tokens.update(value)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class FridayModel(Phi3Model):
|
| 791 |
+
config_class = FridayConfig
|
| 792 |
+
|
| 793 |
+
def __init__(self, config: FridayConfig):
|
| 794 |
+
super().__init__(config)
|
| 795 |
+
|
| 796 |
+
self.cfg_vision_adapter = config.cfg_vision_adapter
|
| 797 |
+
self.cfg_vision_tower = config.cfg_vision_tower
|
| 798 |
+
|
| 799 |
+
self.vision_tower = None
|
| 800 |
+
self.mm_projector = None
|
| 801 |
+
if not config.delay_load:
|
| 802 |
+
self.initialize_vision_modules()
|
| 803 |
+
|
| 804 |
+
def get_vision_tower(self):
|
| 805 |
+
return self.vision_tower
|
| 806 |
+
|
| 807 |
+
def initialize_vision_modules(self):
|
| 808 |
+
if self.vision_tower is not None:
|
| 809 |
+
return
|
| 810 |
+
|
| 811 |
+
if self.cfg_vision_tower.get("type", "siglip").lower() == "siglip":
|
| 812 |
+
if self.cfg_vision_tower.get("use_s2", True):
|
| 813 |
+
self.vision_tower = SiglipVisionTowerS2(**self.cfg_vision_tower)
|
| 814 |
+
else:
|
| 815 |
+
self.vision_tower = SiglipVisionTower(**self.cfg_vision_tower)
|
| 816 |
+
elif self.cfg_vision_tower.get("type", "siglip").lower() == "fastvit":
|
| 817 |
+
if self.cfg_vision_tower.get("use_s2", True):
|
| 818 |
+
self.vision_tower = FastVitVisionTowerS2(**self.cfg_vision_tower)
|
| 819 |
+
else:
|
| 820 |
+
self.vision_tower = FastVitVisionTower(**self.cfg_vision_tower)
|
| 821 |
+
else:
|
| 822 |
+
raise ValueError(f"Unsupported vision tower type: {self.cfg_vision_tower.get('type', 'siglip')}. Supported types are 'siglip' and 'fastvit'.")
|
| 823 |
+
|
| 824 |
+
self.vision_tower.load_model()
|
| 825 |
+
self.mm_projector = MLPAdapter(**self.cfg_vision_adapter)
|
| 826 |
+
|
| 827 |
+
if self.cfg_vision_tower.get("freeze", False):
|
| 828 |
+
self.set_vision_tower_requires_grad(False)
|
| 829 |
+
|
| 830 |
+
if self.cfg_vision_adapter.get("freeze", False):
|
| 831 |
+
self.set_vision_adapter_requires_grad(False)
|
| 832 |
+
|
| 833 |
+
def compute_image_features(self, imgs: torch.Tensor) -> torch.Tensor:
|
| 834 |
+
features = self.vision_tower(imgs)
|
| 835 |
+
if isinstance(features, list):
|
| 836 |
+
features = torch.stack(features, dim=1)
|
| 837 |
+
return self.mm_projector(features)
|
| 838 |
+
|
| 839 |
+
def set_vision_tower_requires_grad(self, requires_grad: bool):
|
| 840 |
+
if self.vision_tower is not None:
|
| 841 |
+
for param in self.vision_tower.parameters():
|
| 842 |
+
param.requires_grad = requires_grad
|
| 843 |
+
else:
|
| 844 |
+
raise ValueError("Vision tower is not initialized. Please call initialize_vision_modules() first.")
|
| 845 |
+
|
| 846 |
+
def set_vision_adapter_requires_grad(self, requires_grad: bool):
|
| 847 |
+
if self.mm_projector is not None:
|
| 848 |
+
for param in self.mm_projector.parameters():
|
| 849 |
+
param.requires_grad = requires_grad
|
| 850 |
+
else:
|
| 851 |
+
raise ValueError("Vision adapter is not initialized. Please call initialize_vision_modules() first.")
|
| 852 |
+
|
| 853 |
+
def set_vision_tower_dtype(self, dtype: torch.dtype):
|
| 854 |
+
if self.vision_tower is not None:
|
| 855 |
+
for p in self.vision_tower.parameters():
|
| 856 |
+
p.data = p.data.to(dtype)
|
| 857 |
+
else:
|
| 858 |
+
raise ValueError("Vision tower is not initialized. Please call initialize_vision_modules() first.")
|
| 859 |
+
|
| 860 |
+
def set_vision_adapter_dtype(self, dtype: torch.dtype):
|
| 861 |
+
if self.mm_projector is not None:
|
| 862 |
+
for p in self.mm_projector.parameters():
|
| 863 |
+
p.data = p.data.to(dtype)
|
| 864 |
+
else:
|
| 865 |
+
raise ValueError("Vision adapter is not initialized. Please call initialize_vision_modules() first.")
|
| 866 |
+
|
| 867 |
+
def is_vision_tower_frozen(self):
|
| 868 |
+
if self.vision_tower is not None:
|
| 869 |
+
return all(not p.requires_grad for p in self.vision_tower.parameters())
|
| 870 |
+
else:
|
| 871 |
+
raise ValueError("Vision tower is not initialized. Please call initialize_vision_modules() first.")
|
| 872 |
+
|
| 873 |
+
def is_vision_adapter_frozen(self):
|
| 874 |
+
if self.mm_projector is not None:
|
| 875 |
+
return all(not p.requires_grad for p in self.mm_projector.parameters())
|
| 876 |
+
else:
|
| 877 |
+
raise ValueError("Vision adapter is not initialized. Please call initialize_vision_modules() first.")
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
class FridayForCausalLM(Phi3ForCausalLM):
|
| 881 |
+
config_class = FridayConfig
|
| 882 |
+
|
| 883 |
+
def __init__(self, config: FridayConfig):
|
| 884 |
+
super().__init__(config)
|
| 885 |
+
|
| 886 |
+
self.config = config
|
| 887 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 888 |
+
self.image_token_id = config.cfg_special_tokens["image_token_id"]
|
| 889 |
+
self.image_start_id = config.cfg_special_tokens["image_start_token_id"]
|
| 890 |
+
self.image_end_id = config.cfg_special_tokens["image_end_token_id"]
|
| 891 |
+
|
| 892 |
+
self.model = FridayModel(config)
|
| 893 |
+
self.post_init()
|
| 894 |
+
|
| 895 |
+
def get_model(self) -> FridayModel:
|
| 896 |
+
return self.model
|
| 897 |
+
|
| 898 |
+
def get_vision_tower(self) -> SiglipVisionTower:
|
| 899 |
+
return self.model.get_vision_tower()
|
| 900 |
+
|
| 901 |
+
def get_vision_adapter(self) -> MLPAdapter:
|
| 902 |
+
return self.model.mm_projector
|
| 903 |
+
|
| 904 |
+
def get_llm_parameters(self, exclude_lora: bool = False):
|
| 905 |
+
return [
|
| 906 |
+
p for n, p in self.named_parameters()
|
| 907 |
+
if "vision_tower" not in n and "mm_projector" not in n and (not exclude_lora or ("lora_" not in n))
|
| 908 |
+
]
|
| 909 |
+
|
| 910 |
+
def get_llm_named_modules(self):
|
| 911 |
+
return {n: m for n, m in self.named_modules() if "vision_tower" not in n and "mm_projector" not in n}
|
| 912 |
+
|
| 913 |
+
def set_llm_requires_grad(self, requires_grad: bool, exclude_lora: bool = True):
|
| 914 |
+
for n, p in self.named_parameters():
|
| 915 |
+
if exclude_lora and ("lora_A" in n or "lora_B" in n):
|
| 916 |
+
continue
|
| 917 |
+
if "vision_tower" in n or "mm_projector" in n:
|
| 918 |
+
continue
|
| 919 |
+
p.requires_grad = requires_grad
|
| 920 |
+
|
| 921 |
+
def set_vision_tower_requires_grad(self, requires_grad: bool):
|
| 922 |
+
self.model.set_vision_tower_requires_grad(requires_grad)
|
| 923 |
+
|
| 924 |
+
def set_vision_adapter_requires_grad(self, requires_grad: bool):
|
| 925 |
+
self.model.set_vision_adapter_requires_grad(requires_grad)
|
| 926 |
+
|
| 927 |
+
def set_llm_dtype(self, dtype: torch.dtype):
|
| 928 |
+
for p in self.get_llm_parameters():
|
| 929 |
+
p.data = p.data.to(dtype)
|
| 930 |
+
|
| 931 |
+
def set_vision_tower_dtype(self, dtype: torch.dtype):
|
| 932 |
+
self.model.set_vision_tower_dtype(dtype)
|
| 933 |
+
|
| 934 |
+
def set_vision_adapter_dtype(self, dtype: torch.dtype):
|
| 935 |
+
self.model.set_vision_adapter_dtype(dtype)
|
| 936 |
+
|
| 937 |
+
def is_llm_frozen(self):
|
| 938 |
+
return all(not p.requires_grad for p in self.get_llm_parameters())
|
| 939 |
+
|
| 940 |
+
def is_vision_tower_frozen(self):
|
| 941 |
+
return self.model.is_vision_tower_frozen()
|
| 942 |
+
|
| 943 |
+
def is_vision_adapter_frozen(self):
|
| 944 |
+
return self.model.is_vision_adapter_frozen()
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def initialize_vision_modules(self):
|
| 949 |
+
self.model.initialize_vision_modules()
|
| 950 |
+
|
| 951 |
+
def get_multimodal_input_embeddings(self, input_ids, image_features, return_labels=True) -> torch.Tensor:
|
| 952 |
+
emb_start_image_id = self.model.embed_tokens(torch.tensor([self.image_start_id], device=self.device))
|
| 953 |
+
emb_end_image_id = self.model.embed_tokens(torch.tensor([self.image_end_id], device=self.device))
|
| 954 |
+
id_ignore = torch.tensor([IGNORE_INDEX], device=self.device)
|
| 955 |
+
|
| 956 |
+
# repetition‑penalty safety ????
|
| 957 |
+
# input_ids[input_ids == self.image_token_id] = 0
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
# Iterate over each batch item
|
| 961 |
+
embeds_list, labels_list = [], []
|
| 962 |
+
for batch_id, item_ids in enumerate(input_ids):
|
| 963 |
+
|
| 964 |
+
image_token_positions = (item_ids == self.image_token_id).nonzero(as_tuple=True)[0]
|
| 965 |
+
if len(image_token_positions) != image_features[batch_id].shape[0]:
|
| 966 |
+
raise ValueError(
|
| 967 |
+
f"Mismatch between number of image tokens ({len(image_token_positions)}) and number of image features ({image_features[batch_id].shape[0]})"
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
cursor = 0
|
| 972 |
+
emb_parts, lbl_parts = [], []
|
| 973 |
+
for indx_image, image_token_pos in enumerate(image_token_positions):
|
| 974 |
+
if image_token_pos > cursor:
|
| 975 |
+
span = item_ids[cursor:image_token_pos]
|
| 976 |
+
emb_parts.append(self.model.embed_tokens(span))
|
| 977 |
+
lbl_parts.append(span)
|
| 978 |
+
|
| 979 |
+
# <image_start>
|
| 980 |
+
emb_parts.append(emb_start_image_id)
|
| 981 |
+
lbl_parts.append(id_ignore)
|
| 982 |
+
|
| 983 |
+
# vision embeddings
|
| 984 |
+
image_tokens = image_features[batch_id][indx_image]
|
| 985 |
+
if image_tokens.shape[0] == 1 and image_tokens.ndim == 3:
|
| 986 |
+
image_tokens = image_tokens.squeeze(0)
|
| 987 |
+
emb_parts.append(image_tokens)
|
| 988 |
+
lbl_parts.append(id_ignore.repeat(image_tokens.shape[0]))
|
| 989 |
+
|
| 990 |
+
# <image_end>
|
| 991 |
+
emb_parts.append(emb_end_image_id)
|
| 992 |
+
lbl_parts.append(id_ignore)
|
| 993 |
+
|
| 994 |
+
cursor = image_token_pos + 1
|
| 995 |
+
|
| 996 |
+
# tail text
|
| 997 |
+
if cursor < item_ids.shape[0]:
|
| 998 |
+
tail = item_ids[cursor:]
|
| 999 |
+
emb_parts.append(self.model.embed_tokens(tail))
|
| 1000 |
+
lbl_parts.append(tail)
|
| 1001 |
+
|
| 1002 |
+
embeds_list.append(torch.cat(emb_parts, dim=0))
|
| 1003 |
+
labels_list.append(torch.cat(lbl_parts, dim=0))
|
| 1004 |
+
|
| 1005 |
+
return (embeds_list, labels_list) if return_labels else embeds_list
|
| 1006 |
+
|
| 1007 |
+
def prepare_inputs_for_multimodal(
|
| 1008 |
+
self,
|
| 1009 |
+
input_ids: torch.LongTensor,
|
| 1010 |
+
images: List[List[PIL.Image.Image]], # B x N
|
| 1011 |
+
position_ids: Optional[torch.LongTensor],
|
| 1012 |
+
attention_mask: Optional[torch.Tensor],
|
| 1013 |
+
past_key_values: Optional[List[torch.FloatTensor]],
|
| 1014 |
+
labels: Optional[torch.LongTensor],
|
| 1015 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.LongTensor], Optional[torch.Tensor], Optional[List[torch.FloatTensor]], torch.Tensor, Optional[torch.Tensor]]:
|
| 1016 |
+
|
| 1017 |
+
# ─────────────────── early return (no image / streaming step) ───────────────────
|
| 1018 |
+
# if we have already processed images and are in a streaming step we can skip the multimodal processing
|
| 1019 |
+
# but we need to ensure the attention mask and position ids are correct
|
| 1020 |
+
|
| 1021 |
+
if past_key_values is not None and attention_mask is not None and input_ids.shape[1] == 1:
|
| 1022 |
+
tgt = past_key_values[-1][-1].shape[-2] + 1
|
| 1023 |
+
attention_mask = torch.cat(
|
| 1024 |
+
[attention_mask,
|
| 1025 |
+
torch.ones((attention_mask.size(0),
|
| 1026 |
+
tgt - attention_mask.size(1)),
|
| 1027 |
+
dtype=attention_mask.dtype,
|
| 1028 |
+
device=attention_mask.device)],
|
| 1029 |
+
dim=1,
|
| 1030 |
+
)
|
| 1031 |
+
position_ids = (attention_mask.sum(dim=1, keepdim=True) - 1).long()
|
| 1032 |
+
|
| 1033 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
| 1034 |
+
|
| 1035 |
+
# ─────────────────────────── images: (B, N) ───────────────────────────
|
| 1036 |
+
if isinstance(images, list) and isinstance(images[0], list):
|
| 1037 |
+
# images is a list of lists, each containing multiple images, B x N
|
| 1038 |
+
# e.g. [[img1, img2], [img3, img4]]
|
| 1039 |
+
assert len(images) == input_ids.shape[0], f"Batch size mismatch: {len(images)} vs {input_ids.shape[0]}"
|
| 1040 |
+
image_features = []
|
| 1041 |
+
for sublst_images in images:
|
| 1042 |
+
if len(sublst_images) == 0:
|
| 1043 |
+
image_features.append(torch.zeros((0, self.get_model().mm_projector.output_dim), device=self.device))
|
| 1044 |
+
else:
|
| 1045 |
+
if isinstance(sublst_images[0], PIL.Image.Image):
|
| 1046 |
+
image_features.append(
|
| 1047 |
+
self.model.compute_image_features(
|
| 1048 |
+
self.model.vision_tower.preprocess_images(sublst_images, pad_and_stack_tensors=True)
|
| 1049 |
+
)
|
| 1050 |
+
)
|
| 1051 |
+
elif isinstance(sublst_images[0], torch.Tensor):
|
| 1052 |
+
# This should be a list of tensors of pre-processed images, [(N X 3 X W x H), ...]
|
| 1053 |
+
image_features.append(
|
| 1054 |
+
self.model.compute_image_features(sublst_images)
|
| 1055 |
+
)
|
| 1056 |
+
elif isinstance(images, list) and isinstance(images[0], PIL.Image.Image):
|
| 1057 |
+
# images is a list of images for a single batch item, 1 x N
|
| 1058 |
+
# e.g. [img1, img2, img3]
|
| 1059 |
+
assert input_ids.shape[0] == 1, f"Batch size mismatch: {len(images)} vs {input_ids.shape[0]}"
|
| 1060 |
+
image_features = [
|
| 1061 |
+
self.model.compute_image_features(
|
| 1062 |
+
self.model.vision_tower.preprocess_images(images, pad_and_stack_tensors=True)
|
| 1063 |
+
)
|
| 1064 |
+
]
|
| 1065 |
+
elif isinstance(images, list) and isinstance(images[0], torch.Tensor):
|
| 1066 |
+
# This should be a list of tensors of pre-processed images, [(N X 3 X W x H), ...]
|
| 1067 |
+
# The list length should match the batch size
|
| 1068 |
+
assert input_ids.shape[0] == len(images), f"Batch size mismatch: {len(images)} vs {input_ids.shape[0]}"
|
| 1069 |
+
image_features = [
|
| 1070 |
+
self.model.compute_image_features(imgs) for imgs in images
|
| 1071 |
+
]
|
| 1072 |
+
elif isinstance(images, PIL.Image.Image):
|
| 1073 |
+
# images is a single image, 1 x 1
|
| 1074 |
+
# e.g. img1
|
| 1075 |
+
assert input_ids.shape[0] == 1, f"Batch size mismatch: {len(images)} vs {input_ids.shape[0]}"
|
| 1076 |
+
image_features = [
|
| 1077 |
+
self.model.compute_image_features(
|
| 1078 |
+
self.model.vision_tower.preprocess_images([images])
|
| 1079 |
+
)
|
| 1080 |
+
]
|
| 1081 |
+
else:
|
| 1082 |
+
raise ValueError(f"Unsupported images format: {type(images)}. Expected list of PIL images, a single PIL image or a Tensor of pre-processed images")
|
| 1083 |
+
|
| 1084 |
+
# ─────────────────────────── image_features: (B x N x D) ───────────────────────────
|
| 1085 |
+
if isinstance(image_features, list):
|
| 1086 |
+
assert input_ids.shape[0] == len(image_features), f"Incorrectly formatted image_features: list length should match batch size"
|
| 1087 |
+
assert isinstance(image_features[0], torch.Tensor), f"Incorrectly formatted image_features: list items should be tensors"
|
| 1088 |
+
elif isinstance(image_features, torch.Tensor):
|
| 1089 |
+
assert input_ids.shape[0] == image_features.shape[0], f"Incorrectly formatted image_features: tensor should match batch size"
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
# ───────────────────────────── pad handling prelims ──────────────────────────────
|
| 1093 |
+
if attention_mask is None:
|
| 1094 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
| 1095 |
+
else:
|
| 1096 |
+
attention_mask = attention_mask.bool()
|
| 1097 |
+
if position_ids is None:
|
| 1098 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
| 1099 |
+
|
| 1100 |
+
input_ids_nopad = [ids[mask] for ids, mask in zip(input_ids, attention_mask)]
|
| 1101 |
+
embeds_list, labels_list = self.get_multimodal_input_embeddings(
|
| 1102 |
+
input_ids_nopad,
|
| 1103 |
+
image_features,
|
| 1104 |
+
return_labels=True
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
# ───────────────────── truncate then pad back to rectangle ──────────────────────
|
| 1108 |
+
new_input_embeds = torch.nn.utils.rnn.pad_sequence(
|
| 1109 |
+
embeds_list,
|
| 1110 |
+
batch_first=True,
|
| 1111 |
+
padding_value=0.0
|
| 1112 |
+
).to(dtype=self.dtype)
|
| 1113 |
+
|
| 1114 |
+
new_labels = torch.nn.utils.rnn.pad_sequence(
|
| 1115 |
+
labels_list,
|
| 1116 |
+
batch_first=True,
|
| 1117 |
+
padding_value=IGNORE_INDEX
|
| 1118 |
+
).long()
|
| 1119 |
+
|
| 1120 |
+
if self.config.tokenizer_model_max_length is not None:
|
| 1121 |
+
new_input_embeds = new_input_embeds[:, :self.config.tokenizer_model_max_length]
|
| 1122 |
+
new_labels = new_labels[:, :self.config.tokenizer_model_max_length]
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
# ────────────────────────────── attention mask and position ids ────────────────
|
| 1128 |
+
|
| 1129 |
+
attention_mask = (
|
| 1130 |
+
torch.arange(new_input_embeds.size(1), device=input_ids.device)
|
| 1131 |
+
.unsqueeze(0)
|
| 1132 |
+
< torch.tensor([e.size(0) for e in embeds_list],
|
| 1133 |
+
device=input_ids.device).unsqueeze(1)
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
raw_pos = attention_mask.cumsum(dim=1) - 1
|
| 1137 |
+
position_ids = raw_pos.masked_fill(~attention_mask, 0).long()
|
| 1138 |
+
|
| 1139 |
+
if not self.training:
|
| 1140 |
+
new_labels = None
|
| 1141 |
+
|
| 1142 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
# ------------------------------------------------------------------
|
| 1147 |
+
def forward(
|
| 1148 |
+
self,
|
| 1149 |
+
input_ids: torch.LongTensor = None,
|
| 1150 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1151 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1152 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1153 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1154 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1155 |
+
use_cache: Optional[bool] = None,
|
| 1156 |
+
output_attentions: Optional[bool] = None,
|
| 1157 |
+
output_hidden_states: Optional[bool] = None,
|
| 1158 |
+
return_dict: Optional[bool] = None,
|
| 1159 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1160 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 1161 |
+
images: Optional[PIL.Image.Image] = None,
|
| 1162 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 1163 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1164 |
+
|
| 1165 |
+
is_multi_modal = images is not None and not (
|
| 1166 |
+
(
|
| 1167 |
+
isinstance(images, list) and (len(images) == 0 or all(i == [] for i in images))
|
| 1168 |
+
)
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
if inputs_embeds is None and is_multi_modal:
|
| 1173 |
+
(
|
| 1174 |
+
input_ids,
|
| 1175 |
+
position_ids,
|
| 1176 |
+
attention_mask,
|
| 1177 |
+
past_key_values,
|
| 1178 |
+
inputs_embeds,
|
| 1179 |
+
labels
|
| 1180 |
+
) = self.prepare_inputs_for_multimodal(
|
| 1181 |
+
input_ids=input_ids,
|
| 1182 |
+
images=images,
|
| 1183 |
+
position_ids=position_ids,
|
| 1184 |
+
attention_mask=attention_mask,
|
| 1185 |
+
past_key_values=past_key_values,
|
| 1186 |
+
labels=labels,
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
if cache_position is not None and inputs_embeds is not None and cache_position.shape[0] != inputs_embeds.shape[1]:
|
| 1190 |
+
cache_position = torch.arange(inputs_embeds.shape[1], device=self.device)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
return Phi3ForCausalLM.forward(
|
| 1194 |
+
self,
|
| 1195 |
+
input_ids=input_ids,
|
| 1196 |
+
attention_mask=attention_mask,
|
| 1197 |
+
position_ids=position_ids,
|
| 1198 |
+
past_key_values=past_key_values,
|
| 1199 |
+
inputs_embeds=inputs_embeds,
|
| 1200 |
+
labels=labels,
|
| 1201 |
+
use_cache=use_cache,
|
| 1202 |
+
output_attentions=output_attentions,
|
| 1203 |
+
output_hidden_states=output_hidden_states,
|
| 1204 |
+
return_dict=return_dict,
|
| 1205 |
+
cache_position=cache_position,
|
| 1206 |
+
logits_to_keep=logits_to_keep,
|
| 1207 |
+
**kwargs
|
| 1208 |
+
)
|
| 1209 |
+
|
| 1210 |
+
def print_device_configuration(self):
|
| 1211 |
+
print("*************Device Configuration*********")
|
| 1212 |
+
if len(self.get_llm_parameters()) > 0:
|
| 1213 |
+
llm_device = set({str(p.device) for p in self.get_llm_parameters()})
|
| 1214 |
+
llm_dtype = set({p.dtype for p in self.get_llm_parameters()})
|
| 1215 |
+
print(f"LLM Parameters:\t\t\tdevice: {llm_device}\tdtype: {llm_dtype}\tfrozen: {self.is_llm_frozen()}")
|
| 1216 |
+
else:
|
| 1217 |
+
print("LLM parameters have not been initialized")
|
| 1218 |
+
|
| 1219 |
+
if self.get_model().vision_tower is not None:
|
| 1220 |
+
vt_device = set({str(p.device) for p in self.get_model().vision_tower.parameters()})
|
| 1221 |
+
vt_dtype = set({p.dtype for p in self.get_model().vision_tower.parameters()})
|
| 1222 |
+
print(f"Vision Tower Parameters:\tdevice: {vt_device}\tdtype: {vt_dtype}\tfrozen: {self.is_vision_tower_frozen()}")
|
| 1223 |
+
else:
|
| 1224 |
+
print("Vision tower parameters have not been initialized")
|
| 1225 |
+
|
| 1226 |
+
if self.get_model().mm_projector is not None:
|
| 1227 |
+
mm_device = set({str(p.device) for p in self.get_model().mm_projector.parameters()})
|
| 1228 |
+
mm_dtype = set({p.dtype for p in self.get_model().mm_projector.parameters()})
|
| 1229 |
+
print(f"MM Projector Parameters:\tdevice: {mm_device}\tdtype: {mm_dtype}\tfrozen: {self.is_vision_adapter_frozen()}")
|
| 1230 |
+
else:
|
| 1231 |
+
print("MM Projector parameters have not been initialized")
|
| 1232 |
+
print("******************************************")
|
| 1233 |
+
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
def build_tokenizer(base_model_id: str) -> Tuple[AutoTokenizer, dict]:
|
| 1237 |
+
tok = AutoTokenizer.from_pretrained(base_model_id, padding_side="right")
|
| 1238 |
+
specials = {t: tok.convert_tokens_to_ids(t) for t in [IMAGE_TOKEN, IMG_START_TOKEN, IMG_END_TOKEN] if t in tok.vocab}
|
| 1239 |
+
if len(specials) < 3:
|
| 1240 |
+
n = tok.add_tokens([IMAGE_TOKEN, IMG_START_TOKEN, IMG_END_TOKEN], special_tokens=True)
|
| 1241 |
+
tok.pad_token = tok.eos_token
|
| 1242 |
+
specials = {
|
| 1243 |
+
"image": tok.convert_tokens_to_ids(IMAGE_TOKEN),
|
| 1244 |
+
"start": tok.convert_tokens_to_ids(IMG_START_TOKEN),
|
| 1245 |
+
"end": tok.convert_tokens_to_ids(IMG_END_TOKEN),
|
| 1246 |
+
}
|
| 1247 |
+
return tok, specials
|
| 1248 |
+
|
modeling_phi3.py
ADDED
|
@@ -0,0 +1,1181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""PyTorch Phi-3 model."""
|
| 17 |
+
|
| 18 |
+
from typing import Callable, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from transformers.activations import ACT2FN
|
| 24 |
+
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
| 25 |
+
from transformers.generation import GenerationMixin
|
| 26 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 27 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 28 |
+
from transformers.modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithPast,
|
| 30 |
+
CausalLMOutputWithPast,
|
| 31 |
+
SequenceClassifierOutputWithPast,
|
| 32 |
+
TokenClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 35 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 36 |
+
from transformers.processing_utils import Unpack
|
| 37 |
+
from transformers.utils import (
|
| 38 |
+
LossKwargs,
|
| 39 |
+
add_code_sample_docstrings,
|
| 40 |
+
add_start_docstrings,
|
| 41 |
+
add_start_docstrings_to_model_forward,
|
| 42 |
+
logging,
|
| 43 |
+
replace_return_docstrings,
|
| 44 |
+
)
|
| 45 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 46 |
+
from .configuration_phi3 import Phi3Config
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
|
| 52 |
+
_CONFIG_FOR_DOC = "Phi3Config"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Phi3MLP(nn.Module):
|
| 56 |
+
def __init__(self, config):
|
| 57 |
+
super().__init__()
|
| 58 |
+
|
| 59 |
+
self.config = config
|
| 60 |
+
self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
|
| 61 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 62 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 63 |
+
|
| 64 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 65 |
+
up_states = self.gate_up_proj(hidden_states)
|
| 66 |
+
|
| 67 |
+
gate, up_states = up_states.chunk(2, dim=-1)
|
| 68 |
+
up_states = up_states * self.activation_fn(gate)
|
| 69 |
+
|
| 70 |
+
return self.down_proj(up_states)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def rotate_half(x):
|
| 74 |
+
"""Rotates half the hidden dims of the input."""
|
| 75 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 76 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 77 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 81 |
+
"""
|
| 82 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 83 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 84 |
+
"""
|
| 85 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 86 |
+
if n_rep == 1:
|
| 87 |
+
return hidden_states
|
| 88 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 89 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def eager_attention_forward(
|
| 93 |
+
module: nn.Module,
|
| 94 |
+
query: torch.Tensor,
|
| 95 |
+
key: torch.Tensor,
|
| 96 |
+
value: torch.Tensor,
|
| 97 |
+
attention_mask: Optional[torch.Tensor],
|
| 98 |
+
scaling: float,
|
| 99 |
+
dropout: float = 0.0,
|
| 100 |
+
**kwargs,
|
| 101 |
+
):
|
| 102 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 103 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 104 |
+
|
| 105 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 106 |
+
if attention_mask is not None:
|
| 107 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 108 |
+
attn_weights = attn_weights + causal_mask
|
| 109 |
+
|
| 110 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 111 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 112 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 113 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 114 |
+
|
| 115 |
+
return attn_output, attn_weights
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 119 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
q (`torch.Tensor`): The query tensor.
|
| 123 |
+
k (`torch.Tensor`): The key tensor.
|
| 124 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 125 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 126 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 127 |
+
Deprecated and unused.
|
| 128 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 129 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 130 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 131 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 132 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 133 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 134 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 135 |
+
Returns:
|
| 136 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 137 |
+
"""
|
| 138 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 139 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 140 |
+
|
| 141 |
+
rotary_dim = cos.shape[-1]
|
| 142 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 143 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 144 |
+
|
| 145 |
+
q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
|
| 146 |
+
k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
|
| 147 |
+
return q_embed, k_embed
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Phi3Attention(nn.Module):
|
| 151 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 152 |
+
|
| 153 |
+
def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.config = config
|
| 156 |
+
self.layer_idx = layer_idx
|
| 157 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 158 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 159 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 160 |
+
self.scaling = self.head_dim**-0.5
|
| 161 |
+
self.attention_dropout = config.attention_dropout
|
| 162 |
+
self.is_causal = True
|
| 163 |
+
|
| 164 |
+
op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)
|
| 165 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 166 |
+
self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)
|
| 167 |
+
|
| 168 |
+
def forward(
|
| 169 |
+
self,
|
| 170 |
+
hidden_states: torch.Tensor,
|
| 171 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 172 |
+
attention_mask: Optional[torch.Tensor],
|
| 173 |
+
past_key_value: Optional[Cache] = None,
|
| 174 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 175 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 176 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 177 |
+
input_shape = hidden_states.shape[:-1]
|
| 178 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 179 |
+
|
| 180 |
+
qkv = self.qkv_proj(hidden_states)
|
| 181 |
+
query_pos = self.config.num_attention_heads * self.head_dim
|
| 182 |
+
query_states = qkv[..., :query_pos]
|
| 183 |
+
key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
|
| 184 |
+
value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
|
| 185 |
+
|
| 186 |
+
query_states = query_states.view(hidden_shape).transpose(1, 2)
|
| 187 |
+
key_states = key_states.view(hidden_shape).transpose(1, 2)
|
| 188 |
+
value_states = value_states.view(hidden_shape).transpose(1, 2)
|
| 189 |
+
|
| 190 |
+
cos, sin = position_embeddings
|
| 191 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 192 |
+
|
| 193 |
+
if past_key_value is not None:
|
| 194 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 195 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 196 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 197 |
+
|
| 198 |
+
attention_interface: Callable = eager_attention_forward
|
| 199 |
+
if self.config._attn_implementation != "eager":
|
| 200 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 201 |
+
logger.warning_once(
|
| 202 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 203 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 207 |
+
|
| 208 |
+
attn_output, attn_weights = attention_interface(
|
| 209 |
+
self,
|
| 210 |
+
query_states,
|
| 211 |
+
key_states,
|
| 212 |
+
value_states,
|
| 213 |
+
attention_mask,
|
| 214 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 215 |
+
scaling=self.scaling,
|
| 216 |
+
sliding_window=getattr(self.config, "sliding_window", None),
|
| 217 |
+
**kwargs,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 221 |
+
attn_output = self.o_proj(attn_output)
|
| 222 |
+
return attn_output, attn_weights
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Phi3RMSNorm(nn.Module):
|
| 226 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 227 |
+
"""
|
| 228 |
+
Phi3RMSNorm is equivalent to T5LayerNorm
|
| 229 |
+
"""
|
| 230 |
+
super().__init__()
|
| 231 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 232 |
+
self.variance_epsilon = eps
|
| 233 |
+
|
| 234 |
+
def forward(self, hidden_states):
|
| 235 |
+
input_dtype = hidden_states.dtype
|
| 236 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 237 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 238 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 239 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 240 |
+
|
| 241 |
+
def extra_repr(self):
|
| 242 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class Phi3DecoderLayer(nn.Module):
|
| 246 |
+
def __init__(self, config: Phi3Config, layer_idx: int):
|
| 247 |
+
super().__init__()
|
| 248 |
+
self.hidden_size = config.hidden_size
|
| 249 |
+
self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)
|
| 250 |
+
self.mlp = Phi3MLP(config)
|
| 251 |
+
self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 252 |
+
self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 253 |
+
self.config = config
|
| 254 |
+
self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
|
| 255 |
+
self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
|
| 256 |
+
|
| 257 |
+
def forward(
|
| 258 |
+
self,
|
| 259 |
+
hidden_states: torch.Tensor,
|
| 260 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 261 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 262 |
+
past_key_value: Optional[Cache] = None,
|
| 263 |
+
output_attentions: Optional[bool] = False,
|
| 264 |
+
use_cache: Optional[bool] = False,
|
| 265 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 266 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 267 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 268 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 269 |
+
"""
|
| 270 |
+
Args:
|
| 271 |
+
hidden_states (`torch.FloatTensor`):
|
| 272 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 273 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 274 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 275 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 276 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
| 277 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
| 278 |
+
past_key_value (`Cache`, *optional*): cached past key and value projection states
|
| 279 |
+
output_attentions (`bool`, *optional*):
|
| 280 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 281 |
+
returned tensors for more detail.
|
| 282 |
+
use_cache (`bool`, *optional*):
|
| 283 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 284 |
+
(see `past_key_values`).
|
| 285 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 286 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
| 287 |
+
kwargs (`dict`, *optional*):
|
| 288 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 289 |
+
into the model
|
| 290 |
+
"""
|
| 291 |
+
residual = hidden_states
|
| 292 |
+
|
| 293 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 294 |
+
|
| 295 |
+
# Self Attention
|
| 296 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 297 |
+
hidden_states=hidden_states,
|
| 298 |
+
attention_mask=attention_mask,
|
| 299 |
+
position_ids=position_ids,
|
| 300 |
+
past_key_value=past_key_value,
|
| 301 |
+
output_attentions=output_attentions,
|
| 302 |
+
use_cache=use_cache,
|
| 303 |
+
cache_position=cache_position,
|
| 304 |
+
position_embeddings=position_embeddings,
|
| 305 |
+
**kwargs,
|
| 306 |
+
)
|
| 307 |
+
hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama
|
| 308 |
+
|
| 309 |
+
residual = hidden_states
|
| 310 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 311 |
+
hidden_states = self.mlp(hidden_states)
|
| 312 |
+
hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama
|
| 313 |
+
|
| 314 |
+
outputs = (hidden_states,)
|
| 315 |
+
if output_attentions:
|
| 316 |
+
outputs += (self_attn_weights,)
|
| 317 |
+
|
| 318 |
+
return outputs
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class Phi3RotaryEmbedding(nn.Module):
|
| 322 |
+
def __init__(self, config: Phi3Config, device=None):
|
| 323 |
+
super().__init__()
|
| 324 |
+
# BC: "rope_type" was originally "type"
|
| 325 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 326 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 327 |
+
else:
|
| 328 |
+
self.rope_type = "default"
|
| 329 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 330 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 331 |
+
|
| 332 |
+
self.config = config
|
| 333 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 334 |
+
|
| 335 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 336 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 337 |
+
self.original_inv_freq = self.inv_freq
|
| 338 |
+
|
| 339 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 340 |
+
"""
|
| 341 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 342 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 343 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 344 |
+
"""
|
| 345 |
+
seq_len = torch.max(position_ids) + 1
|
| 346 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 347 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
| 348 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 349 |
+
self.max_seq_len_cached = seq_len
|
| 350 |
+
|
| 351 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 352 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
| 353 |
+
# the buffer is automatically moved, but not the original copy)
|
| 354 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
| 355 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 356 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 357 |
+
|
| 358 |
+
@torch.no_grad()
|
| 359 |
+
def forward(self, x, position_ids):
|
| 360 |
+
if "dynamic" in self.rope_type:
|
| 361 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 362 |
+
elif self.rope_type == "longrope":
|
| 363 |
+
self._longrope_frequency_update(position_ids, device=x.device)
|
| 364 |
+
|
| 365 |
+
# Core RoPE block
|
| 366 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 367 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 368 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 369 |
+
device_type = x.device.type
|
| 370 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 371 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 372 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 373 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 374 |
+
cos = emb.cos()
|
| 375 |
+
sin = emb.sin()
|
| 376 |
+
|
| 377 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 378 |
+
cos = cos * self.attention_scaling
|
| 379 |
+
sin = sin * self.attention_scaling
|
| 380 |
+
|
| 381 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 382 |
+
|
| 383 |
+
def _longrope_frequency_update(self, position_ids, device):
|
| 384 |
+
"""Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
|
| 385 |
+
seq_len = torch.max(position_ids) + 1
|
| 386 |
+
if hasattr(self.config, "original_max_position_embeddings"):
|
| 387 |
+
original_max_position_embeddings = self.config.original_max_position_embeddings
|
| 388 |
+
else:
|
| 389 |
+
original_max_position_embeddings = self.config.max_position_embeddings
|
| 390 |
+
if seq_len > original_max_position_embeddings:
|
| 391 |
+
if not hasattr(self, "long_inv_freq"):
|
| 392 |
+
self.long_inv_freq, _ = self.rope_init_fn(
|
| 393 |
+
self.config, device, seq_len=original_max_position_embeddings + 1
|
| 394 |
+
)
|
| 395 |
+
self.register_buffer("inv_freq", self.long_inv_freq, persistent=False)
|
| 396 |
+
else:
|
| 397 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
| 398 |
+
# the buffer is automatically moved, but not the original copy)
|
| 399 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
| 400 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
PHI3_START_DOCSTRING = r"""
|
| 404 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 405 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 406 |
+
etc.)
|
| 407 |
+
|
| 408 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 409 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 410 |
+
and behavior.
|
| 411 |
+
|
| 412 |
+
Parameters:
|
| 413 |
+
config ([`Phi3Config`]):
|
| 414 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 415 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 416 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@add_start_docstrings(
|
| 421 |
+
"The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
|
| 422 |
+
PHI3_START_DOCSTRING,
|
| 423 |
+
)
|
| 424 |
+
class Phi3PreTrainedModel(PreTrainedModel):
|
| 425 |
+
config_class = Phi3Config
|
| 426 |
+
base_model_prefix = "model"
|
| 427 |
+
supports_gradient_checkpointing = True
|
| 428 |
+
_no_split_modules = ["Phi3DecoderLayer"]
|
| 429 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 430 |
+
_supports_flash_attn_2 = True
|
| 431 |
+
_supports_sdpa = True
|
| 432 |
+
_supports_flex_attn = True
|
| 433 |
+
_supports_cache_class = True
|
| 434 |
+
_supports_quantized_cache = True
|
| 435 |
+
_supports_static_cache = True
|
| 436 |
+
_supports_attention_backend = True
|
| 437 |
+
_version = "0.0.5"
|
| 438 |
+
|
| 439 |
+
def _init_weights(self, module):
|
| 440 |
+
std = self.config.initializer_range
|
| 441 |
+
if isinstance(module, nn.Linear):
|
| 442 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 443 |
+
if module.bias is not None:
|
| 444 |
+
module.bias.data.zero_()
|
| 445 |
+
elif isinstance(module, nn.Embedding):
|
| 446 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 447 |
+
if module.padding_idx is not None:
|
| 448 |
+
module.weight.data[module.padding_idx].zero_()
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
PHI3_INPUTS_DOCSTRING = r"""
|
| 452 |
+
Args:
|
| 453 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 454 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 455 |
+
it.
|
| 456 |
+
|
| 457 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 458 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 459 |
+
|
| 460 |
+
[What are input IDs?](../glossary#input-ids)
|
| 461 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 462 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 463 |
+
|
| 464 |
+
- 1 for tokens that are **not masked**,
|
| 465 |
+
- 0 for tokens that are **masked**.
|
| 466 |
+
|
| 467 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 468 |
+
|
| 469 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 470 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 471 |
+
|
| 472 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 473 |
+
`past_key_values`).
|
| 474 |
+
|
| 475 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 476 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 477 |
+
information on the default strategy.
|
| 478 |
+
|
| 479 |
+
- 1 indicates the head is **not masked**,
|
| 480 |
+
- 0 indicates the head is **masked**.
|
| 481 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 482 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 483 |
+
config.n_positions - 1]`.
|
| 484 |
+
|
| 485 |
+
[What are position IDs?](../glossary#position-ids)
|
| 486 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 487 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 488 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 489 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 490 |
+
|
| 491 |
+
Two formats are allowed:
|
| 492 |
+
- a [`~cache_utils.Cache`] instance, see our
|
| 493 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
| 494 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 495 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 496 |
+
cache format.
|
| 497 |
+
|
| 498 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 499 |
+
legacy cache format will be returned.
|
| 500 |
+
|
| 501 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 502 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 503 |
+
of shape `(batch_size, sequence_length)`.
|
| 504 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 505 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 506 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 507 |
+
model's internal embedding lookup matrix.
|
| 508 |
+
use_cache (`bool`, *optional*):
|
| 509 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 510 |
+
`past_key_values`).
|
| 511 |
+
output_attentions (`bool`, *optional*):
|
| 512 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 513 |
+
tensors for more detail.
|
| 514 |
+
output_hidden_states (`bool`, *optional*):
|
| 515 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 516 |
+
more detail.
|
| 517 |
+
return_dict (`bool`, *optional*):
|
| 518 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 519 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 520 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 521 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 522 |
+
the complete sequence length.
|
| 523 |
+
"""
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
@add_start_docstrings(
|
| 527 |
+
"The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
|
| 528 |
+
PHI3_START_DOCSTRING,
|
| 529 |
+
)
|
| 530 |
+
class Phi3Model(Phi3PreTrainedModel):
|
| 531 |
+
"""
|
| 532 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
|
| 533 |
+
|
| 534 |
+
Args:
|
| 535 |
+
config: Phi3Config
|
| 536 |
+
"""
|
| 537 |
+
|
| 538 |
+
def __init__(self, config: Phi3Config):
|
| 539 |
+
super().__init__(config)
|
| 540 |
+
self.padding_idx = config.pad_token_id
|
| 541 |
+
self.vocab_size = config.vocab_size
|
| 542 |
+
|
| 543 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 544 |
+
self.layers = nn.ModuleList(
|
| 545 |
+
[Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 546 |
+
)
|
| 547 |
+
self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 548 |
+
self.rotary_emb = Phi3RotaryEmbedding(config=config)
|
| 549 |
+
self.gradient_checkpointing = False
|
| 550 |
+
|
| 551 |
+
# Initialize weights and apply final processing
|
| 552 |
+
self.post_init()
|
| 553 |
+
|
| 554 |
+
def get_input_embeddings(self):
|
| 555 |
+
return self.embed_tokens
|
| 556 |
+
|
| 557 |
+
def set_input_embeddings(self, value):
|
| 558 |
+
self.embed_tokens = value
|
| 559 |
+
|
| 560 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 561 |
+
def forward(
|
| 562 |
+
self,
|
| 563 |
+
input_ids: torch.LongTensor = None,
|
| 564 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 565 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 566 |
+
past_key_values: Optional[Cache] = None,
|
| 567 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 568 |
+
use_cache: Optional[bool] = None,
|
| 569 |
+
output_attentions: Optional[bool] = None,
|
| 570 |
+
output_hidden_states: Optional[bool] = None,
|
| 571 |
+
return_dict: Optional[bool] = None,
|
| 572 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 573 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 574 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 575 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 576 |
+
output_hidden_states = (
|
| 577 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 578 |
+
)
|
| 579 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 580 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 581 |
+
|
| 582 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 583 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 584 |
+
|
| 585 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 586 |
+
logger.warning_once(
|
| 587 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 588 |
+
)
|
| 589 |
+
use_cache = False
|
| 590 |
+
|
| 591 |
+
if inputs_embeds is None:
|
| 592 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 593 |
+
|
| 594 |
+
if use_cache and past_key_values is None:
|
| 595 |
+
past_key_values = DynamicCache()
|
| 596 |
+
|
| 597 |
+
if cache_position is None:
|
| 598 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 599 |
+
cache_position = torch.arange(
|
| 600 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
if position_ids is None:
|
| 604 |
+
position_ids = cache_position.unsqueeze(0)
|
| 605 |
+
|
| 606 |
+
causal_mask = self._update_causal_mask(
|
| 607 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
hidden_states = inputs_embeds
|
| 611 |
+
|
| 612 |
+
# create position embeddings to be shared across the decoder layers
|
| 613 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 614 |
+
|
| 615 |
+
# decoder layers
|
| 616 |
+
all_hidden_states = () if output_hidden_states else None
|
| 617 |
+
all_self_attns = () if output_attentions else None
|
| 618 |
+
|
| 619 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 620 |
+
if output_hidden_states:
|
| 621 |
+
all_hidden_states += (hidden_states,)
|
| 622 |
+
|
| 623 |
+
if self.gradient_checkpointing and self.training:
|
| 624 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 625 |
+
decoder_layer.__call__,
|
| 626 |
+
hidden_states,
|
| 627 |
+
causal_mask,
|
| 628 |
+
position_ids,
|
| 629 |
+
past_key_values,
|
| 630 |
+
output_attentions,
|
| 631 |
+
use_cache,
|
| 632 |
+
cache_position,
|
| 633 |
+
position_embeddings,
|
| 634 |
+
)
|
| 635 |
+
else:
|
| 636 |
+
layer_outputs = decoder_layer(
|
| 637 |
+
hidden_states,
|
| 638 |
+
attention_mask=causal_mask,
|
| 639 |
+
position_ids=position_ids,
|
| 640 |
+
past_key_value=past_key_values,
|
| 641 |
+
output_attentions=output_attentions,
|
| 642 |
+
use_cache=use_cache,
|
| 643 |
+
cache_position=cache_position,
|
| 644 |
+
position_embeddings=position_embeddings,
|
| 645 |
+
**flash_attn_kwargs,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
hidden_states = layer_outputs[0]
|
| 649 |
+
|
| 650 |
+
if output_attentions:
|
| 651 |
+
all_self_attns += (layer_outputs[1],)
|
| 652 |
+
|
| 653 |
+
hidden_states = self.norm(hidden_states)
|
| 654 |
+
|
| 655 |
+
# add hidden states from the last decoder layer
|
| 656 |
+
if output_hidden_states:
|
| 657 |
+
all_hidden_states += (hidden_states,)
|
| 658 |
+
|
| 659 |
+
output = BaseModelOutputWithPast(
|
| 660 |
+
last_hidden_state=hidden_states,
|
| 661 |
+
past_key_values=past_key_values if use_cache else None,
|
| 662 |
+
hidden_states=all_hidden_states,
|
| 663 |
+
attentions=all_self_attns,
|
| 664 |
+
)
|
| 665 |
+
return output if return_dict else output.to_tuple()
|
| 666 |
+
|
| 667 |
+
def _update_causal_mask(
|
| 668 |
+
self,
|
| 669 |
+
attention_mask: torch.Tensor,
|
| 670 |
+
input_tensor: torch.Tensor,
|
| 671 |
+
cache_position: torch.Tensor,
|
| 672 |
+
past_key_values: Cache,
|
| 673 |
+
output_attentions: bool,
|
| 674 |
+
):
|
| 675 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 676 |
+
if attention_mask is not None and past_key_values is not None:
|
| 677 |
+
is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
|
| 678 |
+
if is_padding_right:
|
| 679 |
+
raise ValueError(
|
| 680 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
| 681 |
+
" this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
|
| 682 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
| 683 |
+
)
|
| 684 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
| 685 |
+
return attention_mask
|
| 686 |
+
return None
|
| 687 |
+
|
| 688 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 689 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 690 |
+
# to infer the attention mask.
|
| 691 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 692 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 693 |
+
using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
|
| 694 |
+
|
| 695 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 696 |
+
if (
|
| 697 |
+
self.config._attn_implementation == "sdpa"
|
| 698 |
+
and not (using_static_cache or using_sliding_window_cache)
|
| 699 |
+
and not output_attentions
|
| 700 |
+
):
|
| 701 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 702 |
+
attention_mask,
|
| 703 |
+
inputs_embeds=input_tensor,
|
| 704 |
+
past_key_values_length=past_seen_tokens,
|
| 705 |
+
sliding_window=self.config.sliding_window,
|
| 706 |
+
is_training=self.training,
|
| 707 |
+
):
|
| 708 |
+
return None
|
| 709 |
+
|
| 710 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 711 |
+
min_dtype = torch.finfo(dtype).min
|
| 712 |
+
sequence_length = input_tensor.shape[1]
|
| 713 |
+
# SlidingWindowCache or StaticCache
|
| 714 |
+
if using_sliding_window_cache or using_static_cache:
|
| 715 |
+
target_length = past_key_values.get_max_cache_shape()
|
| 716 |
+
# DynamicCache or no cache
|
| 717 |
+
else:
|
| 718 |
+
target_length = (
|
| 719 |
+
attention_mask.shape[-1]
|
| 720 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 721 |
+
else past_seen_tokens + sequence_length + 1
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
| 725 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
| 726 |
+
attention_mask,
|
| 727 |
+
sequence_length=sequence_length,
|
| 728 |
+
target_length=target_length,
|
| 729 |
+
dtype=dtype,
|
| 730 |
+
device=device,
|
| 731 |
+
cache_position=cache_position,
|
| 732 |
+
batch_size=input_tensor.shape[0],
|
| 733 |
+
config=self.config,
|
| 734 |
+
past_key_values=past_key_values,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
if (
|
| 738 |
+
self.config._attn_implementation == "sdpa"
|
| 739 |
+
and attention_mask is not None
|
| 740 |
+
and attention_mask.device.type in ["cuda", "xpu"]
|
| 741 |
+
and not output_attentions
|
| 742 |
+
):
|
| 743 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 744 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 745 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 746 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 747 |
+
|
| 748 |
+
return causal_mask
|
| 749 |
+
|
| 750 |
+
@staticmethod
|
| 751 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
| 752 |
+
attention_mask: torch.Tensor,
|
| 753 |
+
sequence_length: int,
|
| 754 |
+
target_length: int,
|
| 755 |
+
dtype: torch.dtype,
|
| 756 |
+
device: torch.device,
|
| 757 |
+
cache_position: torch.Tensor,
|
| 758 |
+
batch_size: int,
|
| 759 |
+
config: Phi3Config,
|
| 760 |
+
past_key_values: Cache,
|
| 761 |
+
):
|
| 762 |
+
"""
|
| 763 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
| 764 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
| 765 |
+
|
| 766 |
+
Args:
|
| 767 |
+
attention_mask (`torch.Tensor`):
|
| 768 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
|
| 769 |
+
sequence_length (`int`):
|
| 770 |
+
The sequence length being processed.
|
| 771 |
+
target_length (`int`):
|
| 772 |
+
The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
|
| 773 |
+
dtype (`torch.dtype`):
|
| 774 |
+
The dtype to use for the 4D attention mask.
|
| 775 |
+
device (`torch.device`):
|
| 776 |
+
The device to plcae the 4D attention mask on.
|
| 777 |
+
cache_position (`torch.Tensor`):
|
| 778 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 779 |
+
batch_size (`torch.Tensor`):
|
| 780 |
+
Batch size.
|
| 781 |
+
config (`Phi3Config`):
|
| 782 |
+
The model's configuration class
|
| 783 |
+
past_key_values (`Cache`):
|
| 784 |
+
The cache class that is being used currently to generate
|
| 785 |
+
"""
|
| 786 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 787 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
| 788 |
+
causal_mask = attention_mask
|
| 789 |
+
else:
|
| 790 |
+
min_dtype = torch.finfo(dtype).min
|
| 791 |
+
causal_mask = torch.full(
|
| 792 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
| 793 |
+
)
|
| 794 |
+
diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 795 |
+
if config.sliding_window is not None:
|
| 796 |
+
# if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
|
| 797 |
+
# the check is needed to verify is current checkpoint was trained with sliding window or not
|
| 798 |
+
if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
|
| 799 |
+
sliding_attend_mask = torch.arange(target_length, device=device) <= (
|
| 800 |
+
cache_position.reshape(-1, 1) - config.sliding_window
|
| 801 |
+
)
|
| 802 |
+
diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
|
| 803 |
+
|
| 804 |
+
causal_mask *= diagonal_attend_mask
|
| 805 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
| 806 |
+
if attention_mask is not None:
|
| 807 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 808 |
+
if attention_mask.shape[-1] > target_length:
|
| 809 |
+
attention_mask = attention_mask[:, :target_length]
|
| 810 |
+
mask_length = attention_mask.shape[-1]
|
| 811 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
|
| 812 |
+
causal_mask.device
|
| 813 |
+
)
|
| 814 |
+
padding_mask = padding_mask == 0
|
| 815 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
| 816 |
+
padding_mask, min_dtype
|
| 817 |
+
)
|
| 818 |
+
return causal_mask
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class Phi3ForCausalLM(Phi3PreTrainedModel, GenerationMixin):
|
| 825 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 826 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 827 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 828 |
+
|
| 829 |
+
def __init__(self, config):
|
| 830 |
+
super().__init__(config)
|
| 831 |
+
# self.model = Phi3Model(config)
|
| 832 |
+
# self.vocab_size = config.vocab_size
|
| 833 |
+
# self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 834 |
+
|
| 835 |
+
# # Initialize weights and apply final processing
|
| 836 |
+
# self.post_init()
|
| 837 |
+
|
| 838 |
+
def get_input_embeddings(self):
|
| 839 |
+
return self.model.embed_tokens
|
| 840 |
+
|
| 841 |
+
def set_input_embeddings(self, value):
|
| 842 |
+
self.model.embed_tokens = value
|
| 843 |
+
|
| 844 |
+
def get_output_embeddings(self):
|
| 845 |
+
return self.lm_head
|
| 846 |
+
|
| 847 |
+
def set_output_embeddings(self, new_embeddings):
|
| 848 |
+
self.lm_head = new_embeddings
|
| 849 |
+
|
| 850 |
+
def set_decoder(self, decoder):
|
| 851 |
+
self.model = decoder
|
| 852 |
+
|
| 853 |
+
def get_decoder(self):
|
| 854 |
+
return self.model
|
| 855 |
+
|
| 856 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 857 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 858 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 859 |
+
def forward(
|
| 860 |
+
self,
|
| 861 |
+
input_ids: torch.LongTensor = None,
|
| 862 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 863 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 864 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 865 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 866 |
+
labels: Optional[torch.LongTensor] = None,
|
| 867 |
+
use_cache: Optional[bool] = None,
|
| 868 |
+
output_attentions: Optional[bool] = None,
|
| 869 |
+
output_hidden_states: Optional[bool] = None,
|
| 870 |
+
return_dict: Optional[bool] = None,
|
| 871 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 872 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 873 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 874 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 875 |
+
r"""
|
| 876 |
+
Args:
|
| 877 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 878 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 879 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 880 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 881 |
+
|
| 882 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
| 883 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
| 884 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 885 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 886 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
| 887 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
| 888 |
+
|
| 889 |
+
Returns:
|
| 890 |
+
|
| 891 |
+
Example:
|
| 892 |
+
|
| 893 |
+
```python
|
| 894 |
+
>>> from transformers import AutoTokenizer, Phi3ForCausalLM
|
| 895 |
+
|
| 896 |
+
>>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
| 897 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
| 898 |
+
|
| 899 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 900 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 901 |
+
|
| 902 |
+
>>> # Generate
|
| 903 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 904 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 905 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 906 |
+
```"""
|
| 907 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 908 |
+
output_hidden_states = (
|
| 909 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 910 |
+
)
|
| 911 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 912 |
+
|
| 913 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 914 |
+
outputs = self.model(
|
| 915 |
+
input_ids=input_ids,
|
| 916 |
+
attention_mask=attention_mask,
|
| 917 |
+
position_ids=position_ids,
|
| 918 |
+
past_key_values=past_key_values,
|
| 919 |
+
inputs_embeds=inputs_embeds,
|
| 920 |
+
use_cache=use_cache,
|
| 921 |
+
output_attentions=output_attentions,
|
| 922 |
+
output_hidden_states=output_hidden_states,
|
| 923 |
+
return_dict=return_dict,
|
| 924 |
+
cache_position=cache_position,
|
| 925 |
+
**kwargs,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
hidden_states = outputs[0]
|
| 929 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 930 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 931 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 932 |
+
|
| 933 |
+
loss = None
|
| 934 |
+
if labels is not None:
|
| 935 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 936 |
+
|
| 937 |
+
if not return_dict:
|
| 938 |
+
output = (logits,) + outputs[1:]
|
| 939 |
+
return (loss,) + output if loss is not None else output
|
| 940 |
+
|
| 941 |
+
return CausalLMOutputWithPast(
|
| 942 |
+
loss=loss,
|
| 943 |
+
logits=logits,
|
| 944 |
+
past_key_values=outputs.past_key_values,
|
| 945 |
+
hidden_states=outputs.hidden_states,
|
| 946 |
+
attentions=outputs.attentions,
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
def prepare_inputs_for_generation(
|
| 950 |
+
self,
|
| 951 |
+
input_ids,
|
| 952 |
+
past_key_values=None,
|
| 953 |
+
attention_mask=None,
|
| 954 |
+
inputs_embeds=None,
|
| 955 |
+
cache_position=None,
|
| 956 |
+
position_ids=None,
|
| 957 |
+
use_cache=True,
|
| 958 |
+
logits_to_keep=None,
|
| 959 |
+
**kwargs,
|
| 960 |
+
):
|
| 961 |
+
# Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
|
| 962 |
+
# process
|
| 963 |
+
|
| 964 |
+
# When the first time input length reached long and short factor switching point, enforce re-compute cache
|
| 965 |
+
# It will cause downside of slower at this single token position, however, better than current failure.
|
| 966 |
+
if (
|
| 967 |
+
past_key_values
|
| 968 |
+
and self.config.rope_scaling
|
| 969 |
+
and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
|
| 970 |
+
):
|
| 971 |
+
past_length = cache_position[0]
|
| 972 |
+
if past_length <= self.config.original_max_position_embeddings:
|
| 973 |
+
past_key_values = None
|
| 974 |
+
|
| 975 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 976 |
+
input_ids=input_ids,
|
| 977 |
+
past_key_values=past_key_values,
|
| 978 |
+
attention_mask=attention_mask,
|
| 979 |
+
inputs_embeds=inputs_embeds,
|
| 980 |
+
cache_position=cache_position,
|
| 981 |
+
position_ids=position_ids,
|
| 982 |
+
use_cache=use_cache,
|
| 983 |
+
logits_to_keep=logits_to_keep,
|
| 984 |
+
**kwargs,
|
| 985 |
+
)
|
| 986 |
+
return model_inputs
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
@add_start_docstrings(
|
| 990 |
+
"""
|
| 991 |
+
The Phi3 Model transformer with a sequence classification head on top (linear layer).
|
| 992 |
+
|
| 993 |
+
[`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 994 |
+
(e.g. GPT-2) do.
|
| 995 |
+
|
| 996 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 997 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 998 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 999 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1000 |
+
each row of the batch).
|
| 1001 |
+
""",
|
| 1002 |
+
PHI3_START_DOCSTRING,
|
| 1003 |
+
)
|
| 1004 |
+
class Phi3ForSequenceClassification(Phi3PreTrainedModel):
|
| 1005 |
+
def __init__(self, config):
|
| 1006 |
+
super().__init__(config)
|
| 1007 |
+
self.num_labels = config.num_labels
|
| 1008 |
+
self.model = Phi3Model(config)
|
| 1009 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1010 |
+
|
| 1011 |
+
# Initialize weights and apply final processing
|
| 1012 |
+
self.post_init()
|
| 1013 |
+
|
| 1014 |
+
def get_input_embeddings(self):
|
| 1015 |
+
return self.model.embed_tokens
|
| 1016 |
+
|
| 1017 |
+
def set_input_embeddings(self, value):
|
| 1018 |
+
self.model.embed_tokens = value
|
| 1019 |
+
|
| 1020 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 1021 |
+
def forward(
|
| 1022 |
+
self,
|
| 1023 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1024 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1025 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1026 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1027 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1028 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1029 |
+
use_cache: Optional[bool] = None,
|
| 1030 |
+
output_attentions: Optional[bool] = None,
|
| 1031 |
+
output_hidden_states: Optional[bool] = None,
|
| 1032 |
+
return_dict: Optional[bool] = None,
|
| 1033 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1034 |
+
r"""
|
| 1035 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1036 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1037 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1038 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1039 |
+
"""
|
| 1040 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1041 |
+
|
| 1042 |
+
transformer_outputs = self.model(
|
| 1043 |
+
input_ids,
|
| 1044 |
+
attention_mask=attention_mask,
|
| 1045 |
+
position_ids=position_ids,
|
| 1046 |
+
past_key_values=past_key_values,
|
| 1047 |
+
inputs_embeds=inputs_embeds,
|
| 1048 |
+
use_cache=use_cache,
|
| 1049 |
+
output_attentions=output_attentions,
|
| 1050 |
+
output_hidden_states=output_hidden_states,
|
| 1051 |
+
return_dict=return_dict,
|
| 1052 |
+
)
|
| 1053 |
+
hidden_states = transformer_outputs[0]
|
| 1054 |
+
logits = self.score(hidden_states)
|
| 1055 |
+
|
| 1056 |
+
if input_ids is not None:
|
| 1057 |
+
batch_size = input_ids.shape[0]
|
| 1058 |
+
else:
|
| 1059 |
+
batch_size = inputs_embeds.shape[0]
|
| 1060 |
+
|
| 1061 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1062 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1063 |
+
if self.config.pad_token_id is None:
|
| 1064 |
+
last_non_pad_token = -1
|
| 1065 |
+
elif input_ids is not None:
|
| 1066 |
+
# To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
|
| 1067 |
+
non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
|
| 1068 |
+
token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
|
| 1069 |
+
last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
|
| 1070 |
+
else:
|
| 1071 |
+
last_non_pad_token = -1
|
| 1072 |
+
logger.warning_once(
|
| 1073 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1074 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
|
| 1078 |
+
|
| 1079 |
+
loss = None
|
| 1080 |
+
if labels is not None:
|
| 1081 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
| 1082 |
+
|
| 1083 |
+
if not return_dict:
|
| 1084 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1085 |
+
return ((loss,) + output) if loss is not None else output
|
| 1086 |
+
|
| 1087 |
+
return SequenceClassifierOutputWithPast(
|
| 1088 |
+
loss=loss,
|
| 1089 |
+
logits=pooled_logits,
|
| 1090 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1091 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1092 |
+
attentions=transformer_outputs.attentions,
|
| 1093 |
+
)
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
@add_start_docstrings(
|
| 1097 |
+
"""
|
| 1098 |
+
The Phi3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
| 1099 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
| 1100 |
+
""",
|
| 1101 |
+
PHI3_START_DOCSTRING,
|
| 1102 |
+
)
|
| 1103 |
+
class Phi3ForTokenClassification(Phi3PreTrainedModel):
|
| 1104 |
+
def __init__(self, config):
|
| 1105 |
+
super().__init__(config)
|
| 1106 |
+
self.num_labels = config.num_labels
|
| 1107 |
+
self.model = Phi3Model(config)
|
| 1108 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
| 1109 |
+
classifier_dropout = config.classifier_dropout
|
| 1110 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
| 1111 |
+
classifier_dropout = config.hidden_dropout
|
| 1112 |
+
else:
|
| 1113 |
+
classifier_dropout = 0.1
|
| 1114 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1115 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
| 1116 |
+
|
| 1117 |
+
# Initialize weights and apply final processing
|
| 1118 |
+
self.post_init()
|
| 1119 |
+
|
| 1120 |
+
def get_input_embeddings(self):
|
| 1121 |
+
return self.model.embed_tokens
|
| 1122 |
+
|
| 1123 |
+
def set_input_embeddings(self, value):
|
| 1124 |
+
self.model.embed_tokens = value
|
| 1125 |
+
|
| 1126 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 1127 |
+
@add_code_sample_docstrings(
|
| 1128 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1129 |
+
output_type=TokenClassifierOutput,
|
| 1130 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1131 |
+
)
|
| 1132 |
+
def forward(
|
| 1133 |
+
self,
|
| 1134 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1135 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1136 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1137 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1138 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1139 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1140 |
+
use_cache: Optional[bool] = None,
|
| 1141 |
+
output_attentions: Optional[bool] = None,
|
| 1142 |
+
output_hidden_states: Optional[bool] = None,
|
| 1143 |
+
return_dict: Optional[bool] = None,
|
| 1144 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1145 |
+
r"""
|
| 1146 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1147 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1148 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1149 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1150 |
+
"""
|
| 1151 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1152 |
+
|
| 1153 |
+
outputs = self.model(
|
| 1154 |
+
input_ids,
|
| 1155 |
+
attention_mask=attention_mask,
|
| 1156 |
+
position_ids=position_ids,
|
| 1157 |
+
past_key_values=past_key_values,
|
| 1158 |
+
inputs_embeds=inputs_embeds,
|
| 1159 |
+
use_cache=use_cache,
|
| 1160 |
+
output_attentions=output_attentions,
|
| 1161 |
+
output_hidden_states=output_hidden_states,
|
| 1162 |
+
return_dict=return_dict,
|
| 1163 |
+
)
|
| 1164 |
+
sequence_output = outputs[0]
|
| 1165 |
+
sequence_output = self.dropout(sequence_output)
|
| 1166 |
+
logits = self.score(sequence_output)
|
| 1167 |
+
|
| 1168 |
+
loss = None
|
| 1169 |
+
if labels is not None:
|
| 1170 |
+
loss = self.loss_function(logits, labels, self.config)
|
| 1171 |
+
|
| 1172 |
+
if not return_dict:
|
| 1173 |
+
output = (logits,) + outputs[2:]
|
| 1174 |
+
return ((loss,) + output) if loss is not None else output
|
| 1175 |
+
|
| 1176 |
+
return TokenClassifierOutput(
|
| 1177 |
+
loss=loss,
|
| 1178 |
+
logits=logits,
|
| 1179 |
+
hidden_states=outputs.hidden_states,
|
| 1180 |
+
attentions=outputs.attentions,
|
| 1181 |
+
)
|