-
Notifications
You must be signed in to change notification settings - Fork 70
Extend attn in Shortfin #2518
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zeeshanhaque21
wants to merge
33
commits into
nod-ai:main
Choose a base branch
from
zeeshanhaque21:extend-attn-shortfin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Extend attn in Shortfin #2518
Changes from 21 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
d2bb0ae
Extend attn prefill
zeeshanhaque21 f8de260
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 ad46fef
Fixt chunked mode
zeeshanhaque21 25af208
Add tests
zeeshanhaque21 638361e
Fix tests
zeeshanhaque21 03be4cb
precommit fix
zeeshanhaque21 31e3aed
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 3c082fe
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 730591c
Change chunking strategy to dnamically recompute based on number of c…
zeeshanhaque21 74ee726
Fix tests
zeeshanhaque21 3496380
precommit
zeeshanhaque21 66bce01
cleanup
zeeshanhaque21 0a0896e
Address PR comments
zeeshanhaque21 c61915f
Refactor scheduler and prefill task
zeeshanhaque21 10794f0
Add tests for PrefillTask
zeeshanhaque21 6c15862
Formatting
zeeshanhaque21 3ad3509
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 759e204
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 9eb0de4
Add parameter
zeeshanhaque21 249fdf9
Merge branch 'main' into extend-attn-shortfin
zeeshanhaque21 5446cf1
Modify sharktank to export flags
zeeshanhaque21 3fdfded
Change min prefill bs to 1 in export
zeeshanhaque21 b16a5e3
Add debug logs to investigate data corruption
zeeshanhaque21 709f975
revert back to bs_min of 2 for torch.export
zeeshanhaque21 eb621cb
Add debug logs
zeeshanhaque21 856a70a
add use_extend_attention to ServiceConfig & update prefill name
archana-ramalingam 353d8ac
Enable extend attention in default path
archana-ramalingam 13858a5
Merge branch 'main' into update-extend-attn
archana-ramalingam 82bb572
Fix error
archana-ramalingam 7957f6e
Merge branch 'update-extend-attn' of https://github.com/nod-ai/shark-…
archana-ramalingam c9fdadb
Add debug statements
zeeshanhaque21 5e245a7
Merge remote-tracking branch 'origin/update-extend-attn' into extend-…
zeeshanhaque21 1c7bb7b
Merge remote-tracking branch 'origin/main' into extend-attn-shortfin
zeeshanhaque21 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
206 changes: 206 additions & 0 deletions
206
shortfin/python/shortfin_apps/llm/components/batching/modes/extend_attention.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| # Copyright 2025 Advanced Micro Devices, Inc. | ||
| # | ||
| # Licensed under the Apache License v2.0 with LLVM Exceptions. | ||
| # See https://llvm.org/LICENSE.txt for license information. | ||
| # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
|
|
||
| import logging | ||
| from typing import List | ||
|
|
||
| import shortfin as sf | ||
|
|
||
| from shortfin import Fiber | ||
|
|
||
| from ..batching_trait import BatchingTrait | ||
| from ..config import BatchConfig | ||
| from ...config_struct import ModelParams | ||
| from ...invocation import ( | ||
| ExtendAttentionPrefillTask, | ||
| LlmInvocationProcess, | ||
| LlmTask, | ||
| LlmTaskInput, | ||
| ) | ||
| from ...kvcache.base_attention_cache import BasePagedAttentionCache | ||
| from ...messages import InferencePhase, LlmInferenceExecRequest | ||
| from ...scheduler import ExtendAttentionScheduler | ||
|
|
||
| from .default import ( | ||
| LlmBatcherProcess, | ||
| PrefillTaskResponder, | ||
| DecodeBatcherProcess, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ExtendAttentionPrefillBatcherProcess(LlmBatcherProcess): | ||
| """Batcher process optimized for extend-attention prefill.""" | ||
|
|
||
| STROBE_SHORT_DELAY = 0.065 | ||
| STROBE_LONG_DELAY = 0.065 | ||
|
|
||
| def __init__( | ||
| self, | ||
| fiber: Fiber, | ||
| page_cache: BasePagedAttentionCache, | ||
| model_params: ModelParams, | ||
| prefill_functions: dict[int, sf.ProgramFunction], | ||
| program_isolation: str, | ||
| token_budget: int, | ||
| ): | ||
| # Use the extend-attention aware scheduler | ||
| block_seq_stride = model_params.paged_kv_cache.block_seq_stride | ||
|
|
||
| scheduler = ExtendAttentionScheduler( | ||
| token_budget=token_budget, block_seq_stride=block_seq_stride | ||
| ) | ||
|
|
||
| llm_task_responder = PrefillTaskResponder(scheduler=scheduler) | ||
|
|
||
| # ideal_batch_size - not really important. we can set it to | ||
| # maximum number of requests that can be batched together. | ||
| ideal_batch_size = token_budget // block_seq_stride | ||
|
|
||
| super().__init__( | ||
| name="extend_attention_prefill", | ||
| fiber=fiber, | ||
| page_cache=page_cache, | ||
| model_params=model_params, | ||
| functions=prefill_functions, | ||
| ideal_batch_size=ideal_batch_size, | ||
| program_isolation=program_isolation, | ||
| scheduler=scheduler, | ||
| llm_task_responder=llm_task_responder, | ||
| ) | ||
|
|
||
| def make_task_inputs( | ||
| self, exec_request: LlmInferenceExecRequest | ||
| ) -> List[LlmTaskInput]: | ||
| """Create a single task input containing all tokens. | ||
|
|
||
| The scheduler will dynamically chunk this request at scheduling time based | ||
| on the number of active requests and the token budget. | ||
| """ | ||
| total_tokens = len(exec_request.input_token_ids) | ||
|
|
||
| # Return a single task with ALL tokens | ||
| # The scheduler will chunk it dynamically | ||
| return [ | ||
| LlmTaskInput( | ||
| rid=exec_request.orig_instance_id, | ||
| instance_id=exec_request.instance_id, | ||
| block_count=exec_request.block_count, | ||
| seq_len=total_tokens, | ||
| input_tokens=tuple(exec_request.input_token_ids), | ||
| page_ids=tuple(exec_request.page_ids), | ||
| start_position=0 | ||
| if exec_request.start_position is None | ||
| else exec_request.start_position, | ||
| ) | ||
| ] | ||
|
|
||
| def make_task( | ||
| self, | ||
| task_inputs: List[LlmTaskInput], | ||
| page_cache: BasePagedAttentionCache, | ||
| ) -> LlmTask: | ||
| """Create an extend-attention aware prefill task.""" | ||
| return ExtendAttentionPrefillTask( | ||
| task_inputs=task_inputs, | ||
| array_cache=self.array_cache, | ||
| page_tables=page_cache.page_pool.page_tables, | ||
| has_prefill_position=self.model_params.has_prefill_position, | ||
| block_seq_stride=self.page_seq_stride, | ||
| ) | ||
|
|
||
| def make_invoker( | ||
| self, | ||
| page_cache: BasePagedAttentionCache, | ||
| fiber: Fiber, | ||
| task_inputs: list[LlmTaskInput], | ||
| ) -> LlmInvocationProcess: | ||
| """Create invoker for extend-attention prefill.""" | ||
| return LlmInvocationProcess( | ||
| name="extend_attention_prefill_invocation", | ||
| fiber=fiber, | ||
| llm_task=self.make_task(task_inputs, page_cache), | ||
| functions=self.functions, | ||
| program_isolation=self.program_isolation, | ||
| responder=self._llm_task_responder, | ||
| ) | ||
|
|
||
|
|
||
| class ExtendAttentionBatchingEngine(BatchingTrait): | ||
| """Batching engine that uses extend-attention for improved prefill batching.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| prefill_lane: ExtendAttentionPrefillBatcherProcess, | ||
| decode_lane: DecodeBatcherProcess, | ||
| ): | ||
| self.prefill_lane = prefill_lane | ||
| self.decode_lane = decode_lane | ||
|
|
||
| def submit(self, request: LlmInferenceExecRequest): | ||
| if request.phase == InferencePhase.PREFILL: | ||
| self.prefill_lane.submit(request) | ||
| elif request.phase == InferencePhase.DECODE: | ||
| self.decode_lane.submit(request) | ||
| else: | ||
| raise ValueError( | ||
| "Requested unsupported batching lane: Supported only either prefill or decode." | ||
| ) | ||
|
|
||
| def launch(self): | ||
| self.prefill_lane.launch() | ||
| self.decode_lane.launch() | ||
|
|
||
| def shutdown(self): | ||
| self.prefill_lane.shutdown() | ||
| self.decode_lane.shutdown() | ||
|
|
||
| def reserve_workload(self, rid: str, count: int): | ||
| self.decode_lane.reserve_workload(rid=rid, count=count) | ||
|
|
||
| def get_model_params(self) -> ModelParams: | ||
| return self.prefill_lane.model_params | ||
|
|
||
| @staticmethod | ||
| def create( | ||
| batch_cfg: BatchConfig, | ||
| page_cache: BasePagedAttentionCache, | ||
| prefill_fiber: sf.Fiber, | ||
| decode_fiber: sf.Fiber, | ||
| ): | ||
| """Create an extend-attention batching engine.""" | ||
|
|
||
| # Check if the model was exported with extend-attention support | ||
| if not batch_cfg.model_params.use_extend_attention: | ||
| raise ValueError( | ||
| "Model was not exported with extend-attention support. " | ||
| "Please export the model with --use-extend-attention flag." | ||
| ) | ||
| assert batch_cfg.token_budget is not None | ||
| token_budget = batch_cfg.token_budget | ||
|
|
||
| prefill_batcher = ExtendAttentionPrefillBatcherProcess( | ||
| fiber=prefill_fiber, | ||
| page_cache=page_cache, | ||
| model_params=batch_cfg.model_params, | ||
| prefill_functions=batch_cfg.prefill_functions, | ||
| program_isolation=batch_cfg.prog_isolation, | ||
| token_budget=token_budget, | ||
| ) | ||
|
|
||
| decode_batcher = DecodeBatcherProcess( | ||
| fiber=decode_fiber, | ||
| page_cache=page_cache, | ||
| model_params=batch_cfg.model_params, | ||
| decode_functions=batch_cfg.decode_functions, | ||
| program_isolation=batch_cfg.prog_isolation, | ||
| ) | ||
|
|
||
| return ExtendAttentionBatchingEngine( | ||
| prefill_lane=prefill_batcher, | ||
| decode_lane=decode_batcher, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's the reasoning for adding this change?