Skip to content

Upcasting, scaling, masking and fused kernels to match Megatron-LM - #10

Merged
jlamypoirier merged 4 commits into
mainfrom
fp32_softmax
Feb 15, 2023
Merged

jlamypoirier merged 4 commits into
mainfrom
fp32_softmax

Conversation

@jlamypoirier

@jlamypoirier jlamypoirier commented Feb 9, 2023 •

Copy link
Copy Markdown
Collaborator

Run the following sequence (when enabled):

  • attn_weights = (query x key) / sqrt(head_dim) / (layer_idx+1) [Single kernel, I think that's needed to stabilize fp16]
  • Convert to fp32
  • multiply by (layer_idx+1)
  • Apply mask
  • Softmax
  • Convert to fp16

The whole thing runs in 2 kernels with jit fusion. Cuda time inference benchmark:

  • Without jit: 793.142ms
  • With jit: 751.869ms

Without upcast, the sequence is:
Run the following sequence (when enabled):

  • attn_weights = (query x key) / sqrt(head_dim)
  • Apply mask
  • Softmax

Jit can reduce it to 2 kernels:

  • Without jit: 745.253ms
  • With jit: 751.365ms

Jit looks slower so I disabled it.

Overall, jit fusion allows fp32 softmax with minimal overhead (0.9% instead of 6.4%) and without the complicated custom kernels from Megatron.

@jlamypoirier jlamypoirier changed the title Redo upcast, scaling and masking to match Megatron-LM Upcast, scaling, masking and fused softmax to match Megatron-LM Feb 10, 2023
@jlamypoirier jlamypoirier changed the title Upcast, scaling, masking and fused softmax to match Megatron-LM Upcasting, scaling, masking and fused kernels to match Megatron-LM Feb 10, 2023
@jlamypoirier
jlamypoirier marked this pull request as ready for review February 10, 2023 19:44
# Self-attention mask.
query_length = input_shape[-1]
key_length = past_length + query_length
self_attention_mask = self.bias[None, key_length - query_length : key_length, :key_length]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to move the causal-masking part from the Attention module to the GPTBigCodeModel?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's an extra optimization, so there is a single masking op instead of two and we avoid duplicating the mask generation.

@RaymondLi0 RaymondLi0 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@jlamypoirier
jlamypoirier merged commit 03716fa into main Feb 15, 2023
@jlamypoirier
jlamypoirier deleted the fp32_softmax branch February 15, 2023 21:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants