Skip to content

Commit 48f3c19

Browse files
committed
Add attention_backend to let user choose
bump this into the constructor of BuilderArgs
1 parent cbc72a4 commit 48f3c19

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

torchchat/cli/builder.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class BuilderArgs:
6969
prefill_possible: bool = False
7070
dynamic_shapes: bool = False
7171
max_seq_length: Optional[int] = None
72+
attention_backend: str = "math"
7273

7374
def __post_init__(self):
7475
if self.device is None:
@@ -178,6 +179,17 @@ def from_args(cls, args: argparse.Namespace) -> "BuilderArgs":
178179
pp = getattr(args, "pp", 1)
179180
tp = getattr(args, "tp", 1)
180181
chpt_from = getattr(args, "chpt_from", "hf")
182+
sdp_backend_dict = {
183+
'math': torch.nn.attention.SDPBackend.MATH,
184+
'flash_attention': torch.nn.attention.SDPBackend.FLASH_ATTENTION,
185+
'efficient_attention': torch.nn.attention.SDPBackend.EFFICIENT_ATTENTION,
186+
'cudnn_attention': torch.nn.attention.SDPBackend.CUDNN_ATTENTION,
187+
}
188+
attention_backend = sdp_backend_dict[args.attention_backend]
189+
if args.device == "cpu" and (args.attention_backend == "efficient_attention"
190+
or args.attention_backend == "cudnn_attention"):
191+
print(f"Warning: {args.attention_backend} is not supported on CPU. Using math instead.")
192+
attention_backend = torch.nn.attention.SDPBackend.MATH
181193
return cls(
182194
checkpoint_dir=checkpoint_dir,
183195
checkpoint_path=checkpoint_path,
@@ -202,6 +214,7 @@ def from_args(cls, args: argparse.Namespace) -> "BuilderArgs":
202214
is_chat_model=is_chat_model,
203215
dynamic_shapes=getattr(args, "dynamic_shapes", False),
204216
max_seq_length=getattr(args, "max_seq_length", None),
217+
attention_backend=attention_backend,
205218
)
206219

207220
@classmethod

torchchat/cli/cli.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,13 @@ def _add_model_config_args(parser, verb: str) -> None:
179179
choices=["fast", "cpu", "cuda", "mps"],
180180
help="Hardware device to use. Options: fast, cpu, cuda, mps",
181181
)
182+
model_config_parser.add_argument(
183+
"--attention-backend",
184+
type=str,
185+
default="math",
186+
choices=["math", "flash_attention", "efficient_attention", "cudnn_attention"],
187+
help="SDPBackend to use. Options: MATH, FLASH_ATTENTION, EFFICIENT_ATTENTION, CUDNN_ATTENTION",
188+
)
182189

183190

184191
# Add CLI Args representing output paths of exported model files

torchchat/generate.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import torch.distributed as dist
2727
import torch.multiprocessing as mp
2828
from torch.distributed.pipelining import PipelineStage, ScheduleGPipe
29+
from torch._C import _SDPBackend as SDPBackend
2930

3031
from PIL import Image
3132

@@ -531,6 +532,7 @@ def decode_n_tokens(
531532
callback=lambda _: _,
532533
eos_token_id: int = 2,
533534
eot_id: Optional[int] = None,
535+
attention_backend: SDPBackend = torch.nn.attention.SDPBackend.MATH,
534536
**sampling_kwargs,
535537
):
536538
new_tokens, new_probs = [], []
@@ -539,7 +541,7 @@ def decode_n_tokens(
539541
num_new_tokens - 1
540542
): # -1 to save space to run an EoS if dont generate it naturally
541543
# Actually better for Inductor to codegen attention here
542-
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
544+
with torch.nn.attention.sdpa_kernel([attention_backend]):
543545

544546
out_token = cur_token.clone()
545547
next_token, next_prob = self.decode_one_token(
@@ -683,6 +685,7 @@ def generate(
683685
sequential_prefill=True,
684686
callback=lambda x: x,
685687
max_seq_length: int,
688+
attention_backend: str = "math",
686689
seed: Optional[int] = None,
687690
**sampling_kwargs,
688691
) -> torch.Tensor:
@@ -799,6 +802,7 @@ def generate(
799802
if self.is_llama3_model
800803
else None
801804
),
805+
attention_backend=attention_backend,
802806
**sampling_kwargs,
803807
):
804808
generated_tokens.append(generated_token.view(-1))
@@ -1186,6 +1190,7 @@ def callback(x, *, done_generating=False):
11861190
start_pos=start_pos,
11871191
skip_cache_setup=not is_first_sample,
11881192
max_seq_length=max_seq_length,
1193+
attention_backend=self.builder_args.attention_backend,
11891194
)
11901195
for token_tensor, metrics in generator_func:
11911196
if token_tensor is not None:

0 commit comments

Comments
 (0)