Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
# limitations under the License.
""" GPTBigCode configuration"""

from enum import IntEnum

from ...configuration_utils import PretrainedConfig
from ...utils import logging

Expand All @@ -25,6 +27,19 @@
}


class InferenceRunnerType(IntEnum):
NO_RUNNER = 0
# Use the inference runner without cuda graphs.
BASE_RUNNER = 1
# Use cuda graphs in the inference runner. Leave out the attention which has a variable shape.
# This significantly lowers the cpu time and prevent a cpu bottleneck for smaller batches and models.
PARTIAL_GRAPH = 2
# Turn the whole model into a cuda graph. One graph for each sequence length.
# Note: only useful for small batches and models, graphs take some time to generate, flaky.
# Crashes with jit on A100 but seems to work without jit (PYTORCH_JIT=0) and on V100.
FULL_GRAPH = 3


class GPTBigCodeConfig(PretrainedConfig):
"""
This is the configuration class to store the configuration of a [`GPTBigCodeModel`]. It is used to instantiate a
Expand Down Expand Up @@ -119,6 +134,12 @@ def __init__(
attention_softmax_in_fp32=True,
scale_attention_softmax_in_fp32=True,
multi_query=True,
inference_runner=InferenceRunnerType.NO_RUNNER,
validate_runner_input=True,
pre_allocate_kv_cache=False,
max_sequence_length=None,
max_batch_size=None,
pad_key_length=True,
**kwargs,
):
self.vocab_size = vocab_size
Expand All @@ -142,4 +163,16 @@ def __init__(
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id

self.inference_runner = InferenceRunnerType(inference_runner)
# Set to False to disable input validation of safe inputs, for a small speedup.
self.validate_runner_input = validate_runner_input

self.pre_allocate_kv_cache = pre_allocate_kv_cache
# The max sequence length for the pre-allocated KV cache (`n_positions` if not provided).
self.max_sequence_length = max_sequence_length
# The max batch size for the pre-allocated KV cache, (deduce from input if not provided).
self.max_batch_size = max_batch_size
# Pad key length to a multiple of 8 (requires pre_allocate_kv_cache).
self.pad_key_length = pad_key_length

super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
14 changes: 7 additions & 7 deletions src/transformers/models/gpt_bigcode/inference_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from transformers import GPTBigCodeConfig
from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions
from transformers.models.gpt_bigcode.configuration_gpt_bigcode import AttentionType, InferenceRunnerType
from transformers.models.gpt_bigcode.configuration_gpt_bigcode import InferenceRunnerType
from transformers.models.gpt_bigcode.modeling_gpt_bigcode import GPTBigCodeBlock, masked_softmax, upcast_masked_softmax


Expand All @@ -25,7 +25,7 @@ def __init__(self, config: GPTBigCodeConfig, model):
self.pad_key_length = 8 if config.pad_key_length else 1

# TODO: Support other attention types?
assert model.attention_type == AttentionType.MULTI_QUERY_1
assert model.multi_query

self.max_sequence_length = config.max_sequence_length or config.n_positions

Expand Down Expand Up @@ -71,7 +71,7 @@ def _allocate(self, batch_size, device, dtype):
for block in self.model.h:
block.attn.freeze_kv_cache()
kv_cache = block.attn.get_kv_cache(self.batch_size, self.max_sequence_length, self.device, self.dtype)
if attn.is_mqa:
if attn.multi_query:
kv_cache = kv_cache.unsqueeze(1)
kv_caches.append(kv_cache)

Expand Down Expand Up @@ -122,7 +122,7 @@ def _allocate(self, batch_size, device, dtype):
self.kv_attn = self.c_attn[:, attn.embed_dim :]

keys, values = zip(*(kv_cache.split((attn.head_dim, attn.head_dim), dim=-1) for kv_cache in kv_caches))
head_slice = 0 if attn.is_mqa else slice(None)
head_slice = 0 if attn.multi_query else slice(None)

self.padded_keys = [
[key[:, head_slice, :key_length, :].transpose(-1, -2) for key in keys] for key_length in padded_key_lengths
Expand Down Expand Up @@ -285,9 +285,9 @@ def _forward(self, key_length):

def forward(
self,
input_ids: torch.LongTensor,
attention_mask: torch.FloatTensor,
position_ids: torch.LongTensor,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
position_ids: torch.Tensor,
past_key_values: Union[List[torch.Tensor], int],
) -> BaseModelOutputWithPastAndCrossAttentions:
batch_size, query_length = input_ids.shape
Expand Down
114 changes: 109 additions & 5 deletions src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
add_start_docstrings_to_model_forward,
logging,
)
from .configuration_gpt_bigcode import GPTBigCodeConfig
from .configuration_gpt_bigcode import GPTBigCodeConfig, InferenceRunnerType


logger = logging.get_logger(__name__)
Expand Down Expand Up @@ -105,6 +105,14 @@ def __init__(self, config, is_cross_attention=False, layer_idx=None):
config.scale_attention_softmax_in_fp32 and config.attention_softmax_in_fp32
)

# KV caching and padding
self.kv_cache = None
self.kv_cache_max_batch_size = config.max_batch_size or 0
self.kv_cache_max_sequence_length = config.max_sequence_length or config.n_positions
self.pre_allocate_kv_cache = config.pre_allocate_kv_cache
self.pad_key_length = config.pad_key_length and config.pre_allocate_kv_cache
self._frozen_kv_cache = False

if self.is_cross_attention:
if self.multi_query:
raise NotImplementedError("Multi-Query Attention not supported for cross_attention")
Expand Down Expand Up @@ -202,6 +210,41 @@ def _attn(self, query, key, value, attention_mask=None, head_mask=None):

return attn_output, attn_weights

def freeze_kv_cache(self, enable=True):
if self.kv_cache is None:
raise RuntimeError("KV cache not found.")
# Prevent re-allocation of the KV cache.
self._frozen_kv_cache = enable

def get_kv_cache(self, batch_size, sequence_length, device, dtype, allocate=True):
if (
self.kv_cache is None
or self.kv_cache.dtype != dtype
or self.kv_cache.device != device
or batch_size > self.kv_cache_max_batch_size
or sequence_length > self.kv_cache_max_sequence_length
):
if self._frozen_kv_cache or not allocate:
if self.kv_cache is None:
raise RuntimeError("KV cache not found.")
else:
raise RuntimeError(
f"Invalid KV cache: "
f"existing = {(self.kv_cache.dtype,self.kv_cache.device,self.kv_cache_max_batch_size,self.kv_cache_max_sequence_length)}, "
f"requested = {(dtype,device,batch_size,sequence_length)}"
)
# Free memory first.
self.kv_cache = None
self.kv_cache_max_sequence_length = max(sequence_length, self.kv_cache_max_sequence_length)
self.kv_cache_max_batch_size = max(batch_size, self.kv_cache_max_batch_size)
kv_cache_size = 2 * self.kv_cache_max_batch_size * self.kv_cache_max_sequence_length * self.kv_dim
self.kv_cache = torch.empty([kv_cache_size], device=device, dtype=dtype)
# This view ensures the cache is contiguous for all batch sizes.
kv_cache = self.kv_cache[: 2 * batch_size * self.kv_cache_max_sequence_length * self.kv_dim].view(
batch_size, self.kv_heads, self.kv_cache_max_sequence_length, 2 * self.head_dim
)
return kv_cache[:, 0, :sequence_length, :] if self.multi_query else kv_cache[:, :, :sequence_length, :]

def forward(
self,
hidden_states: torch.Tensor,
Expand Down Expand Up @@ -239,9 +282,27 @@ def forward(
.split((self.head_dim, 2 * self.head_dim), dim=3)
)

if layer_past is not None:
key_value = torch.cat((layer_past, key_value), dim=-2)
present = key_value if use_cache else None
present = None

if self.pre_allocate_kv_cache:
if use_cache or layer_past is not None:
last_key_length = layer_past or 0
batch_size = key_value.size(0)
key_length = last_key_length + key_value.size(-2)
padded_key_length = key_length + -key_length % (8 if self.pad_key_length else 1)
kv_cache = self.get_kv_cache(
batch_size, padded_key_length, key_value.device, key_value.dtype, allocate=last_key_length == 0
)
if self.multi_query:
kv_cache[:, last_key_length:key_length, :].copy_(key_value)
key_value = kv_cache
if use_cache:
present = key_length
else:
if layer_past is not None:
key_value = torch.cat((layer_past, key_value), dim=-2)
if use_cache:
present = key_value

key, value = key_value.split((self.head_dim, self.head_dim), dim=-1)

Expand Down Expand Up @@ -513,6 +574,17 @@ def __init__(self, config):
self.h = nn.ModuleList([GPTBigCodeBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)

self.pre_allocate_kv_cache = config.pre_allocate_kv_cache
self.pad_key_length = config.pad_key_length and self.pre_allocate_kv_cache
self.inference_runner_type = InferenceRunnerType(config.inference_runner)

if self.inference_runner_type == InferenceRunnerType.NO_RUNNER:
self.inference_runner = None
else:
from .inference_runner import GPTBigCodeInferenceRunner

self.inference_runner = GPTBigCodeInferenceRunner(config, self)

max_positions = config.max_position_embeddings
self.register_buffer(
"bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)), persistent=False
Expand Down Expand Up @@ -551,6 +623,31 @@ def forward(
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
if self.inference_runner is not None and past_key_values is not None:
if self.config.validate_runner_input:
assert input_ids is not None
assert past_key_values is not None
assert attention_mask is not None
assert token_type_ids is None
assert position_ids is not None
assert head_mask is None
assert inputs_embeds is None
assert encoder_hidden_states is None
assert encoder_attention_mask is None
use_cache = use_cache if use_cache is not None else self.config.use_cache
assert use_cache is True
output_attentions = (
output_attentions if output_attentions is not None else self.config.output_attentions
)
assert output_attentions is False
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
assert output_hidden_states is False
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
assert return_dict is True
return self.inference_runner.forward(input_ids, attention_mask, position_ids, past_key_values)

output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
Expand Down Expand Up @@ -583,8 +680,10 @@ def forward(
if past_key_values is None:
past_length = 0
past_key_values = tuple([None] * len(self.h))
elif self.pre_allocate_kv_cache:
past_length = past_key_values[0]
else:
past_length = past_key_values[0][0].size(-2)
past_length = past_key_values[0].size(-2)

if attention_mask is not None and len(attention_mask.shape) == 2 and position_ids is None:
# create position_ids on the fly for batch generation
Expand All @@ -610,6 +709,11 @@ def forward(
# MHA models: (batch_size, n_heads, query_length, key_length)
attention_mask = self_attention_mask.unsqueeze(2 if self.multi_query else 1)

if self.pad_key_length:
pad = -key_length % 8
if pad > 0:
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad), mode="constant", value=False)

# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if (
Expand Down