Repository navigation
[TRTLLM-17109][perf] Reduce Gemma multimodal attention mask construction peak memory #20405
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
Merged
zhaoyangwang-nvidia
merged 4 commits into
NVIDIA:main
from
zhaoyangwang-nvidia:perf/gemma-mask-peak
Oct 19, 2026
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0b5e952
Reduce Gemma multimodal attention mask construction peak memory
zhaoyangwang-nvidia c6dbe38
Limit Gemma mask CI coverage to one peak-memory regression
zhaoyangwang-nvidia 04391ea
Strengthen Gemma mask output contract and modality coverage
zhaoyangwang-nvidia d98b728
Keep shared Gemma attention mask helper in model code
zhaoyangwang-nvidia 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Construct Gemma vision attention masks directly in their final storage.""" | ||
|
|
||
| import torch | ||
| import triton | ||
| import triton.language as tl | ||
|
|
||
|
|
||
| @triton.jit | ||
| def _write_mask( | ||
| output, | ||
| blob_ids, | ||
| query_length, | ||
| prefix_length, | ||
| WINDOW: tl.constexpr, | ||
| BLOCK: tl.constexpr, | ||
| ): | ||
| row = tl.program_id(0) | ||
| col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) | ||
| key_length = prefix_length + query_length | ||
| valid = col < key_length | ||
| offsets = row.to(tl.int64) * key_length + col | ||
| allowed = col <= prefix_length + row | ||
| if WINDOW is not None: | ||
| allowed &= col > prefix_length + row - WINDOW | ||
| query_blob = tl.load(blob_ids + row) | ||
| key_blob = tl.load(blob_ids + col - prefix_length, valid & (col >= prefix_length), other=0) | ||
| allowed |= (query_blob != 0) & (query_blob == key_blob) | ||
| tl.store(output + offsets, allowed, valid) | ||
|
|
||
|
|
||
| def build_gemma_attention_mask( | ||
| token_types: torch.Tensor, | ||
| context_lengths: list[int], | ||
| prefix_lengths: list[int], | ||
| sliding_window: int | None = None, | ||
| ) -> torch.Tensor: | ||
| """Build flattened bool masks for packed Gemma context requests. | ||
|
|
||
| CUDA graph capture requires prior warmup. Request lengths, prefix lengths, | ||
| and the sliding window are host-side launch parameters and must remain | ||
| fixed during replay; token-type values may change in place. This function | ||
| does not modify token_types. | ||
|
|
||
| Args: | ||
| token_types: One-dimensional CUDA bool image flags (Gemma3) or integer | ||
| modality IDs (Gemma4: 0=text, 1=image, 2=video, 3=audio). Contiguous | ||
| runs of the same vision type attend bidirectionally. A strided | ||
| input is supported; trailing generation tokens are ignored. | ||
| context_lengths: Number of new tokens for each context request. | ||
| prefix_lengths: Cached token counts in the same request order. Chunk | ||
| boundaries must not split a vision blob, as in the model caller. | ||
| sliding_window: Exclusive lower attention-window bound, or None. | ||
|
|
||
| Returns: | ||
| Contiguous mask with sum(q * (p + q)) elements. Prefix columns apply | ||
| causal/window rules; vision blobs override those rules only among | ||
| new tokens. Intermediate storage is linear in the context length. | ||
| """ | ||
| mask_sizes = [q * (p + q) for q, p in zip(context_lengths, prefix_lengths, strict=True)] | ||
| output = torch.empty(sum(mask_sizes), dtype=torch.bool, device=token_types.device) | ||
| token_offset = 0 | ||
| mask_offset = 0 | ||
| for q, p, size in zip(context_lengths, prefix_lengths, mask_sizes, strict=True): | ||
| types = token_types[token_offset : token_offset + q] | ||
| if size: | ||
| vision = (types == 1) | (types == 2) | ||
| previous = torch.cat((types.new_zeros(1), types[:-1])) | ||
| starts = (types != previous) & vision | ||
| blobs = torch.cumsum(starts, dim=0, dtype=torch.int32) | ||
| blobs.masked_fill_(~vision, 0) | ||
| _write_mask[(q, triton.cdiv(p + q, 1024))]( | ||
| output[mask_offset : mask_offset + size], blobs, q, p, sliding_window, 1024 | ||
| ) | ||
| token_offset += q | ||
| mask_offset += size | ||
| return output | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.