Skip to content
Merged
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
25 changes: 8 additions & 17 deletions torchtitan/models/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
#
# Copyright (c) Meta Platforms, Inc. All Rights Reserved.

import functools
from collections.abc import Callable
from typing import ClassVar, NamedTuple

Expand Down Expand Up @@ -164,22 +163,19 @@ def forward(
return F.scaled_dot_product_attention(q, k, v, scale=scale, is_causal=True)


# We cannot do inner function/closure because we won't be able to cache it --
# if we an inner function, a new closure will be created every time
# `get_causal_mask_mod` is called.
def _causal_mask(
b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor
) -> torch.Tensor:
"""Causal mask that prevents attention to future tokens."""
return q_idx >= kv_idx


def get_causal_mask_mod() -> _mask_mod_signature:
"""Returns a causal mask modifier for flex attention.

Returns:
A mask modifier function that implements causal masking.
"""

def _causal_mask(
b: torch.Tensor, h: torch.Tensor, q_idx: torch.Tensor, kv_idx: torch.Tensor
) -> torch.Tensor:
"""Causal mask that prevents attention to future tokens."""
return q_idx >= kv_idx

return _causal_mask


Expand Down Expand Up @@ -268,13 +264,8 @@ def sliding_window_mod(
_compiled_create_block_mask = torch.compile(create_block_mask)


@functools.lru_cache(4)
def create_attention_mask(*args, **kwargs):
"""Create an attention mask using compiled create_block_mask.

This function is cached to avoid recreating BlockMasks for the same
arguments.
"""
"""Create an attention mask using compiled create_block_mask."""
return _compiled_create_block_mask(*args, **kwargs)


Expand Down
Loading