Skip to main content
CookLLM logoCookLLM Docs

Causal Masking Optimization

Premium

Implement causal attention for autoregressive models, achieving ~2x speedup by skipping the upper-triangular computation.

Get code access

In the previous three chapters, we implemented a complete Flash Attention kernel that supports arbitrary sequence lengths and multi-dimensional parallelism. But we have not yet optimized for one very important application scenario: autoregressive generation.

This is precisely the core computation pattern of decoder-only models such as GPT and LLaMA. By introducing causal masking, we can gain a further speedup of about 2x.

Quick Review of Causal Attention

Causal attention is the core mechanism of autoregressive language models: when predicting the ii-th token, the model can only see information from positions 0 to i-1, and cannot see future tokens.

In the attention matrix, this is implemented by setting the upper-triangular part to −∞-\infty:

         K₀  K₁  K₂  K₃
    Q₀ [ ·  -∞  -∞  -∞ ]  ← Q₀ can only see K₀
    Q₁ [ ·   ·  -∞  -∞ ]  ← Q₁ can only see K₀,K₁
    Q₂ [ ·   ·   ·  -∞ ]  ← Q₂ can only see K₀,K₁,K₂
    Q₃ [ ·   ·   ·   · ]  ← Q₃ can see everything

If you are not yet familiar with the concept and principles of causal attention, we recommend first reading the detailed introduction in Attention Mechanism Explained.

This chapter focuses on how to efficiently implement causal masking in Flash Attention to gain a performance improvement.

Log in to continue reading

This is premium content. Please log in to access the full article.