Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
79 commits
Select commit Hold shift + click to select a range
31aad90
add: 2 variants of multi query implementation; printing some details
Aug 31, 2022
9c13b66
Unpin PyTorch
sgugger Nov 1, 2022
1ebb3f7
Release v4.24.0
sgugger Nov 1, 2022
0e654e0
Added onnx config whisper (#19525)
mht-sharma Nov 1, 2022
502d3b6
Remove pin temporarily to get tests
sgugger Nov 1, 2022
8f95346
Add ESMFold code sample (#20000)
Rocketknight1 Nov 1, 2022
94b3f54
Unpin PyTorch for the release
sgugger Nov 1, 2022
a367bc0
Merge tag 'v4.24.0' into mayank/multi_query
mayank31398 Dec 4, 2022
b7e2124
fix saving
mayank31398 Dec 5, 2022
5171b4f
Merge branch 'main' of github.com:bigcode-collaboration/transformers …
Jan 20, 2023
357ba81
added Raymond MQA variant
Jan 20, 2023
a96771f
chg: tensor vs fill acc to comments by Joel
Jan 23, 2023
14f2249
Style and fix
jlamypoirier Jan 23, 2023
4dc821c
cleanup
jlamypoirier Jan 23, 2023
129e8c9
cleanup
jlamypoirier Jan 23, 2023
303e1b8
cleanup
jlamypoirier Jan 23, 2023
d0b58e9
cleanup
jlamypoirier Jan 23, 2023
a1e9182
Fixes and cleanup
jlamypoirier Jan 23, 2023
a57ca7a
Fixes and cleanup
jlamypoirier Jan 23, 2023
e152e94
Fixes and merge implementations
jlamypoirier Jan 23, 2023
2e32a95
Fixes and improvements
jlamypoirier Jan 24, 2023
93b42d2
simplify and fix
jlamypoirier Jan 24, 2023
82b11df
Fixes, optimization and comments
jlamypoirier Jan 25, 2023
98319da
Best GeLU]
jlamypoirier Jan 26, 2023
d81e46f
simpler gelu
jlamypoirier Jan 27, 2023
33ae645
Merge branch 'main' into joel-mqa
jlamypoirier Feb 7, 2023
2f299a2
Merge branch 'gpt2_bigcode' into joel-mqa
jlamypoirier Feb 7, 2023
a1d7a95
Move code
jlamypoirier Feb 7, 2023
138fefb
fix
jlamypoirier Feb 7, 2023
732e447
Merge branch 'gpt2_bigcode' into joel-mqa
jlamypoirier Feb 7, 2023
52a6d97
fix
jlamypoirier Feb 7, 2023
b4c9cf4
fix
jlamypoirier Feb 7, 2023
3dd5a5b
gelu
jlamypoirier Feb 7, 2023
2c13d08
Add changes from fast inferences
jlamypoirier Feb 7, 2023
e8a024c
Merge branch 'gpt2_bigcode' into joel-mqa
jlamypoirier Feb 7, 2023
37e4611
Inference runner
jlamypoirier Feb 7, 2023
17f229c
Merge branch 'main' into fast_inference
jlamypoirier Feb 8, 2023
a645112
Redo upcast, scaling and masking
jlamypoirier Feb 9, 2023
4b80a12
fused kernels
jlamypoirier Feb 10, 2023
9023ea6
fixes
jlamypoirier Feb 10, 2023
8981ec5
Merge branch 'fp32_softmax' into fast_inference
jlamypoirier Feb 10, 2023
564cbbe
fixes and full cuda graphs
jlamypoirier Feb 11, 2023
dcb5176
Merge branch 'main' into fp32_softmax
jlamypoirier Feb 14, 2023
d4c500e
Merge branch 'fp32_softmax' into fast_inference
jlamypoirier Feb 14, 2023
ababf09
fixes
jlamypoirier Feb 15, 2023
8c8a6bc
fix
jlamypoirier Feb 15, 2023
82c8216
stye
jlamypoirier Feb 15, 2023
39030da
Merge branch 'main' into fast_inference
jlamypoirier Feb 15, 2023
6f2da6f
Simplify runner config, conv1d factory kwargs
jlamypoirier Feb 16, 2023
15f94f5
Fix jit in inference runner, use contiguous buffers
jlamypoirier Feb 17, 2023
4ac98f2
linear layers
jlamypoirier Feb 21, 2023
3de50c1
cleanup
jlamypoirier Feb 21, 2023
ff6d137
More optimizations and fixes
jlamypoirier Feb 22, 2023
7c258b8
cleanup
jlamypoirier Feb 22, 2023
0f27985
More optimizations
jlamypoirier Feb 23, 2023
0a6c8fe
cleanup
jlamypoirier Feb 23, 2023
cdf610b
conversion script
jlamypoirier Feb 24, 2023
718ab39
cleanup
jlamypoirier Feb 24, 2023
eb80372
cleanup
jlamypoirier Feb 24, 2023
7da239c
fixes
jlamypoirier Feb 24, 2023
be288ed
Merge branch 'more_optimizations' into fast_inference
jlamypoirier Feb 24, 2023
98b99db
Memory usage and alignment
jlamypoirier Feb 24, 2023
f5a2d7f
Use separate file for now
jlamypoirier Feb 25, 2023
9fefeaf
Merge branch 'main' into more_optimizations
jlamypoirier Feb 27, 2023
04538bc
Merge branch 'more_optimizations' into fast_inference
jlamypoirier Feb 27, 2023
60a41a1
style
jlamypoirier Feb 27, 2023
c997996
Merge branch 'more_optimizations' into fast_inference
jlamypoirier Feb 27, 2023
435b923
enum
jlamypoirier Feb 27, 2023
0d09856
Merge branch 'more_optimizations' into fast_inference
jlamypoirier Feb 27, 2023
efae11f
enum
jlamypoirier Feb 27, 2023
c560bdc
Pad key length
jlamypoirier Feb 28, 2023
d6a1ccd
Move gpu optimization to base model
jlamypoirier Feb 28, 2023
77b9ccf
Adapt inference runner
jlamypoirier Mar 1, 2023
f3c45f1
bugfix
jlamypoirier Mar 2, 2023
9b8d550
Merge branch 'main' into more_optimizations
jlamypoirier Mar 2, 2023
3741f9d
Merge branch 'more_optimizations' into fast_inference
jlamypoirier Mar 2, 2023
a58bba8
Merge branch 'main' into fast_inference
jlamypoirier Mar 2, 2023
352e36f
Merge branch 'fast_inference' into fast_inference_base
jlamypoirier Mar 2, 2023
80ff910
Merge branch 'main' into fast_inference_base
jlamypoirier Mar 2, 2023
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
14 changes: 10 additions & 4 deletions src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,9 @@ def __init__(
attention_type=AttentionType.MULTI_HEAD,
inference_runner=InferenceRunnerType.NO_RUNNER,
validate_runner_input=True,
runner_max_sequence_length=None,
pre_allocate_kv_cache=False,
max_sequence_length=None,
max_batch_size=None,
pad_key_length=True,
**kwargs,
):
Expand Down Expand Up @@ -218,9 +220,13 @@ def __init__(
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
# Set if `n_positions` uses too much memory.
self.runner_max_sequence_length = runner_max_sequence_length
# Pad key length to a multiple of 8.

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)
Expand Down
41 changes: 23 additions & 18 deletions src/transformers/models/gpt_bigcode/inference_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ def __init__(self, config: GPTBigCodeConfig, model):

self.inference_runner_type = InferenceRunnerType(config.inference_runner)
assert self.inference_runner_type != InferenceRunnerType.NO_RUNNER
assert config.pre_allocate_kv_cache
self.validate_input = config.validate_runner_input
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

self.max_sequence_length = config.runner_max_sequence_length or config.n_positions
self.max_sequence_length = config.max_sequence_length or config.n_positions

def _allocate(self, batch_size, device, dtype):
block: GPTBigCodeBlock = self.model.h[0]
Expand Down Expand Up @@ -55,19 +56,28 @@ def _allocate(self, batch_size, device, dtype):
attn_weights_begin = _align_tensor(kv_end)
attn_weights_end = kv_end + self.batch_size * attn.num_heads * self.max_sequence_length
# Projection: (batch_size, embed_dim), no overlap with attn outputs ~ query.
# Also used for MLP projection ()
# Also used for MLP projection
c_proj_begin = _align_tensor(query_end)
c_proj_end = c_proj_begin + self.batch_size * attn.embed_dim
c_fc_begin = query_begin
c_fc_end = c_fc_begin + self.batch_size * block.inner_dim
pool_size = max(attn_weights_end, c_proj_end, c_fc_end)
kv_cache_shape = (self.n_layer, self.batch_size, attn.kv_heads, self.max_sequence_length, 2 * attn.head_dim)
kv_cache_size = math.prod(kv_cache_shape)

print(
f"Allocating inference buffers (batch size = {self.batch_size}, max sequence length ="
f" {self.max_sequence_length})..."
)

kv_caches = []
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:
kv_cache=kv_cache.unsqueeze(1)
kv_caches.append(kv_cache)

kv_cache_size = sum(kv_cache.numel() for kv_cache in kv_caches)

print(f" Activation pool size: {pool_size:,}")
print(f" KV cache size: {kv_cache_size:,}")
buffer_memory = (pool_size + kv_cache_size) * torch.finfo(
Expand All @@ -76,10 +86,6 @@ def _allocate(self, batch_size, device, dtype):
print(f" Memory usage: {buffer_memory/2**20:.0f} MiB")

activation_pool = torch.empty(pool_size, **factory_kwargs)
kv_cache = torch.empty(
kv_cache_shape,
**factory_kwargs,
)
self.mask_value = torch.full(
[], torch.finfo(self.softmax_dtype).min, dtype=self.softmax_dtype, device=self.device
)
Expand Down Expand Up @@ -116,19 +122,22 @@ def _allocate(self, batch_size, device, dtype):
self.query = self.c_attn[:, : attn.embed_dim].view(self.batch_size, attn.num_heads, attn.head_dim)
self.kv_attn = self.c_attn[:, attn.embed_dim :]

key, value = kv_cache.split((attn.head_dim, attn.head_dim), dim=-1)
key = key.transpose(-1, -2)
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)

self.padded_keys = [key[:, :, head_slice, :, :key_length].unbind(0) for key_length in padded_key_lengths]
self.padded_values = [value[:, :, head_slice, :key_length, :].unbind(0) for key_length in padded_key_lengths]
self.padded_keys = [
[key[:, head_slice, :key_length, :].transpose(-1, -2) for key in keys] for key_length in padded_key_lengths
]
self.padded_values = [
[value[:, head_slice, :key_length, :] for value in values] for key_length in padded_key_lengths
]

# This is nonsense for key_length == 0, but we never need the value.
self.current_key_values = [
kv_cache[:, :, head_slice, key_length - 1, :].unbind(0) for key_length in key_lengths
[kv_cache[:, head_slice, key_length - 1, :] for kv_cache in kv_caches] for key_length in key_lengths
]
self.past_key_values = [
kv_cache[:, :, head_slice, : key_length - 1, :].unbind(0) for key_length in key_lengths
[kv_cache[:, head_slice, : key_length - 1, :] for kv_cache in kv_caches] for key_length in key_lengths
]

# Attn weights: (batch_size, num_heads, key_length), no overlap with value.
Expand Down Expand Up @@ -302,10 +311,6 @@ def forward(
else:
key_length = attention_mask.shape[1]

if not isinstance(past_key_values, int):
for buffer, past_key_value in zip(self.past_key_values[key_length], past_key_values):
buffer.copy_(past_key_value)

self._forward_embed(input_ids, position_ids)

self.attn_masks[key_length].copy_(attention_mask)
Expand Down
75 changes: 69 additions & 6 deletions src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,17 @@ class GPTBigCodeAttention(nn.Module):
def __init__(self, config, is_cross_attention=False, layer_idx=None):
super().__init__()
self.mask_value = None
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.attention_type = AttentionType(config.attention_type)
self.is_mqa = self.attention_type != AttentionType.MULTI_HEAD

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

self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
Expand Down Expand Up @@ -252,8 +259,6 @@ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
torch.empty(attn_view, dtype=query.dtype, device=query.device), query, key, beta=0, alpha=scale_factor
).view(attn_shape)

# attn_weights = self._matmul(query, key, scale_factor=scale_factor)

if upcast:
# Use a fused kernel to prevent a large overhead from casting and scaling.
# Sub-optimal when the key length is not a multiple of 8.
Expand Down Expand Up @@ -282,6 +287,35 @@ 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:
# TODO: Improve error message
raise RuntimeError("KV cache not found." if self.kv_cache is None else "Invalid KV cache.")
# 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.is_mqa else kv_cache[:, :, :sequence_length, :]

def forward(
self,
hidden_states: torch.FloatTensor,
Expand Down Expand Up @@ -319,8 +353,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 = 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.is_mqa:
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 All @@ -332,7 +385,7 @@ def forward(
attn_output = self.resid_dropout(attn_output)

# TODO: Is it ok to send unwrapped present?
outputs = (attn_output, key_value if use_cache else None)
outputs = (attn_output, present)
if output_attentions:
outputs += (attn_weights,)

Expand Down Expand Up @@ -681,6 +734,9 @@ 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:
Expand Down Expand Up @@ -827,8 +883,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 position_ids is None:
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
Expand All @@ -844,6 +902,11 @@ def forward(
# MHA: (b, nh, sq, sk)
attention_mask = self_attention_mask.unsqueeze(2 if self.is_mqa 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