zhjohnchan
commited on
Upload 4 files
Browse files- configuration_chexagent.py +184 -0
- modeling_chexagent.py +1138 -0
- modeling_visual.py +322 -0
- tokenization_chexagent.py +675 -0
configuration_chexagent.py
ADDED
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 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 model configuration"""
|
17 |
+
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
from transformers.utils import logging
|
20 |
+
|
21 |
+
logger = logging.get_logger(__name__)
|
22 |
+
|
23 |
+
PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
24 |
+
"microsoft/phi-2": "https://huggingface.co/microsoft/phi-2/resolve/main/config.json",
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
class CheXagentConfig(PretrainedConfig):
|
29 |
+
r"""
|
30 |
+
This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
|
31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
32 |
+
defaults will yield a similar configuration to that of the Phi
|
33 |
+
[microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information.
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 51200):
|
38 |
+
Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`PhiModel`].
|
40 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
57 |
+
Dropout probability for mlp outputs.
|
58 |
+
embd_pdrop (`int`, *optional*, defaults to 0.0):
|
59 |
+
The dropout ratio for the embeddings.
|
60 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
61 |
+
The dropout ratio after computing the attention scores.
|
62 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
|
63 |
+
The non-linear activation function (function or string) in the decoder.
|
64 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
65 |
+
The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
|
66 |
+
tokens.
|
67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
69 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
70 |
+
The epsilon used by the rms normalization layers.
|
71 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
72 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
73 |
+
relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
|
74 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
75 |
+
Whether to tie weight embeddings
|
76 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
77 |
+
The base period of the RoPE embeddings.
|
78 |
+
rope_scaling (`Dict`, *optional*):
|
79 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
80 |
+
strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
|
81 |
+
is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
82 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
83 |
+
these scaling strategies behave:
|
84 |
+
https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
|
85 |
+
is an experimental feature, subject to breaking API changes in future versions.
|
86 |
+
partial_rotary_factor (`float`, *optional*, defaults to 0.5):
|
87 |
+
Percentage of the query and keys which will have rotary embedding.
|
88 |
+
qk_layernorm (`bool`, *optional*, defaults to `False`):
|
89 |
+
Whether or not to normalize the Queries and Keys after projecting the hidden states.
|
90 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
91 |
+
Denotes beginning of sequences token id.
|
92 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
93 |
+
Denotes end of sequences token id.
|
94 |
+
Example:
|
95 |
+
```python
|
96 |
+
>>> from transformers import PhiModel, PhiConfig
|
97 |
+
>>> # Initializing a Phi-1 style configuration
|
98 |
+
>>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
|
99 |
+
>>> # Initializing a model from the configuration
|
100 |
+
>>> model = PhiModel(configuration)
|
101 |
+
>>> # Accessing the model configuration
|
102 |
+
>>> configuration = model.config
|
103 |
+
```"""
|
104 |
+
|
105 |
+
model_type = "phi"
|
106 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
107 |
+
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
vocab_size=51200,
|
111 |
+
hidden_size=2048,
|
112 |
+
intermediate_size=8192,
|
113 |
+
num_hidden_layers=24,
|
114 |
+
num_attention_heads=32,
|
115 |
+
num_key_value_heads=None,
|
116 |
+
resid_pdrop=0.0,
|
117 |
+
embd_pdrop=0.0,
|
118 |
+
attention_dropout=0.0,
|
119 |
+
hidden_act="gelu_new",
|
120 |
+
max_position_embeddings=2048,
|
121 |
+
initializer_range=0.02,
|
122 |
+
layer_norm_eps=1e-5,
|
123 |
+
use_cache=True,
|
124 |
+
tie_word_embeddings=False,
|
125 |
+
rope_theta=10000.0,
|
126 |
+
rope_scaling=None,
|
127 |
+
partial_rotary_factor=0.5,
|
128 |
+
qk_layernorm=False,
|
129 |
+
bos_token_id=1,
|
130 |
+
eos_token_id=2,
|
131 |
+
**kwargs,
|
132 |
+
):
|
133 |
+
self.vocab_size = vocab_size
|
134 |
+
self.hidden_size = hidden_size
|
135 |
+
self.intermediate_size = intermediate_size
|
136 |
+
self.num_hidden_layers = num_hidden_layers
|
137 |
+
self.num_attention_heads = num_attention_heads
|
138 |
+
|
139 |
+
if num_key_value_heads is None:
|
140 |
+
num_key_value_heads = num_attention_heads
|
141 |
+
|
142 |
+
self.num_key_value_heads = num_key_value_heads
|
143 |
+
self.resid_pdrop = resid_pdrop
|
144 |
+
self.embd_pdrop = embd_pdrop
|
145 |
+
self.attention_dropout = attention_dropout
|
146 |
+
self.hidden_act = hidden_act
|
147 |
+
self.max_position_embeddings = max_position_embeddings
|
148 |
+
self.initializer_range = initializer_range
|
149 |
+
self.layer_norm_eps = layer_norm_eps
|
150 |
+
self.use_cache = use_cache
|
151 |
+
self.rope_theta = rope_theta
|
152 |
+
self.rope_scaling = rope_scaling
|
153 |
+
self.partial_rotary_factor = partial_rotary_factor
|
154 |
+
self.qk_layernorm = qk_layernorm
|
155 |
+
self._rope_scaling_validation()
|
156 |
+
|
157 |
+
super().__init__(
|
158 |
+
bos_token_id=bos_token_id,
|
159 |
+
eos_token_id=eos_token_id,
|
160 |
+
tie_word_embeddings=tie_word_embeddings,
|
161 |
+
**kwargs,
|
162 |
+
)
|
163 |
+
|
164 |
+
# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
|
165 |
+
def _rope_scaling_validation(self):
|
166 |
+
"""
|
167 |
+
Validate the `rope_scaling` configuration.
|
168 |
+
"""
|
169 |
+
if self.rope_scaling is None:
|
170 |
+
return
|
171 |
+
|
172 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
173 |
+
raise ValueError(
|
174 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
175 |
+
f"got {self.rope_scaling}"
|
176 |
+
)
|
177 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
178 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
179 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
180 |
+
raise ValueError(
|
181 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
182 |
+
)
|
183 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
184 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
modeling_chexagent.py
ADDED
@@ -0,0 +1,1138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ft 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 model."""
|
17 |
+
|
18 |
+
import math
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import CrossEntropyLoss
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache
|
28 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
29 |
+
from transformers.modeling_outputs import (
|
30 |
+
BaseModelOutputWithPast,
|
31 |
+
CausalLMOutputWithPast,
|
32 |
+
)
|
33 |
+
from transformers.modeling_utils import PreTrainedModel
|
34 |
+
from transformers.utils import (
|
35 |
+
add_start_docstrings,
|
36 |
+
add_start_docstrings_to_model_forward,
|
37 |
+
is_flash_attn_greater_or_equal_2_10,
|
38 |
+
logging,
|
39 |
+
)
|
40 |
+
|
41 |
+
from .configuration_chexagent import CheXagentConfig
|
42 |
+
from .modeling_visual import CLIPModel
|
43 |
+
from .tokenization_chexagent import CheXagentTokenizer
|
44 |
+
|
45 |
+
try:
|
46 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
47 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
48 |
+
except:
|
49 |
+
pass
|
50 |
+
|
51 |
+
logger = logging.get_logger(__name__)
|
52 |
+
|
53 |
+
_CHECKPOINT_FOR_DOC = "microsoft/phi-2"
|
54 |
+
_CONFIG_FOR_DOC = "CheXagentConfig"
|
55 |
+
|
56 |
+
PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
57 |
+
"microsoft/phi-2",
|
58 |
+
# See all Phi models at https://huggingface.co/models?filter=phi
|
59 |
+
]
|
60 |
+
|
61 |
+
|
62 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
63 |
+
def _get_unpad_data(attention_mask):
|
64 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
65 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
66 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
67 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
68 |
+
return (
|
69 |
+
indices,
|
70 |
+
cu_seqlens,
|
71 |
+
max_seqlen_in_batch,
|
72 |
+
)
|
73 |
+
|
74 |
+
|
75 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
|
76 |
+
class PhiRotaryEmbedding(nn.Module):
|
77 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
78 |
+
super().__init__()
|
79 |
+
|
80 |
+
self.dim = dim
|
81 |
+
self.max_position_embeddings = max_position_embeddings
|
82 |
+
self.base = base
|
83 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
84 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
85 |
+
|
86 |
+
# Build here to make `torch.jit.trace` work.
|
87 |
+
self._set_cos_sin_cache(
|
88 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
89 |
+
)
|
90 |
+
|
91 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
92 |
+
self.max_seq_len_cached = seq_len
|
93 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
94 |
+
|
95 |
+
freqs = torch.outer(t, self.inv_freq)
|
96 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
97 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
98 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
99 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
100 |
+
|
101 |
+
def forward(self, x, seq_len=None):
|
102 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
103 |
+
if seq_len > self.max_seq_len_cached:
|
104 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
105 |
+
|
106 |
+
return (
|
107 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
108 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
109 |
+
)
|
110 |
+
|
111 |
+
|
112 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
|
113 |
+
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
|
114 |
+
"""PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
115 |
+
|
116 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
117 |
+
self.scaling_factor = scaling_factor
|
118 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
119 |
+
|
120 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
121 |
+
self.max_seq_len_cached = seq_len
|
122 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
123 |
+
t = t / self.scaling_factor
|
124 |
+
|
125 |
+
freqs = torch.outer(t, self.inv_freq)
|
126 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
127 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
128 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
129 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
130 |
+
|
131 |
+
|
132 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
|
133 |
+
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
|
134 |
+
"""PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
135 |
+
|
136 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
137 |
+
self.scaling_factor = scaling_factor
|
138 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
139 |
+
|
140 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
141 |
+
self.max_seq_len_cached = seq_len
|
142 |
+
|
143 |
+
if seq_len > self.max_position_embeddings:
|
144 |
+
base = self.base * (
|
145 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
146 |
+
) ** (self.dim / (self.dim - 2))
|
147 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
148 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
149 |
+
|
150 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
151 |
+
|
152 |
+
freqs = torch.outer(t, self.inv_freq)
|
153 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
154 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
155 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
156 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
157 |
+
|
158 |
+
|
159 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
160 |
+
def rotate_half(x):
|
161 |
+
"""Rotates half the hidden dims of the input."""
|
162 |
+
x1 = x[..., : x.shape[-1] // 2]
|
163 |
+
x2 = x[..., x.shape[-1] // 2:]
|
164 |
+
return torch.cat((-x2, x1), dim=-1)
|
165 |
+
|
166 |
+
|
167 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
Args:
|
171 |
+
q (`torch.Tensor`): The query tensor.
|
172 |
+
k (`torch.Tensor`): The key tensor.
|
173 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
174 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
175 |
+
position_ids (`torch.Tensor`):
|
176 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
177 |
+
used to pass offsetted position ids when working with a KV-cache.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
|
196 |
+
class PhiMLP(nn.Module):
|
197 |
+
def __init__(self, config):
|
198 |
+
super().__init__()
|
199 |
+
self.config = config
|
200 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
201 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
202 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
203 |
+
|
204 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
205 |
+
hidden_states = self.fc1(hidden_states)
|
206 |
+
hidden_states = self.activation_fn(hidden_states)
|
207 |
+
hidden_states = self.fc2(hidden_states)
|
208 |
+
return hidden_states
|
209 |
+
|
210 |
+
|
211 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
class PhiAttention(nn.Module):
|
225 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
226 |
+
|
227 |
+
def __init__(self, config: CheXagentConfig, layer_idx: Optional[int] = None):
|
228 |
+
super().__init__()
|
229 |
+
self.config = config
|
230 |
+
self.layer_idx = layer_idx
|
231 |
+
if layer_idx is None:
|
232 |
+
logger.warning_once(
|
233 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
234 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
235 |
+
"when creating this class."
|
236 |
+
)
|
237 |
+
|
238 |
+
self.attention_dropout = config.attention_dropout
|
239 |
+
self.hidden_size = config.hidden_size
|
240 |
+
self.num_heads = config.num_attention_heads
|
241 |
+
self.head_dim = self.hidden_size // self.num_heads
|
242 |
+
self.num_key_value_heads = config.num_key_value_heads
|
243 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
244 |
+
self.max_position_embeddings = config.max_position_embeddings
|
245 |
+
self.rope_theta = config.rope_theta
|
246 |
+
self.partial_rotary_factor = config.partial_rotary_factor
|
247 |
+
self.is_causal = True
|
248 |
+
|
249 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
250 |
+
raise ValueError(
|
251 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
252 |
+
f" and `num_heads`: {self.num_heads})."
|
253 |
+
)
|
254 |
+
|
255 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
256 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
257 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
258 |
+
self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
|
259 |
+
|
260 |
+
self.qk_layernorm = config.qk_layernorm
|
261 |
+
if self.qk_layernorm:
|
262 |
+
self.q_layernorm = nn.LayerNorm(
|
263 |
+
config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
|
264 |
+
)
|
265 |
+
self.k_layernorm = nn.LayerNorm(
|
266 |
+
config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
|
267 |
+
)
|
268 |
+
|
269 |
+
self._init_rope()
|
270 |
+
|
271 |
+
def _init_rope(self):
|
272 |
+
if self.config.rope_scaling is None:
|
273 |
+
self.rotary_emb = PhiRotaryEmbedding(
|
274 |
+
int(self.partial_rotary_factor * self.head_dim),
|
275 |
+
max_position_embeddings=self.max_position_embeddings,
|
276 |
+
base=self.rope_theta,
|
277 |
+
)
|
278 |
+
else:
|
279 |
+
scaling_type = self.config.rope_scaling["type"]
|
280 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
281 |
+
if scaling_type == "linear":
|
282 |
+
self.rotary_emb = PhiLinearScalingRotaryEmbedding(
|
283 |
+
int(self.partial_rotary_factor * self.head_dim),
|
284 |
+
max_position_embeddings=self.max_position_embeddings,
|
285 |
+
scaling_factor=scaling_factor,
|
286 |
+
base=self.rope_theta,
|
287 |
+
)
|
288 |
+
elif scaling_type == "dynamic":
|
289 |
+
self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
|
290 |
+
int(self.partial_rotary_factor * self.head_dim),
|
291 |
+
max_position_embeddings=self.max_position_embeddings,
|
292 |
+
scaling_factor=scaling_factor,
|
293 |
+
base=self.rope_theta,
|
294 |
+
)
|
295 |
+
else:
|
296 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
297 |
+
|
298 |
+
# Phi-2 has an attention overflow issue (with FP16) and requires autocast to be disabled
|
299 |
+
@torch.autocast("cpu", enabled=False)
|
300 |
+
@torch.autocast("cuda", enabled=False)
|
301 |
+
def forward(
|
302 |
+
self,
|
303 |
+
hidden_states: torch.Tensor,
|
304 |
+
attention_mask: Optional[torch.Tensor] = None,
|
305 |
+
position_ids: Optional[torch.LongTensor] = None,
|
306 |
+
past_key_value: Optional[Cache] = None,
|
307 |
+
output_attentions: bool = False,
|
308 |
+
use_cache: bool = False,
|
309 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
310 |
+
bsz, q_len, _ = hidden_states.size()
|
311 |
+
|
312 |
+
query_states = self.q_proj(hidden_states)
|
313 |
+
key_states = self.k_proj(hidden_states)
|
314 |
+
value_states = self.v_proj(hidden_states)
|
315 |
+
|
316 |
+
if self.qk_layernorm:
|
317 |
+
query_states = self.q_layernorm(query_states)
|
318 |
+
key_states = self.k_layernorm(key_states)
|
319 |
+
|
320 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
321 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
322 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
323 |
+
|
324 |
+
kv_seq_len = key_states.shape[-2]
|
325 |
+
if past_key_value is not None:
|
326 |
+
if self.layer_idx is None:
|
327 |
+
raise ValueError(
|
328 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
329 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
330 |
+
"with a layer index."
|
331 |
+
)
|
332 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
333 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
334 |
+
|
335 |
+
# Partial rotary embedding
|
336 |
+
query_rot, query_pass = (
|
337 |
+
query_states[..., : self.rotary_emb.dim],
|
338 |
+
query_states[..., self.rotary_emb.dim:],
|
339 |
+
)
|
340 |
+
key_rot, key_pass = (
|
341 |
+
key_states[..., : self.rotary_emb.dim],
|
342 |
+
key_states[..., self.rotary_emb.dim:],
|
343 |
+
)
|
344 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
345 |
+
query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
346 |
+
|
347 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
348 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
349 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
350 |
+
|
351 |
+
if past_key_value is not None:
|
352 |
+
cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
|
353 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
354 |
+
|
355 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
356 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
357 |
+
|
358 |
+
# Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
|
359 |
+
attn_weights = torch.matmul(
|
360 |
+
query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
|
361 |
+
) / math.sqrt(self.head_dim)
|
362 |
+
|
363 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
364 |
+
raise ValueError(
|
365 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
366 |
+
f" {attn_weights.size()}"
|
367 |
+
)
|
368 |
+
|
369 |
+
if attention_mask is not None:
|
370 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
371 |
+
raise ValueError(
|
372 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
373 |
+
)
|
374 |
+
attn_weights = attn_weights + attention_mask
|
375 |
+
|
376 |
+
# upcast attention to fp32
|
377 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
|
378 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
379 |
+
|
380 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
381 |
+
|
382 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
383 |
+
raise ValueError(
|
384 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
385 |
+
f" {attn_output.size()}"
|
386 |
+
)
|
387 |
+
|
388 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
389 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
390 |
+
|
391 |
+
attn_output = self.dense(attn_output)
|
392 |
+
|
393 |
+
if not output_attentions:
|
394 |
+
attn_weights = None
|
395 |
+
|
396 |
+
return attn_output, attn_weights, past_key_value
|
397 |
+
|
398 |
+
|
399 |
+
class PhiFlashAttention2(PhiAttention):
|
400 |
+
"""
|
401 |
+
Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
|
402 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
403 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
404 |
+
"""
|
405 |
+
|
406 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
407 |
+
def __init__(self, *args, **kwargs):
|
408 |
+
super().__init__(*args, **kwargs)
|
409 |
+
|
410 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
411 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
412 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
413 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
414 |
+
|
415 |
+
def forward(
|
416 |
+
self,
|
417 |
+
hidden_states: torch.Tensor,
|
418 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
419 |
+
position_ids: Optional[torch.LongTensor] = None,
|
420 |
+
past_key_value: Optional[Cache] = None,
|
421 |
+
output_attentions: bool = False,
|
422 |
+
use_cache: bool = False,
|
423 |
+
**kwargs,
|
424 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
425 |
+
# PhiFlashAttention2 attention does not support output_attentions
|
426 |
+
|
427 |
+
output_attentions = False
|
428 |
+
|
429 |
+
bsz, q_len, _ = hidden_states.size()
|
430 |
+
|
431 |
+
query_states = self.q_proj(hidden_states)
|
432 |
+
key_states = self.k_proj(hidden_states)
|
433 |
+
value_states = self.v_proj(hidden_states)
|
434 |
+
|
435 |
+
if self.qk_layernorm:
|
436 |
+
query_states = self.q_layernorm(query_states)
|
437 |
+
key_states = self.k_layernorm(key_states)
|
438 |
+
|
439 |
+
# Flash attention requires the input to have the shape
|
440 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
441 |
+
# therefore we just need to keep the original shape
|
442 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
443 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
444 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
445 |
+
|
446 |
+
kv_seq_len = key_states.shape[-2]
|
447 |
+
if past_key_value is not None:
|
448 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
449 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
450 |
+
|
451 |
+
# Partial rotary embedding
|
452 |
+
query_rot, query_pass = (
|
453 |
+
query_states[..., : self.rotary_emb.dim],
|
454 |
+
query_states[..., self.rotary_emb.dim:],
|
455 |
+
)
|
456 |
+
key_rot, key_pass = (
|
457 |
+
key_states[..., : self.rotary_emb.dim],
|
458 |
+
key_states[..., self.rotary_emb.dim:],
|
459 |
+
)
|
460 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
461 |
+
query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
462 |
+
|
463 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
464 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
465 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
466 |
+
|
467 |
+
if past_key_value is not None:
|
468 |
+
cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
|
469 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
470 |
+
|
471 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
472 |
+
# to be able to avoid many of these transpose/reshape/view.
|
473 |
+
query_states = query_states.transpose(1, 2)
|
474 |
+
key_states = key_states.transpose(1, 2)
|
475 |
+
value_states = value_states.transpose(1, 2)
|
476 |
+
|
477 |
+
attn_dropout = self.attention_dropout if self.training else 0.0
|
478 |
+
|
479 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
480 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
481 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
482 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
483 |
+
# in fp32.
|
484 |
+
|
485 |
+
if query_states.dtype == torch.float32:
|
486 |
+
if torch.is_autocast_enabled():
|
487 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
488 |
+
# Handle the case where the model is quantized
|
489 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
490 |
+
target_dtype = self.config._pre_quantization_dtype
|
491 |
+
else:
|
492 |
+
target_dtype = self.q_proj.weight.dtype
|
493 |
+
|
494 |
+
logger.warning_once(
|
495 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
496 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
497 |
+
f" {target_dtype}."
|
498 |
+
)
|
499 |
+
|
500 |
+
query_states = query_states.to(target_dtype)
|
501 |
+
key_states = key_states.to(target_dtype)
|
502 |
+
value_states = value_states.to(target_dtype)
|
503 |
+
|
504 |
+
attn_output = self._flash_attention_forward(
|
505 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
|
506 |
+
)
|
507 |
+
|
508 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
509 |
+
attn_output = self.dense(attn_output)
|
510 |
+
|
511 |
+
if not output_attentions:
|
512 |
+
attn_weights = None
|
513 |
+
|
514 |
+
return attn_output, attn_weights, past_key_value
|
515 |
+
|
516 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
|
517 |
+
def _flash_attention_forward(
|
518 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
519 |
+
):
|
520 |
+
"""
|
521 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
522 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
523 |
+
Args:
|
524 |
+
query_states (`torch.Tensor`):
|
525 |
+
Input query states to be passed to Flash Attention API
|
526 |
+
key_states (`torch.Tensor`):
|
527 |
+
Input key states to be passed to Flash Attention API
|
528 |
+
value_states (`torch.Tensor`):
|
529 |
+
Input value states to be passed to Flash Attention API
|
530 |
+
attention_mask (`torch.Tensor`):
|
531 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
532 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
533 |
+
dropout (`int`, *optional*):
|
534 |
+
Attention dropout
|
535 |
+
softmax_scale (`float`, *optional*):
|
536 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
537 |
+
"""
|
538 |
+
if not self._flash_attn_uses_top_left_mask:
|
539 |
+
causal = self.is_causal
|
540 |
+
else:
|
541 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
542 |
+
causal = self.is_causal and query_length != 1
|
543 |
+
|
544 |
+
# Contains at least one padding token in the sequence
|
545 |
+
if attention_mask is not None:
|
546 |
+
batch_size = query_states.shape[0]
|
547 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
548 |
+
query_states, key_states, value_states, attention_mask, query_length
|
549 |
+
)
|
550 |
+
|
551 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
552 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
553 |
+
|
554 |
+
attn_output_unpad = flash_attn_varlen_func(
|
555 |
+
query_states,
|
556 |
+
key_states,
|
557 |
+
value_states,
|
558 |
+
cu_seqlens_q=cu_seqlens_q,
|
559 |
+
cu_seqlens_k=cu_seqlens_k,
|
560 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
561 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
562 |
+
dropout_p=dropout,
|
563 |
+
softmax_scale=softmax_scale,
|
564 |
+
causal=causal,
|
565 |
+
)
|
566 |
+
|
567 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
568 |
+
else:
|
569 |
+
attn_output = flash_attn_func(
|
570 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
571 |
+
)
|
572 |
+
|
573 |
+
return attn_output
|
574 |
+
|
575 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
|
576 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
577 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
578 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
579 |
+
|
580 |
+
key_layer = index_first_axis(
|
581 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
582 |
+
)
|
583 |
+
value_layer = index_first_axis(
|
584 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
585 |
+
)
|
586 |
+
if query_length == kv_seq_len:
|
587 |
+
query_layer = index_first_axis(
|
588 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
589 |
+
)
|
590 |
+
cu_seqlens_q = cu_seqlens_k
|
591 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
592 |
+
indices_q = indices_k
|
593 |
+
elif query_length == 1:
|
594 |
+
max_seqlen_in_batch_q = 1
|
595 |
+
cu_seqlens_q = torch.arange(
|
596 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
597 |
+
) # There is a memcpy here, that is very bad.
|
598 |
+
indices_q = cu_seqlens_q[:-1]
|
599 |
+
query_layer = query_layer.squeeze(1)
|
600 |
+
else:
|
601 |
+
# The -q_len: slice assumes left padding.
|
602 |
+
attention_mask = attention_mask[:, -query_length:]
|
603 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
604 |
+
|
605 |
+
return (
|
606 |
+
query_layer,
|
607 |
+
key_layer,
|
608 |
+
value_layer,
|
609 |
+
indices_q,
|
610 |
+
(cu_seqlens_q, cu_seqlens_k),
|
611 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
612 |
+
)
|
613 |
+
|
614 |
+
|
615 |
+
PHI_ATTENTION_CLASSES = {
|
616 |
+
"eager": PhiAttention,
|
617 |
+
"flash_attention_2": PhiFlashAttention2,
|
618 |
+
}
|
619 |
+
|
620 |
+
|
621 |
+
class PhiDecoderLayer(nn.Module):
|
622 |
+
def __init__(self, config: CheXagentConfig, layer_idx: int):
|
623 |
+
super().__init__()
|
624 |
+
self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
|
625 |
+
self.mlp = PhiMLP(config)
|
626 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
627 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
628 |
+
|
629 |
+
def forward(
|
630 |
+
self,
|
631 |
+
hidden_states: torch.Tensor,
|
632 |
+
attention_mask: Optional[torch.Tensor] = None,
|
633 |
+
position_ids: Optional[torch.LongTensor] = None,
|
634 |
+
output_attentions: Optional[bool] = False,
|
635 |
+
use_cache: Optional[bool] = False,
|
636 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
637 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
638 |
+
"""
|
639 |
+
Args:
|
640 |
+
hidden_states (`torch.FloatTensor`):
|
641 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
642 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
643 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
644 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
645 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
646 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
647 |
+
output_attentions (`bool`, *optional*):
|
648 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
649 |
+
returned tensors for more detail.
|
650 |
+
use_cache (`bool`, *optional*):
|
651 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
652 |
+
(see `past_key_values`).
|
653 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
654 |
+
"""
|
655 |
+
|
656 |
+
residual = hidden_states
|
657 |
+
|
658 |
+
hidden_states = self.input_layernorm(hidden_states)
|
659 |
+
|
660 |
+
# Self Attention
|
661 |
+
attn_outputs, self_attn_weights, present_key_value = self.self_attn(
|
662 |
+
hidden_states=hidden_states,
|
663 |
+
attention_mask=attention_mask,
|
664 |
+
position_ids=position_ids,
|
665 |
+
past_key_value=past_key_value,
|
666 |
+
output_attentions=output_attentions,
|
667 |
+
use_cache=use_cache,
|
668 |
+
)
|
669 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
670 |
+
|
671 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
672 |
+
hidden_states = attn_outputs + feed_forward_hidden_states + residual
|
673 |
+
outputs = (hidden_states,)
|
674 |
+
|
675 |
+
if output_attentions:
|
676 |
+
outputs += (self_attn_weights,)
|
677 |
+
|
678 |
+
if use_cache:
|
679 |
+
outputs += (present_key_value,)
|
680 |
+
|
681 |
+
return outputs
|
682 |
+
|
683 |
+
|
684 |
+
PHI_START_DOCSTRING = r"""
|
685 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
686 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
687 |
+
etc.)
|
688 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
689 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
690 |
+
and behavior.
|
691 |
+
Parameters:
|
692 |
+
config ([`CheXagentConfig`]):
|
693 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
694 |
+
load the weights associated with the model, only the configuration. Check out the
|
695 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
696 |
+
"""
|
697 |
+
|
698 |
+
|
699 |
+
@add_start_docstrings(
|
700 |
+
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
|
701 |
+
PHI_START_DOCSTRING,
|
702 |
+
)
|
703 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
704 |
+
config_class = CheXagentConfig
|
705 |
+
base_model_prefix = "model"
|
706 |
+
supports_gradient_checkpointing = True
|
707 |
+
_no_split_modules = ["PhiDecoderLayer"]
|
708 |
+
_skip_keys_device_placement = "past_key_values"
|
709 |
+
_supports_flash_attn_2 = True
|
710 |
+
_supports_cache_class = True
|
711 |
+
|
712 |
+
def _init_weights(self, module):
|
713 |
+
std = self.config.initializer_range
|
714 |
+
if isinstance(module, nn.Linear):
|
715 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
716 |
+
if module.bias is not None:
|
717 |
+
module.bias.data.zero_()
|
718 |
+
elif isinstance(module, nn.Embedding):
|
719 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
720 |
+
if module.padding_idx is not None:
|
721 |
+
module.weight.data[module.padding_idx].zero_()
|
722 |
+
|
723 |
+
|
724 |
+
PHI_INPUTS_DOCSTRING = r"""
|
725 |
+
Args:
|
726 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
727 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
728 |
+
it.
|
729 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
730 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
731 |
+
[What are input IDs?](../glossary#input-ids)
|
732 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
733 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
734 |
+
- 1 for tokens that are **not masked**,
|
735 |
+
- 0 for tokens that are **masked**.
|
736 |
+
[What are attention masks?](../glossary#attention-mask)
|
737 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
738 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
739 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
740 |
+
`past_key_values`).
|
741 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
742 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
743 |
+
information on the default strategy.
|
744 |
+
- 1 indicates the head is **not masked**,
|
745 |
+
- 0 indicates the head is **masked**.
|
746 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
747 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
748 |
+
config.n_positions - 1]`.
|
749 |
+
[What are position IDs?](../glossary#position-ids)
|
750 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
751 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
752 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
753 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
754 |
+
Two formats are allowed:
|
755 |
+
- a [`~cache_utils.Cache`] instance;
|
756 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
757 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
758 |
+
cache format.
|
759 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
760 |
+
legacy cache format will be returned.
|
761 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
762 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
763 |
+
of shape `(batch_size, sequence_length)`.
|
764 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
765 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
766 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
767 |
+
model's internal embedding lookup matrix.
|
768 |
+
use_cache (`bool`, *optional*):
|
769 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
770 |
+
`past_key_values`).
|
771 |
+
output_attentions (`bool`, *optional*):
|
772 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
773 |
+
tensors for more detail.
|
774 |
+
output_hidden_states (`bool`, *optional*):
|
775 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
776 |
+
more detail.
|
777 |
+
return_dict (`bool`, *optional*):
|
778 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
779 |
+
"""
|
780 |
+
|
781 |
+
|
782 |
+
class CheXagentModel(PhiPreTrainedModel):
|
783 |
+
"""
|
784 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
|
785 |
+
Args:
|
786 |
+
config: CheXagentConfig
|
787 |
+
"""
|
788 |
+
|
789 |
+
def __init__(self, config: CheXagentConfig):
|
790 |
+
super().__init__(config)
|
791 |
+
self.padding_idx = config.pad_token_id
|
792 |
+
self.vocab_size = config.vocab_size
|
793 |
+
|
794 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
795 |
+
self.embed_dropout = nn.Dropout(config.embd_pdrop)
|
796 |
+
self.layers = nn.ModuleList(
|
797 |
+
[PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
798 |
+
)
|
799 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
800 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
801 |
+
|
802 |
+
self.gradient_checkpointing = False
|
803 |
+
|
804 |
+
# Initialize weights and apply final processing
|
805 |
+
self.post_init()
|
806 |
+
|
807 |
+
# IMAGE
|
808 |
+
self.tokenizer = CheXagentTokenizer.from_pretrained(config.name_or_path)
|
809 |
+
# self.visual = VisionEnsembleModel(**config.visual)
|
810 |
+
self.visual = CLIPModel(**config.visual)
|
811 |
+
# self.visual = DINOv2Model(**config.visual)
|
812 |
+
|
813 |
+
def get_input_embeddings(self):
|
814 |
+
return self.embed_tokens
|
815 |
+
|
816 |
+
def set_input_embeddings(self, value):
|
817 |
+
self.embed_tokens = value
|
818 |
+
|
819 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
820 |
+
def forward(
|
821 |
+
self,
|
822 |
+
input_ids: torch.LongTensor = None,
|
823 |
+
attention_mask: Optional[torch.Tensor] = None,
|
824 |
+
position_ids: Optional[torch.LongTensor] = None,
|
825 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
826 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
827 |
+
use_cache: Optional[bool] = None,
|
828 |
+
output_attentions: Optional[bool] = None,
|
829 |
+
output_hidden_states: Optional[bool] = None,
|
830 |
+
return_dict: Optional[bool] = None,
|
831 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
832 |
+
# IMAGE: encode images
|
833 |
+
if past_key_values is None and torch.any(input_ids == self.tokenizer.img_start_id):
|
834 |
+
bos_pos = torch.where(input_ids == self.tokenizer.img_start_id)
|
835 |
+
eos_pos = torch.where(input_ids == self.tokenizer.img_end_id)
|
836 |
+
assert (bos_pos[0] == eos_pos[0]).all()
|
837 |
+
img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1)
|
838 |
+
image_paths = []
|
839 |
+
for i, a, b in img_pos:
|
840 |
+
image = input_ids[i][a + 1: b - 1].tolist()
|
841 |
+
image = image[: image.index(self.tokenizer.img_pad_id)]
|
842 |
+
image_paths.append(self.tokenizer.decode(image))
|
843 |
+
images = self.visual.encode(image_paths, training=self.training)
|
844 |
+
assert images.shape[0] == len(images)
|
845 |
+
fake_images = None
|
846 |
+
elif self.training:
|
847 |
+
fake_images = torch.zeros(1, 3, 512, 512).to(
|
848 |
+
dtype=next(self.visual.parameters()).dtype, device=next(self.visual.parameters()).device)
|
849 |
+
images = self.visual(fake_images)
|
850 |
+
else:
|
851 |
+
fake_images = None
|
852 |
+
images = None
|
853 |
+
|
854 |
+
# set constants
|
855 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
856 |
+
output_hidden_states = (
|
857 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
858 |
+
)
|
859 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
860 |
+
|
861 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
862 |
+
|
863 |
+
# IMAGE: retrieve input_ids and inputs_embeds
|
864 |
+
if input_ids is not None and inputs_embeds is not None:
|
865 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
866 |
+
elif input_ids is not None:
|
867 |
+
input_shape = input_ids.size()
|
868 |
+
batch_size, seq_length = input_ids.shape[:2]
|
869 |
+
elif inputs_embeds is not None:
|
870 |
+
input_shape = inputs_embeds.size()[:-1]
|
871 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
872 |
+
else:
|
873 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
874 |
+
|
875 |
+
past_key_values_length = 0
|
876 |
+
|
877 |
+
if self.gradient_checkpointing and self.training:
|
878 |
+
if use_cache:
|
879 |
+
logger.warning_once(
|
880 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
881 |
+
)
|
882 |
+
use_cache = False
|
883 |
+
|
884 |
+
if use_cache:
|
885 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
886 |
+
if use_legacy_cache:
|
887 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
888 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
889 |
+
|
890 |
+
if position_ids is None:
|
891 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
892 |
+
position_ids = torch.arange(
|
893 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
894 |
+
)
|
895 |
+
position_ids = position_ids.unsqueeze(0)
|
896 |
+
|
897 |
+
if inputs_embeds is None:
|
898 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
899 |
+
|
900 |
+
inputs_embeds = self.embed_dropout(inputs_embeds)
|
901 |
+
|
902 |
+
# Attention mask.
|
903 |
+
if self._use_flash_attention_2:
|
904 |
+
# 2d mask is passed through the layers
|
905 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
906 |
+
else:
|
907 |
+
# 4d mask is passed through the layers
|
908 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
909 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
910 |
+
)
|
911 |
+
|
912 |
+
# IMAGE: embed positions
|
913 |
+
hidden_states = inputs_embeds.clone()
|
914 |
+
if fake_images is not None:
|
915 |
+
hidden_states = hidden_states + images.mean() * 0
|
916 |
+
elif images is not None:
|
917 |
+
for idx, (i, a, b) in enumerate(img_pos):
|
918 |
+
hidden_states[i][a + 1: b] = images[idx]
|
919 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
920 |
+
|
921 |
+
# decoder layers
|
922 |
+
all_hidden_states = () if output_hidden_states else None
|
923 |
+
all_self_attns = () if output_attentions else None
|
924 |
+
next_decoder_cache = None
|
925 |
+
|
926 |
+
for decoder_layer in self.layers:
|
927 |
+
if output_hidden_states:
|
928 |
+
all_hidden_states += (hidden_states,)
|
929 |
+
|
930 |
+
if self.gradient_checkpointing and self.training:
|
931 |
+
layer_outputs = self._gradient_checkpointing_func(
|
932 |
+
decoder_layer.__call__,
|
933 |
+
hidden_states,
|
934 |
+
attention_mask,
|
935 |
+
position_ids,
|
936 |
+
past_key_values,
|
937 |
+
output_attentions,
|
938 |
+
)
|
939 |
+
else:
|
940 |
+
layer_outputs = decoder_layer(
|
941 |
+
hidden_states,
|
942 |
+
attention_mask=attention_mask,
|
943 |
+
position_ids=position_ids,
|
944 |
+
past_key_value=past_key_values,
|
945 |
+
output_attentions=output_attentions,
|
946 |
+
use_cache=use_cache,
|
947 |
+
)
|
948 |
+
|
949 |
+
hidden_states = layer_outputs[0]
|
950 |
+
|
951 |
+
if use_cache:
|
952 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
953 |
+
|
954 |
+
if output_attentions:
|
955 |
+
all_self_attns += (layer_outputs[1],)
|
956 |
+
|
957 |
+
hidden_states = self.final_layernorm(hidden_states)
|
958 |
+
|
959 |
+
# add hidden states from the last decoder layer
|
960 |
+
if output_hidden_states:
|
961 |
+
all_hidden_states += (hidden_states,)
|
962 |
+
|
963 |
+
next_cache = None
|
964 |
+
if use_cache:
|
965 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
966 |
+
if not return_dict:
|
967 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
968 |
+
return BaseModelOutputWithPast(
|
969 |
+
last_hidden_state=hidden_states,
|
970 |
+
past_key_values=next_cache,
|
971 |
+
hidden_states=all_hidden_states,
|
972 |
+
attentions=all_self_attns,
|
973 |
+
)
|
974 |
+
|
975 |
+
|
976 |
+
class CheXagentForCausalLM(PhiPreTrainedModel):
|
977 |
+
_tied_weights_keys = ["lm_head.weight"]
|
978 |
+
|
979 |
+
def __init__(self, config):
|
980 |
+
super().__init__(config)
|
981 |
+
self.model = CheXagentModel(config)
|
982 |
+
self.vocab_size = config.vocab_size
|
983 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
984 |
+
|
985 |
+
# Initialize weights and apply final processing
|
986 |
+
self.post_init()
|
987 |
+
|
988 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
|
989 |
+
def get_input_embeddings(self):
|
990 |
+
return self.model.embed_tokens
|
991 |
+
|
992 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
|
993 |
+
def set_input_embeddings(self, value):
|
994 |
+
self.model.embed_tokens = value
|
995 |
+
|
996 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
|
997 |
+
def get_output_embeddings(self):
|
998 |
+
return self.lm_head
|
999 |
+
|
1000 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
|
1001 |
+
def set_output_embeddings(self, new_embeddings):
|
1002 |
+
self.lm_head = new_embeddings
|
1003 |
+
|
1004 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
|
1005 |
+
def set_decoder(self, decoder):
|
1006 |
+
self.model = decoder
|
1007 |
+
|
1008 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
|
1009 |
+
def get_decoder(self):
|
1010 |
+
return self.model
|
1011 |
+
|
1012 |
+
def forward(
|
1013 |
+
self,
|
1014 |
+
input_ids: torch.LongTensor = None,
|
1015 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1016 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1017 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1018 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1019 |
+
labels: Optional[torch.LongTensor] = None,
|
1020 |
+
use_cache: Optional[bool] = None,
|
1021 |
+
output_attentions: Optional[bool] = None,
|
1022 |
+
output_hidden_states: Optional[bool] = None,
|
1023 |
+
return_dict: Optional[bool] = None,
|
1024 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1025 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1026 |
+
output_hidden_states = (
|
1027 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1028 |
+
)
|
1029 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1030 |
+
|
1031 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1032 |
+
outputs = self.model(
|
1033 |
+
input_ids=input_ids,
|
1034 |
+
attention_mask=attention_mask,
|
1035 |
+
position_ids=position_ids,
|
1036 |
+
past_key_values=past_key_values,
|
1037 |
+
inputs_embeds=inputs_embeds,
|
1038 |
+
use_cache=use_cache,
|
1039 |
+
output_attentions=output_attentions,
|
1040 |
+
output_hidden_states=output_hidden_states,
|
1041 |
+
return_dict=return_dict,
|
1042 |
+
)
|
1043 |
+
|
1044 |
+
hidden_states = outputs[0]
|
1045 |
+
logits = self.lm_head(hidden_states)
|
1046 |
+
logits = logits.float()
|
1047 |
+
|
1048 |
+
loss = None
|
1049 |
+
if labels is not None:
|
1050 |
+
# Shift so that tokens < n predict n
|
1051 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1052 |
+
shift_labels = labels[..., 1:].contiguous()
|
1053 |
+
# Flatten the tokens
|
1054 |
+
loss_fct = CrossEntropyLoss()
|
1055 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1056 |
+
shift_labels = shift_labels.view(-1)
|
1057 |
+
# Enable model parallelism
|
1058 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1059 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1060 |
+
|
1061 |
+
if not return_dict:
|
1062 |
+
output = (logits,) + outputs[1:]
|
1063 |
+
return (loss,) + output if loss is not None else output
|
1064 |
+
|
1065 |
+
return CausalLMOutputWithPast(
|
1066 |
+
loss=loss,
|
1067 |
+
logits=logits,
|
1068 |
+
past_key_values=outputs.past_key_values,
|
1069 |
+
hidden_states=outputs.hidden_states,
|
1070 |
+
attentions=outputs.attentions,
|
1071 |
+
)
|
1072 |
+
|
1073 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
|
1074 |
+
def prepare_inputs_for_generation(
|
1075 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1076 |
+
):
|
1077 |
+
if past_key_values is not None:
|
1078 |
+
if isinstance(past_key_values, Cache):
|
1079 |
+
cache_length = past_key_values.get_seq_length()
|
1080 |
+
past_length = past_key_values.seen_tokens
|
1081 |
+
max_cache_length = past_key_values.get_max_length()
|
1082 |
+
else:
|
1083 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1084 |
+
max_cache_length = None
|
1085 |
+
|
1086 |
+
# Keep only the unprocessed tokens:
|
1087 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1088 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1089 |
+
# input)
|
1090 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1091 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
|
1092 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1093 |
+
# input_ids based on the past_length.
|
1094 |
+
elif past_length < input_ids.shape[1]:
|
1095 |
+
input_ids = input_ids[:, past_length:]
|
1096 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1097 |
+
|
1098 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1099 |
+
if (
|
1100 |
+
max_cache_length is not None
|
1101 |
+
and attention_mask is not None
|
1102 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1103 |
+
):
|
1104 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1105 |
+
|
1106 |
+
position_ids = kwargs.get("position_ids", None)
|
1107 |
+
if attention_mask is not None and position_ids is None:
|
1108 |
+
# create position_ids on the fly for batch generation
|
1109 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1110 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1111 |
+
if past_key_values:
|
1112 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
1113 |
+
|
1114 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1115 |
+
if inputs_embeds is not None and past_key_values is None:
|
1116 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1117 |
+
else:
|
1118 |
+
model_inputs = {"input_ids": input_ids}
|
1119 |
+
|
1120 |
+
model_inputs.update(
|
1121 |
+
{
|
1122 |
+
"position_ids": position_ids,
|
1123 |
+
"past_key_values": past_key_values,
|
1124 |
+
"use_cache": kwargs.get("use_cache"),
|
1125 |
+
"attention_mask": attention_mask,
|
1126 |
+
}
|
1127 |
+
)
|
1128 |
+
return model_inputs
|
1129 |
+
|
1130 |
+
@staticmethod
|
1131 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
|
1132 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1133 |
+
reordered_past = ()
|
1134 |
+
for layer_past in past_key_values:
|
1135 |
+
reordered_past += (
|
1136 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1137 |
+
)
|
1138 |
+
return reordered_past
|
modeling_visual.py
ADDED
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import math
|
3 |
+
import re
|
4 |
+
from functools import partial
|
5 |
+
from typing import List
|
6 |
+
|
7 |
+
import albumentations as A
|
8 |
+
import cv2
|
9 |
+
import numpy as np
|
10 |
+
import pyarrow as pa
|
11 |
+
import requests
|
12 |
+
import torch
|
13 |
+
from PIL import Image
|
14 |
+
from albumentations.pytorch import ToTensorV2
|
15 |
+
from einops import rearrange
|
16 |
+
from torch import nn
|
17 |
+
from torch.nn import functional as F
|
18 |
+
from torch.nn.init import trunc_normal_
|
19 |
+
from torchvision import transforms
|
20 |
+
from torchvision.transforms import InterpolationMode
|
21 |
+
from transformers import AutoModel, AutoProcessor
|
22 |
+
from transformers.activations import ACT2FN
|
23 |
+
|
24 |
+
|
25 |
+
class TransformCXR(object):
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
image_size=448,
|
29 |
+
mean=(0.48145466, 0.4578275, 0.40821073),
|
30 |
+
std=(0.26862954, 0.26130258, 0.27577711),
|
31 |
+
allow_shift=True,
|
32 |
+
training=True,
|
33 |
+
normalize=True
|
34 |
+
):
|
35 |
+
|
36 |
+
resize_size = image_size
|
37 |
+
p_train = 0.5
|
38 |
+
shift_limit = (-0.0, 0.0)
|
39 |
+
scale_limit = (-0.1, -0.02)
|
40 |
+
rotate_limit = 5
|
41 |
+
scale = (0.00, 0.01)
|
42 |
+
brightness_limit = (-0.15, 0.15)
|
43 |
+
contrast_limit = (-0.05, 0.05)
|
44 |
+
pad_mode = cv2.BORDER_CONSTANT
|
45 |
+
pad_val = (0, 0, 0)
|
46 |
+
|
47 |
+
if training:
|
48 |
+
if allow_shift:
|
49 |
+
transform_list = [
|
50 |
+
A.ShiftScaleRotate(
|
51 |
+
shift_limit=shift_limit, scale_limit=scale_limit,
|
52 |
+
rotate_limit=rotate_limit, border_mode=pad_mode, value=pad_val,
|
53 |
+
p=p_train
|
54 |
+
),
|
55 |
+
A.Perspective(
|
56 |
+
scale=scale, pad_mode=pad_mode, pad_val=pad_val, p=p_train
|
57 |
+
),
|
58 |
+
A.Resize(height=resize_size, width=resize_size, interpolation=cv2.INTER_CUBIC),
|
59 |
+
A.RandomCrop(height=image_size, width=image_size),
|
60 |
+
A.RandomBrightnessContrast(
|
61 |
+
brightness_limit=brightness_limit, contrast_limit=contrast_limit,
|
62 |
+
p=p_train
|
63 |
+
)
|
64 |
+
]
|
65 |
+
else:
|
66 |
+
transform_list = [
|
67 |
+
A.Resize(height=image_size, width=image_size, interpolation=cv2.INTER_CUBIC),
|
68 |
+
A.RandomBrightnessContrast(
|
69 |
+
brightness_limit=brightness_limit, contrast_limit=contrast_limit,
|
70 |
+
p=p_train
|
71 |
+
)
|
72 |
+
]
|
73 |
+
else:
|
74 |
+
transform_list = [
|
75 |
+
A.Resize(height=image_size, width=image_size, interpolation=cv2.INTER_CUBIC)
|
76 |
+
]
|
77 |
+
|
78 |
+
if normalize:
|
79 |
+
transform_list += [A.Normalize(mean=mean, std=std), ToTensorV2(transpose_mask=True)]
|
80 |
+
|
81 |
+
self.transforms = A.Compose(transform_list)
|
82 |
+
|
83 |
+
def __call__(self, image):
|
84 |
+
image = np.array(image)
|
85 |
+
return self.transforms(image=image)['image']
|
86 |
+
|
87 |
+
|
88 |
+
def get_abs_pos(abs_pos, tgt_size):
|
89 |
+
# abs_pos: L, C
|
90 |
+
# tgt_size: M
|
91 |
+
# return: M, C
|
92 |
+
src_size = int(math.sqrt(abs_pos.size(0)))
|
93 |
+
tgt_size = int(math.sqrt(tgt_size))
|
94 |
+
dtype = abs_pos.dtype
|
95 |
+
|
96 |
+
if src_size != tgt_size:
|
97 |
+
return F.interpolate(
|
98 |
+
abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
|
99 |
+
size=(tgt_size, tgt_size),
|
100 |
+
mode="bicubic",
|
101 |
+
align_corners=False,
|
102 |
+
).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
|
103 |
+
else:
|
104 |
+
return abs_pos
|
105 |
+
|
106 |
+
|
107 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
|
108 |
+
"""
|
109 |
+
grid_size: int of the grid height and width
|
110 |
+
return:
|
111 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
112 |
+
"""
|
113 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
114 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
115 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
116 |
+
grid = np.stack(grid, axis=0)
|
117 |
+
|
118 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
119 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
120 |
+
if cls_token:
|
121 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
122 |
+
return pos_embed
|
123 |
+
|
124 |
+
|
125 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
126 |
+
assert embed_dim % 2 == 0
|
127 |
+
|
128 |
+
# use half of dimensions to encode grid_h
|
129 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
130 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
131 |
+
|
132 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
133 |
+
return emb
|
134 |
+
|
135 |
+
|
136 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
137 |
+
"""
|
138 |
+
embed_dim: output dimension for each position
|
139 |
+
pos: a list of positions to be encoded: size (M,)
|
140 |
+
out: (M, D)
|
141 |
+
"""
|
142 |
+
assert embed_dim % 2 == 0
|
143 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
144 |
+
omega /= embed_dim / 2.
|
145 |
+
omega = 1. / 10000 ** omega # (D/2,)
|
146 |
+
|
147 |
+
pos = pos.reshape(-1) # (M,)
|
148 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
149 |
+
|
150 |
+
emb_sin = np.sin(out) # (M, D/2)
|
151 |
+
emb_cos = np.cos(out) # (M, D/2)
|
152 |
+
|
153 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
154 |
+
return emb
|
155 |
+
|
156 |
+
|
157 |
+
class Resampler(nn.Module):
|
158 |
+
"""
|
159 |
+
A 2D perceiver-resampler network with one cross attention layers by
|
160 |
+
(grid_size**2) learnable queries and 2d sincos pos_emb
|
161 |
+
Outputs:
|
162 |
+
A tensor with the shape of (grid_size**2, embed_dim)
|
163 |
+
"""
|
164 |
+
|
165 |
+
def __init__(
|
166 |
+
self,
|
167 |
+
grid_size,
|
168 |
+
embed_dim,
|
169 |
+
num_heads,
|
170 |
+
kv_dim=None,
|
171 |
+
norm_layer=nn.LayerNorm
|
172 |
+
):
|
173 |
+
super().__init__()
|
174 |
+
self.num_queries = grid_size ** 2
|
175 |
+
self.embed_dim = embed_dim
|
176 |
+
self.num_heads = num_heads
|
177 |
+
|
178 |
+
self.pos_embed = nn.Parameter(
|
179 |
+
torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
|
180 |
+
).requires_grad_(False)
|
181 |
+
|
182 |
+
self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
|
183 |
+
# trunc_normal_(self.query, std=.02)
|
184 |
+
|
185 |
+
if kv_dim is not None and kv_dim != embed_dim:
|
186 |
+
self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
|
187 |
+
else:
|
188 |
+
self.kv_proj = nn.Identity()
|
189 |
+
|
190 |
+
self.attn = nn.MultiheadAttention(embed_dim, num_heads)
|
191 |
+
self.ln_q = norm_layer(embed_dim)
|
192 |
+
self.ln_kv = norm_layer(embed_dim)
|
193 |
+
# self.apply(self._init_weights)
|
194 |
+
|
195 |
+
def _init_weights(self, m):
|
196 |
+
if isinstance(m, nn.Linear):
|
197 |
+
trunc_normal_(m.weight, std=.02)
|
198 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
199 |
+
nn.init.constant_(m.bias, 0)
|
200 |
+
elif isinstance(m, nn.LayerNorm):
|
201 |
+
nn.init.constant_(m.bias, 0)
|
202 |
+
nn.init.constant_(m.weight, 1.0)
|
203 |
+
|
204 |
+
def forward(self, x, attn_mask=None):
|
205 |
+
|
206 |
+
pos_embed = get_abs_pos(self.pos_embed, x.size(1))
|
207 |
+
|
208 |
+
x = self.kv_proj(x)
|
209 |
+
x = self.ln_kv(x).permute(1, 0, 2)
|
210 |
+
|
211 |
+
N = x.shape[1]
|
212 |
+
q = self.ln_q(self.query)
|
213 |
+
out = self.attn(
|
214 |
+
self._repeat(q, N) + self.pos_embed.unsqueeze(1),
|
215 |
+
x + pos_embed.unsqueeze(1),
|
216 |
+
x,
|
217 |
+
attn_mask=attn_mask
|
218 |
+
)[0]
|
219 |
+
return out.permute(1, 0, 2)
|
220 |
+
|
221 |
+
def _repeat(self, query, N: int):
|
222 |
+
return query.unsqueeze(1).repeat(1, N, 1)
|
223 |
+
|
224 |
+
|
225 |
+
class CLIPModel(nn.Module):
|
226 |
+
|
227 |
+
def __init__(
|
228 |
+
self,
|
229 |
+
image_size: int,
|
230 |
+
n_queries: int = 256,
|
231 |
+
output_dim: int = 512,
|
232 |
+
vision_model_name_or_path: str = "StanfordAIMI/XraySigLIP__vit-l-16-siglip-384__webli",
|
233 |
+
**kwargs
|
234 |
+
):
|
235 |
+
super().__init__()
|
236 |
+
# load model and processor
|
237 |
+
self.model = AutoModel.from_pretrained(vision_model_name_or_path).vision_model
|
238 |
+
self.processor = AutoProcessor.from_pretrained(vision_model_name_or_path).image_processor
|
239 |
+
|
240 |
+
# set constants
|
241 |
+
self.image_height, self.image_width = self.image_size = (image_size, image_size)
|
242 |
+
width = self.model.config.hidden_size
|
243 |
+
patch_height, patch_width = self.model.embeddings.patch_embedding.kernel_size
|
244 |
+
self.grid_size = (self.image_height // patch_height, self.image_width // patch_width)
|
245 |
+
self.output_dim = output_dim
|
246 |
+
|
247 |
+
# Transforms
|
248 |
+
self.mean = self.processor.image_mean
|
249 |
+
self.std = self.processor.image_std
|
250 |
+
self.image_transform_train = TransformCXR(image_size=image_size, mean=self.mean, std=self.std, training=True)
|
251 |
+
self.image_transform_train_no_shift = TransformCXR(
|
252 |
+
image_size=image_size, mean=self.mean, std=self.std, allow_shift=False, training=True
|
253 |
+
)
|
254 |
+
self.image_transform_val = TransformCXR(image_size=image_size, mean=self.mean, std=self.std, training=False)
|
255 |
+
self.image_transform = transforms.Compose([
|
256 |
+
transforms.Resize(
|
257 |
+
(image_size, image_size),
|
258 |
+
interpolation=InterpolationMode.BICUBIC
|
259 |
+
),
|
260 |
+
transforms.ToTensor(),
|
261 |
+
transforms.Normalize(mean=self.mean, std=self.std),
|
262 |
+
])
|
263 |
+
|
264 |
+
# MLP
|
265 |
+
self.pos_embed = nn.Parameter(
|
266 |
+
torch.from_numpy(get_2d_sincos_pos_embed(width, self.grid_size[0])).float()
|
267 |
+
).requires_grad_(False)
|
268 |
+
self.attn_pool = nn.Sequential(
|
269 |
+
nn.Linear(width, output_dim * 4, bias=True),
|
270 |
+
ACT2FN["gelu"],
|
271 |
+
nn.Linear(output_dim * 4, output_dim, bias=True)
|
272 |
+
)
|
273 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
274 |
+
self.ln_post = norm_layer(output_dim)
|
275 |
+
self.proj = nn.Parameter((output_dim ** -0.5) * torch.randn(output_dim, output_dim), requires_grad=True)
|
276 |
+
|
277 |
+
def forward_resampler(self, x):
|
278 |
+
pos_embed = get_abs_pos(self.pos_embed, x.size(1))
|
279 |
+
x = x + pos_embed.unsqueeze(0)
|
280 |
+
x = self.attn_pool(x)
|
281 |
+
x = self.ln_post(x)
|
282 |
+
x = x @ self.proj
|
283 |
+
return x
|
284 |
+
|
285 |
+
def forward(self, x: torch.Tensor):
|
286 |
+
# get feature
|
287 |
+
x = self.model(x, output_hidden_states=True).hidden_states[-1]
|
288 |
+
|
289 |
+
# resampler
|
290 |
+
x = self.forward_resampler(x)
|
291 |
+
return x
|
292 |
+
|
293 |
+
def load_image(self, image_path, training):
|
294 |
+
if image_path.startswith("http://") or image_path.startswith("https://"):
|
295 |
+
image = Image.open(requests.get(image_path, stream=True).raw)
|
296 |
+
else:
|
297 |
+
image = Image.open(image_path)
|
298 |
+
|
299 |
+
image = image.convert("RGB")
|
300 |
+
|
301 |
+
no_shift = any([keyword in image_path for keyword in ["vindr", "candid", "siim", "object-cxr", "ms-cxr"]])
|
302 |
+
try:
|
303 |
+
if training or self.training:
|
304 |
+
if no_shift:
|
305 |
+
image_tensor = self.image_transform_train_no_shift(image)
|
306 |
+
else:
|
307 |
+
image_tensor = self.image_transform_train(image)
|
308 |
+
else:
|
309 |
+
image_tensor = self.image_transform_val(image)
|
310 |
+
except:
|
311 |
+
image_tensor = self.image_transform(image)
|
312 |
+
return image_tensor
|
313 |
+
|
314 |
+
def encode(self, image_paths: List[str], training):
|
315 |
+
images = []
|
316 |
+
for image_path in image_paths:
|
317 |
+
image = self.load_image(image_path, training)
|
318 |
+
images.append(image)
|
319 |
+
images = torch.stack(images, dim=0)
|
320 |
+
images = images.to(dtype=next(self.parameters()).dtype, device=next(self.parameters()).device)
|
321 |
+
outputs = self.forward(images)
|
322 |
+
return outputs
|
tokenization_chexagent.py
ADDED
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from functools import lru_cache
|
3 |
+
from typing import TYPE_CHECKING
|
4 |
+
|
5 |
+
import regex as re
|
6 |
+
from transformers.tokenization_utils_base import TextInput
|
7 |
+
from transformers.utils import is_tf_available, is_torch_available, to_py_obj
|
8 |
+
|
9 |
+
if TYPE_CHECKING:
|
10 |
+
if is_torch_available():
|
11 |
+
import torch
|
12 |
+
if is_tf_available():
|
13 |
+
import tensorflow as tf
|
14 |
+
|
15 |
+
import os
|
16 |
+
import random
|
17 |
+
from typing import Dict, List, Tuple, Union, Any, Callable, Optional
|
18 |
+
|
19 |
+
import matplotlib as mpl
|
20 |
+
import matplotlib.colors as mcolors
|
21 |
+
import matplotlib.colors as mplc
|
22 |
+
import matplotlib.figure as mplfigure
|
23 |
+
import numpy as np
|
24 |
+
import requests
|
25 |
+
import torch
|
26 |
+
from PIL import Image
|
27 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
28 |
+
from transformers import PreTrainedTokenizer, AddedToken
|
29 |
+
from transformers.utils import logging
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
VOCAB_FILES_NAMES = {
|
34 |
+
"vocab_file": "vocab.json",
|
35 |
+
"merges_file": "merges.txt",
|
36 |
+
}
|
37 |
+
|
38 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
39 |
+
"vocab_file": {
|
40 |
+
"Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json",
|
41 |
+
},
|
42 |
+
"merges_file": {
|
43 |
+
"Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt",
|
44 |
+
},
|
45 |
+
}
|
46 |
+
|
47 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
48 |
+
"Salesforce/codegen-350M-mono": 2048,
|
49 |
+
}
|
50 |
+
|
51 |
+
IMG_TOKEN_SPAN = 1024
|
52 |
+
|
53 |
+
DEFAULT_CHAT_TEMPLATE = "{% for message in messages %}\n{% if message['from'] == 'human' %}\n{{ '<|user|>\n' + message['value'] + eos_token }}\n{% elif message['from'] == 'system' %}\n{{ '<|system|>\n' + message['value'] + eos_token }}\n{% elif message['from'] == 'gpt' %}\n{{ '<|assistant|>\n' + message['value'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}"
|
54 |
+
|
55 |
+
|
56 |
+
@lru_cache()
|
57 |
+
def bytes_to_unicode():
|
58 |
+
"""
|
59 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
60 |
+
characters the bpe code barfs on.
|
61 |
+
|
62 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
63 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
64 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
65 |
+
tables between utf-8 bytes and unicode strings.
|
66 |
+
"""
|
67 |
+
bs = (
|
68 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(
|
69 |
+
range(ord("®"), ord("ÿ") + 1))
|
70 |
+
)
|
71 |
+
cs = bs[:]
|
72 |
+
n = 0
|
73 |
+
for b in range(2 ** 8):
|
74 |
+
if b not in bs:
|
75 |
+
bs.append(b)
|
76 |
+
cs.append(2 ** 8 + n)
|
77 |
+
n += 1
|
78 |
+
cs = [chr(n) for n in cs]
|
79 |
+
return dict(zip(bs, cs))
|
80 |
+
|
81 |
+
|
82 |
+
def get_pairs(word):
|
83 |
+
"""
|
84 |
+
Return set of symbol pairs in a word.
|
85 |
+
|
86 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
87 |
+
"""
|
88 |
+
pairs = set()
|
89 |
+
prev_char = word[0]
|
90 |
+
for char in word[1:]:
|
91 |
+
pairs.add((prev_char, char))
|
92 |
+
prev_char = char
|
93 |
+
return pairs
|
94 |
+
|
95 |
+
|
96 |
+
def _list_find(
|
97 |
+
input_list: List[Any],
|
98 |
+
candidates: Tuple[Any],
|
99 |
+
start: int = 0,
|
100 |
+
):
|
101 |
+
for i in range(start, len(input_list)):
|
102 |
+
if input_list[i] in candidates:
|
103 |
+
return i
|
104 |
+
return -1
|
105 |
+
|
106 |
+
|
107 |
+
def _replace_closed_tag(
|
108 |
+
input_tokens: List[Any],
|
109 |
+
start_tags: Union[Any, Tuple[Any]],
|
110 |
+
end_tags: Union[Any, Tuple[Any]],
|
111 |
+
inclusive_replace_func: Callable,
|
112 |
+
exclusive_replace_func: Callable = lambda x: x,
|
113 |
+
):
|
114 |
+
if isinstance(start_tags, (str, int)):
|
115 |
+
start_tags = (start_tags,)
|
116 |
+
if isinstance(end_tags, (str, int)):
|
117 |
+
end_tags = (end_tags,)
|
118 |
+
assert len(start_tags) == len(end_tags)
|
119 |
+
|
120 |
+
output_tokens = []
|
121 |
+
end = 0
|
122 |
+
while True:
|
123 |
+
start = _list_find(input_tokens, start_tags, end)
|
124 |
+
if start == -1:
|
125 |
+
break
|
126 |
+
output_tokens.extend(exclusive_replace_func(input_tokens[end: start]))
|
127 |
+
tag_idx = start_tags.index(input_tokens[start])
|
128 |
+
end = _list_find(input_tokens, (end_tags[tag_idx],), start)
|
129 |
+
if end == -1:
|
130 |
+
raise ValueError("Unclosed image token")
|
131 |
+
output_tokens.extend(inclusive_replace_func(input_tokens[start: end + 1]))
|
132 |
+
end += 1
|
133 |
+
output_tokens.extend(exclusive_replace_func(input_tokens[end:]))
|
134 |
+
return output_tokens
|
135 |
+
|
136 |
+
|
137 |
+
class CheXagentTokenizer(PreTrainedTokenizer):
|
138 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
139 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
140 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
141 |
+
model_input_names = ["input_ids", "attention_mask"]
|
142 |
+
|
143 |
+
def __init__(
|
144 |
+
self,
|
145 |
+
vocab_file,
|
146 |
+
merges_file,
|
147 |
+
errors="replace",
|
148 |
+
unk_token="<|endoftext|>",
|
149 |
+
bos_token="<|endoftext|>",
|
150 |
+
eos_token="<|endoftext|>",
|
151 |
+
pad_token=None,
|
152 |
+
add_prefix_space=False,
|
153 |
+
add_bos_token=False,
|
154 |
+
image_start_tag='<|img|>',
|
155 |
+
image_end_tag='<|/img|>',
|
156 |
+
image_pad_tag='<|imgpad|>',
|
157 |
+
ref_start_tag='<|ref|>',
|
158 |
+
ref_end_tag='<|/ref|>',
|
159 |
+
box_start_tag='<|box|>',
|
160 |
+
box_end_tag='<|/box|>',
|
161 |
+
quad_start_tag='<|quad|>',
|
162 |
+
quad_end_tag='<|/quad|>',
|
163 |
+
**kwargs,
|
164 |
+
):
|
165 |
+
bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
|
166 |
+
eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
|
167 |
+
unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
|
168 |
+
pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
|
169 |
+
self.add_bos_token = add_bos_token
|
170 |
+
|
171 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
172 |
+
self.encoder = json.load(vocab_handle)
|
173 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
174 |
+
self.errors = errors # how to handle errors in decoding
|
175 |
+
self.byte_encoder = bytes_to_unicode()
|
176 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
177 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
178 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
179 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
180 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
181 |
+
self.cache = {}
|
182 |
+
self.add_prefix_space = add_prefix_space
|
183 |
+
|
184 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
185 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
186 |
+
super().__init__(
|
187 |
+
errors=errors,
|
188 |
+
unk_token=unk_token,
|
189 |
+
bos_token=bos_token,
|
190 |
+
eos_token=eos_token,
|
191 |
+
pad_token=pad_token,
|
192 |
+
add_prefix_space=add_prefix_space,
|
193 |
+
add_bos_token=add_bos_token,
|
194 |
+
**kwargs,
|
195 |
+
)
|
196 |
+
|
197 |
+
self.image_start_tag = image_start_tag
|
198 |
+
self.image_end_tag = image_end_tag
|
199 |
+
self.image_pad_tag = image_pad_tag
|
200 |
+
self.ref_start_tag = ref_start_tag
|
201 |
+
self.ref_end_tag = ref_end_tag
|
202 |
+
self.box_start_tag = box_start_tag
|
203 |
+
self.box_end_tag = box_end_tag
|
204 |
+
self.quad_start_tag = quad_start_tag
|
205 |
+
self.quad_end_tag = quad_end_tag
|
206 |
+
self.IMAGE_ST = (
|
207 |
+
image_start_tag, image_end_tag, image_pad_tag,
|
208 |
+
ref_start_tag, ref_end_tag, box_start_tag, box_end_tag,
|
209 |
+
quad_start_tag, quad_end_tag,
|
210 |
+
)
|
211 |
+
for special_token in self.IMAGE_ST:
|
212 |
+
if special_token not in self.get_vocab():
|
213 |
+
self.add_special_tokens({"additional_special_tokens": [special_token]})
|
214 |
+
for coordinate in range(10):
|
215 |
+
if f"<{coordinate}>" not in self.get_vocab():
|
216 |
+
self.add_special_tokens({"additional_special_tokens": [f"<|coord_{coordinate}|>"]})
|
217 |
+
if len(self) % 64 != 0:
|
218 |
+
for extra in range(((len(self) // 64) + 1) * 64 - len(self)):
|
219 |
+
if f"<extra_{extra}>" not in self.get_vocab():
|
220 |
+
self.add_special_tokens({"additional_special_tokens": [f"<|extra_{extra}|>"]})
|
221 |
+
self.img_start_id = self.convert_tokens_to_ids(self.image_start_tag)
|
222 |
+
self.img_end_id = self.convert_tokens_to_ids(self.image_end_tag)
|
223 |
+
self.img_pad_id = self.convert_tokens_to_ids(self.image_pad_tag)
|
224 |
+
self.ref_start_id = self.convert_tokens_to_ids(self.ref_start_tag)
|
225 |
+
self.ref_end_id = self.convert_tokens_to_ids(self.ref_end_tag)
|
226 |
+
self.box_start_id = self.convert_tokens_to_ids(self.box_start_tag)
|
227 |
+
self.box_end_id = self.convert_tokens_to_ids(self.box_end_tag)
|
228 |
+
self.quad_start_id = self.convert_tokens_to_ids(self.quad_start_tag)
|
229 |
+
self.quad_end_id = self.convert_tokens_to_ids(self.quad_end_tag)
|
230 |
+
self.chat_template = DEFAULT_CHAT_TEMPLATE
|
231 |
+
|
232 |
+
@property
|
233 |
+
def vocab_size(self):
|
234 |
+
return len(self.encoder)
|
235 |
+
|
236 |
+
def get_vocab(self):
|
237 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
238 |
+
|
239 |
+
def bpe(self, token):
|
240 |
+
if token in self.cache:
|
241 |
+
return self.cache[token]
|
242 |
+
word = tuple(token)
|
243 |
+
pairs = get_pairs(word)
|
244 |
+
|
245 |
+
if not pairs:
|
246 |
+
return token
|
247 |
+
|
248 |
+
while True:
|
249 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
250 |
+
if bigram not in self.bpe_ranks:
|
251 |
+
break
|
252 |
+
first, second = bigram
|
253 |
+
new_word = []
|
254 |
+
i = 0
|
255 |
+
while i < len(word):
|
256 |
+
try:
|
257 |
+
j = word.index(first, i)
|
258 |
+
except ValueError:
|
259 |
+
new_word.extend(word[i:])
|
260 |
+
break
|
261 |
+
else:
|
262 |
+
new_word.extend(word[i:j])
|
263 |
+
i = j
|
264 |
+
|
265 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
266 |
+
new_word.append(first + second)
|
267 |
+
i += 2
|
268 |
+
else:
|
269 |
+
new_word.append(word[i])
|
270 |
+
i += 1
|
271 |
+
new_word = tuple(new_word)
|
272 |
+
word = new_word
|
273 |
+
if len(word) == 1:
|
274 |
+
break
|
275 |
+
else:
|
276 |
+
pairs = get_pairs(word)
|
277 |
+
word = " ".join(word)
|
278 |
+
self.cache[token] = word
|
279 |
+
return word
|
280 |
+
|
281 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
282 |
+
if self.add_bos_token:
|
283 |
+
bos_token_ids = [self.bos_token_id]
|
284 |
+
else:
|
285 |
+
bos_token_ids = []
|
286 |
+
|
287 |
+
output = bos_token_ids + token_ids_0
|
288 |
+
|
289 |
+
if token_ids_1 is None:
|
290 |
+
return output
|
291 |
+
|
292 |
+
return output + bos_token_ids + token_ids_1
|
293 |
+
|
294 |
+
def tokenize(self, text: TextInput, **kwargs) -> List[str]:
|
295 |
+
def _encode_imgurl(img_tokens):
|
296 |
+
assert img_tokens[0] == self.image_start_tag and img_tokens[-1] == self.image_end_tag
|
297 |
+
img_tokens = img_tokens[1:-1]
|
298 |
+
img_url = ''.join(img_tokens)
|
299 |
+
out_img_tokens = list(img_url)
|
300 |
+
if len(out_img_tokens) > IMG_TOKEN_SPAN:
|
301 |
+
raise ValueError("The content in {}..{} is too long".format(self.image_start_tag, self.image_end_tag))
|
302 |
+
out_img_tokens.extend([self.image_pad_tag] * (IMG_TOKEN_SPAN - len(out_img_tokens)))
|
303 |
+
out_img_tokens = [self.image_start_tag] + out_img_tokens + [self.image_end_tag]
|
304 |
+
return out_img_tokens
|
305 |
+
|
306 |
+
tokens = super().tokenize(text, **kwargs)
|
307 |
+
tokens = _replace_closed_tag(tokens, self.image_start_tag, self.image_end_tag, _encode_imgurl)
|
308 |
+
return tokens
|
309 |
+
|
310 |
+
def _tokenize(self, text):
|
311 |
+
"""Tokenize a string."""
|
312 |
+
|
313 |
+
bpe_tokens = []
|
314 |
+
for token in re.findall(self.pat, text):
|
315 |
+
token = "".join(
|
316 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
317 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
318 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
319 |
+
return bpe_tokens
|
320 |
+
|
321 |
+
def _convert_token_to_id(self, token):
|
322 |
+
"""Converts a token (str) in an id using the vocab."""
|
323 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
324 |
+
|
325 |
+
def _convert_id_to_token(self, index):
|
326 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
327 |
+
return self.decoder.get(index)
|
328 |
+
|
329 |
+
def convert_tokens_to_string(self, tokens):
|
330 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
331 |
+
text = "".join(tokens)
|
332 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
333 |
+
return text
|
334 |
+
|
335 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
336 |
+
if not os.path.isdir(save_directory):
|
337 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
338 |
+
return
|
339 |
+
vocab_file = os.path.join(
|
340 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
341 |
+
)
|
342 |
+
merge_file = os.path.join(
|
343 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
344 |
+
)
|
345 |
+
|
346 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
347 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
348 |
+
|
349 |
+
index = 0
|
350 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
351 |
+
writer.write("#version: 0.2\n")
|
352 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
353 |
+
if index != token_index:
|
354 |
+
logger.warning(
|
355 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
356 |
+
" Please check that the tokenizer is not corrupted!"
|
357 |
+
)
|
358 |
+
index = token_index
|
359 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
360 |
+
index += 1
|
361 |
+
|
362 |
+
return vocab_file, merge_file
|
363 |
+
|
364 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
365 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
366 |
+
if is_split_into_words or add_prefix_space:
|
367 |
+
text = " " + text
|
368 |
+
return (text, kwargs)
|
369 |
+
|
370 |
+
def decode(
|
371 |
+
self,
|
372 |
+
token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
|
373 |
+
skip_special_tokens: bool = False,
|
374 |
+
clean_up_tokenization_spaces: bool = None,
|
375 |
+
truncate_before_pattern: Optional[List[str]] = None,
|
376 |
+
**kwargs,
|
377 |
+
) -> str:
|
378 |
+
"""
|
379 |
+
Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
|
380 |
+
tokens and clean up tokenization spaces.
|
381 |
+
|
382 |
+
Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
|
383 |
+
|
384 |
+
Args:
|
385 |
+
token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
|
386 |
+
List of tokenized input ids. Can be obtained using the `__call__` method.
|
387 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
388 |
+
Whether or not to remove special tokens in the decoding.
|
389 |
+
clean_up_tokenization_spaces (`bool`, *optional*):
|
390 |
+
Whether or not to clean up the tokenization spaces. If `None`, will default to
|
391 |
+
`self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
|
392 |
+
truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
|
393 |
+
A list of regular expression strings that will be used to truncate the returned string. This can be
|
394 |
+
used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
|
395 |
+
of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
|
396 |
+
kwargs (additional keyword arguments, *optional*):
|
397 |
+
Will be passed to the underlying model specific decode method.
|
398 |
+
|
399 |
+
Returns:
|
400 |
+
`str`: The decoded sentence.
|
401 |
+
"""
|
402 |
+
|
403 |
+
token_ids = to_py_obj(token_ids)
|
404 |
+
|
405 |
+
decoded_text = self._decode(
|
406 |
+
token_ids=token_ids,
|
407 |
+
skip_special_tokens=skip_special_tokens,
|
408 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
409 |
+
**kwargs,
|
410 |
+
)
|
411 |
+
|
412 |
+
if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
|
413 |
+
decoded_text = self.truncate(decoded_text, truncate_before_pattern)
|
414 |
+
|
415 |
+
return decoded_text
|
416 |
+
|
417 |
+
def _decode(
|
418 |
+
self,
|
419 |
+
token_ids: List[int],
|
420 |
+
skip_special_tokens: bool = False,
|
421 |
+
clean_up_tokenization_spaces: bool = None,
|
422 |
+
spaces_between_special_tokens: bool = True,
|
423 |
+
**kwargs,
|
424 |
+
) -> str:
|
425 |
+
|
426 |
+
def _decode_imgurl(img_token_ids):
|
427 |
+
assert img_token_ids[0] == self.img_start_id and img_token_ids[-1] == self.img_end_id
|
428 |
+
img_token_ids = img_token_ids[1:-1]
|
429 |
+
img_token_ids = img_token_ids[: img_token_ids.index(self.img_pad_id)]
|
430 |
+
return [self.img_start_id] + img_token_ids + [self.img_end_id]
|
431 |
+
|
432 |
+
token_ids = _replace_closed_tag(token_ids, self.img_start_id, self.img_end_id, _decode_imgurl)
|
433 |
+
|
434 |
+
return super()._decode(
|
435 |
+
token_ids, skip_special_tokens, clean_up_tokenization_spaces, spaces_between_special_tokens, **kwargs
|
436 |
+
)
|
437 |
+
|
438 |
+
def truncate(self, completion, truncate_before_pattern):
|
439 |
+
def find_re(string, pattern, start_pos):
|
440 |
+
m = pattern.search(string, start_pos)
|
441 |
+
return m.start() if m else -1
|
442 |
+
|
443 |
+
terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
|
444 |
+
|
445 |
+
prints = list(re.finditer("^print", completion, re.MULTILINE))
|
446 |
+
|
447 |
+
if len(prints) > 1:
|
448 |
+
completion = completion[: prints[1].start()]
|
449 |
+
|
450 |
+
defs = list(re.finditer("^def", completion, re.MULTILINE))
|
451 |
+
|
452 |
+
if len(defs) > 1:
|
453 |
+
completion = completion[: defs[1].start()]
|
454 |
+
|
455 |
+
start_pos = 0
|
456 |
+
|
457 |
+
terminals_pos = [
|
458 |
+
pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
|
459 |
+
]
|
460 |
+
|
461 |
+
if len(terminals_pos) > 0:
|
462 |
+
return completion[: min(terminals_pos)]
|
463 |
+
else:
|
464 |
+
return completion
|
465 |
+
|
466 |
+
def from_list_format(self, list_format: List[Dict]):
|
467 |
+
text = ''
|
468 |
+
num_images = 0
|
469 |
+
for ele in list_format:
|
470 |
+
if 'image' in ele:
|
471 |
+
num_images += 1
|
472 |
+
text += f'Picture {num_images}:'
|
473 |
+
text += self.image_start_tag + ele['image'] + self.image_end_tag
|
474 |
+
text += '\n'
|
475 |
+
elif 'text' in ele:
|
476 |
+
text += ele['text']
|
477 |
+
elif 'box' in ele:
|
478 |
+
if 'ref' in ele:
|
479 |
+
text += self.ref_start_tag + ele['ref'] + self.ref_end_tag
|
480 |
+
for box in ele['box']:
|
481 |
+
text += self.box_start_tag + '(%d,%d),(%d,%d)' % (box[0], box[1], box[2], box[3]) + self.box_end_tag
|
482 |
+
else:
|
483 |
+
raise ValueError("Unsupport element: " + str(ele))
|
484 |
+
return text
|
485 |
+
|
486 |
+
def to_list_format(self, text: str):
|
487 |
+
token_ids = self.encode(text)
|
488 |
+
|
489 |
+
def _encode_vl_info(tokens):
|
490 |
+
if len(tokens) == 0:
|
491 |
+
return []
|
492 |
+
if tokens[0] == self.img_start_id and tokens[-1] == self.img_end_id:
|
493 |
+
key = 'image'
|
494 |
+
elif tokens[0] == self.ref_start_id and tokens[-1] == self.ref_end_id:
|
495 |
+
key = 'ref'
|
496 |
+
elif tokens[0] == self.box_start_id and tokens[-1] == self.box_end_id:
|
497 |
+
key = 'box'
|
498 |
+
elif tokens[0] == self.quad_start_id and tokens[-1] == self.quad_end_id:
|
499 |
+
key = 'quad'
|
500 |
+
else:
|
501 |
+
val = self.decode(tokens)
|
502 |
+
return [{'text': val}]
|
503 |
+
tokens = [token for token in tokens[1:-1] if token != self.img_pad_id]
|
504 |
+
val = self.decode(tokens, skip_special_tokens=True)
|
505 |
+
return [{key: val}]
|
506 |
+
|
507 |
+
return _replace_closed_tag(
|
508 |
+
token_ids,
|
509 |
+
(self.img_start_id, self.ref_start_id, self.box_start_id, self.quad_start_id),
|
510 |
+
(self.img_end_id, self.ref_end_id, self.box_end_id, self.quad_end_id),
|
511 |
+
_encode_vl_info,
|
512 |
+
_encode_vl_info,
|
513 |
+
)
|
514 |
+
|
515 |
+
def _fetch_latest_picture(self, response, history):
|
516 |
+
if history is None:
|
517 |
+
history = []
|
518 |
+
_history = history + [(response, None)]
|
519 |
+
for q, r in _history[::-1]:
|
520 |
+
for ele in self.to_list_format(q)[::-1]:
|
521 |
+
if 'image' in ele:
|
522 |
+
return ele['image']
|
523 |
+
return None
|
524 |
+
|
525 |
+
def _fetch_all_box_with_ref(self, text):
|
526 |
+
list_format = self.to_list_format(text)
|
527 |
+
output = []
|
528 |
+
for i, ele in enumerate(list_format):
|
529 |
+
if 'box' in ele:
|
530 |
+
bbox = tuple(map(int, ele['box'].replace('(', '').replace(')', '').split(',')))
|
531 |
+
assert len(bbox) == 4
|
532 |
+
output.append({'box': bbox})
|
533 |
+
if i > 0 and 'ref' in list_format[i - 1]:
|
534 |
+
output[-1]['ref'] = list_format[i - 1]['ref'].strip()
|
535 |
+
return output
|
536 |
+
|
537 |
+
def draw_bbox_on_latest_picture(
|
538 |
+
self,
|
539 |
+
response,
|
540 |
+
history=None,
|
541 |
+
) -> Optional[Image.Image]:
|
542 |
+
image = self._fetch_latest_picture(response, history)
|
543 |
+
if image is None:
|
544 |
+
return None
|
545 |
+
if image.startswith("http://") or image.startswith("https://"):
|
546 |
+
image = Image.open(requests.get(image, stream=True).raw).convert("RGB")
|
547 |
+
h, w = image.height, image.width
|
548 |
+
else:
|
549 |
+
image = np.asarray(Image.open(image).convert("RGB"))
|
550 |
+
h, w = image.shape[0], image.shape[1]
|
551 |
+
visualizer = Visualizer(image)
|
552 |
+
|
553 |
+
boxes = self._fetch_all_box_with_ref(response)
|
554 |
+
if not boxes:
|
555 |
+
return None
|
556 |
+
color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()]) # init color
|
557 |
+
for box in boxes:
|
558 |
+
if 'ref' in box: # random new color for new refexps
|
559 |
+
color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()])
|
560 |
+
x1, y1, x2, y2 = box['box']
|
561 |
+
x1, y1, x2, y2 = (int(x1 / 1000 * w), int(y1 / 1000 * h), int(x2 / 1000 * w), int(y2 / 1000 * h))
|
562 |
+
visualizer.draw_box((x1, y1, x2, y2), alpha=1, edge_color=color)
|
563 |
+
if 'ref' in box:
|
564 |
+
visualizer.draw_text(box['ref'], (x1, y1), color=color, horizontal_alignment="left")
|
565 |
+
return visualizer.output
|
566 |
+
|
567 |
+
|
568 |
+
class VisImage:
|
569 |
+
def __init__(self, img, scale=1.0):
|
570 |
+
self.img = img
|
571 |
+
self.scale = scale
|
572 |
+
self.width, self.height = img.shape[1], img.shape[0]
|
573 |
+
self._setup_figure(img)
|
574 |
+
|
575 |
+
def _setup_figure(self, img):
|
576 |
+
fig = mplfigure.Figure(frameon=False)
|
577 |
+
self.dpi = fig.get_dpi()
|
578 |
+
# add a small 1e-2 to avoid precision lost due to matplotlib's truncation
|
579 |
+
# (https://github.com/matplotlib/matplotlib/issues/15363)
|
580 |
+
fig.set_size_inches(
|
581 |
+
(self.width * self.scale + 1e-2) / self.dpi,
|
582 |
+
(self.height * self.scale + 1e-2) / self.dpi,
|
583 |
+
)
|
584 |
+
self.canvas = FigureCanvasAgg(fig)
|
585 |
+
# self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
|
586 |
+
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
587 |
+
ax.axis("off")
|
588 |
+
self.fig = fig
|
589 |
+
self.ax = ax
|
590 |
+
self.reset_image(img)
|
591 |
+
|
592 |
+
def reset_image(self, img):
|
593 |
+
img = img.astype("uint8")
|
594 |
+
self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
|
595 |
+
|
596 |
+
def save(self, filepath):
|
597 |
+
self.fig.savefig(filepath)
|
598 |
+
|
599 |
+
def get_image(self):
|
600 |
+
canvas = self.canvas
|
601 |
+
s, (width, height) = canvas.print_to_buffer()
|
602 |
+
|
603 |
+
buffer = np.frombuffer(s, dtype="uint8")
|
604 |
+
|
605 |
+
img_rgba = buffer.reshape(height, width, 4)
|
606 |
+
rgb, alpha = np.split(img_rgba, [3], axis=2)
|
607 |
+
return rgb.astype("uint8")
|
608 |
+
|
609 |
+
|
610 |
+
class Visualizer:
|
611 |
+
def __init__(self, img_rgb, metadata=None, scale=1.0):
|
612 |
+
self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
|
613 |
+
self.output = VisImage(self.img, scale=scale)
|
614 |
+
self.cpu_device = torch.device("cpu")
|
615 |
+
|
616 |
+
# too small texts are useless, therefore clamp to 14
|
617 |
+
self._default_font_size = max(
|
618 |
+
np.sqrt(self.output.height * self.output.width) // 30, 15 // scale
|
619 |
+
)
|
620 |
+
|
621 |
+
def draw_text(
|
622 |
+
self,
|
623 |
+
text,
|
624 |
+
position,
|
625 |
+
*,
|
626 |
+
font_size=None,
|
627 |
+
color="g",
|
628 |
+
horizontal_alignment="center",
|
629 |
+
rotation=0,
|
630 |
+
):
|
631 |
+
if not font_size:
|
632 |
+
font_size = self._default_font_size
|
633 |
+
|
634 |
+
# since the text background is dark, we don't want the text to be dark
|
635 |
+
color = np.maximum(list(mplc.to_rgb(color)), 0.2)
|
636 |
+
color[np.argmax(color)] = max(0.8, np.max(color))
|
637 |
+
|
638 |
+
x, y = position
|
639 |
+
self.output.ax.text(
|
640 |
+
x,
|
641 |
+
y,
|
642 |
+
text,
|
643 |
+
size=font_size * self.output.scale,
|
644 |
+
bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
|
645 |
+
verticalalignment="top",
|
646 |
+
horizontalalignment=horizontal_alignment,
|
647 |
+
color=color,
|
648 |
+
zorder=10,
|
649 |
+
rotation=rotation,
|
650 |
+
)
|
651 |
+
return self.output
|
652 |
+
|
653 |
+
def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
|
654 |
+
x0, y0, x1, y1 = box_coord
|
655 |
+
width = x1 - x0
|
656 |
+
height = y1 - y0
|
657 |
+
|
658 |
+
linewidth = max(self._default_font_size / 4, 1)
|
659 |
+
|
660 |
+
self.output.ax.add_patch(
|
661 |
+
mpl.patches.Rectangle(
|
662 |
+
(x0, y0),
|
663 |
+
width,
|
664 |
+
height,
|
665 |
+
fill=False,
|
666 |
+
edgecolor=edge_color,
|
667 |
+
linewidth=linewidth * self.output.scale,
|
668 |
+
alpha=alpha,
|
669 |
+
linestyle=line_style,
|
670 |
+
)
|
671 |
+
)
|
672 |
+
return self.output
|
673 |
+
|
674 |
+
def get_output(self):
|
675 |
+
return self.output
|