-
Notifications
You must be signed in to change notification settings - Fork 19
Add Granite 4.1 20B support (GraniteSWA adapter) #283
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
lipikaworkemail-ctrl
wants to merge
2
commits into
torch-spyre:main
Choose a base branch
from
lipikaworkemail-ctrl:enable-granite-4-1-20b-hf-adapters
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| # Copyright 2025 The Torch-Spyre Authors. | ||
| # | ||
| # 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. | ||
|
|
||
| """ | ||
| HuggingFace Transformers adapter for Granite 4.1 SWA models on Spyre. | ||
|
|
||
| GraniteSWAForCausalLM is identical to Granite 3.x except that layers alternate | ||
| between full attention and sliding-window attention (``layer_type`` attribute on | ||
| each ``GraniteSWADecoderLayer``). Sliding-window layers receive a local attention | ||
| mask that restricts each token to attend only within the ``sliding_window`` window; | ||
| full-attention layers delegate to ``make_standard_gqa_block`` (same as Granite 3.x). | ||
|
|
||
| Usage:: | ||
|
|
||
| from hf_adapters import AutoSpyreModelForCausalLM | ||
| from transformers import AutoTokenizer | ||
|
|
||
| model = AutoSpyreModelForCausalLM.from_pretrained( | ||
| "/tmp/models/granite-4.1-20b") | ||
| tokenizer = AutoTokenizer.from_pretrained("/tmp/models/granite-4.1-20b") | ||
| outputs = model.generate(tokenizer, ["Hello!"], max_new_tokens=32) | ||
| """ | ||
|
|
||
| import torch | ||
| import torch.nn.functional as F | ||
|
|
||
| from hf_adapters.hf_common import ( | ||
| apply_rope_matmul, | ||
| get_backbone, | ||
| kv_cache_update, | ||
| make_standard_gqa_block, | ||
| pad_lm_head, | ||
| patch_rmsnorm, | ||
| prepare_rope_and_heads, | ||
| ) | ||
| from hf_adapters.hf_granite import _run_backbone_forward, _run_forward # noqa: F401 | ||
|
|
||
|
|
||
| def _make_compiled_block(layer, sliding_window: int): | ||
| """Compiled block for a GraniteSWA sliding-window attention layer. | ||
|
|
||
| Builds a band mask: positions further than ``sliding_window`` steps back | ||
| are set to ``-inf``. | ||
| """ | ||
| attn = layer.self_attn | ||
| mlp = layer.mlp | ||
| input_ln = layer.input_layernorm | ||
| post_attn_ln = layer.post_attention_layernorm | ||
| res_mult = layer.residual_multiplier | ||
| v_head_dim = getattr(attn, "v_head_dim", attn.head_dim) | ||
|
|
||
| def block_forward( | ||
| hidden_states, | ||
| selected_freqs, | ||
| attn_mask, | ||
| key_cache, | ||
| value_cache, | ||
| is_filling, | ||
| token_index, | ||
| cache_position, | ||
| ): | ||
| residual = hidden_states | ||
| h = input_ln(hidden_states) | ||
|
|
||
| bsz, seq_len, _ = h.shape | ||
| q = attn.q_proj(h).view(bsz, seq_len, -1, attn.head_dim).transpose(1, 2) | ||
| k = attn.k_proj(h).view(bsz, seq_len, -1, attn.head_dim).transpose(1, 2) | ||
| v = attn.v_proj(h).view(bsz, seq_len, -1, v_head_dim).transpose(1, 2) | ||
|
|
||
| q = apply_rope_matmul(q, selected_freqs) | ||
| k = apply_rope_matmul(k, selected_freqs) | ||
|
|
||
| key_cache, value_cache = kv_cache_update( | ||
| k, | ||
| v, | ||
| key_cache, | ||
| value_cache, | ||
| is_filling, | ||
| token_index, | ||
| cache_position, | ||
| ) | ||
|
|
||
| cache_len = key_cache.shape[2] | ||
| q_len = q.shape[2] | ||
| q_pos = (token_index + torch.arange(q_len, device=q.device)).unsqueeze( | ||
| 1 | ||
| ) # [q, 1] | ||
| k_pos = torch.arange(cache_len, device=q.device).unsqueeze(0) # [1, k] | ||
| window_mask = (q_pos - k_pos) >= sliding_window # [q, k] | ||
| swa_mask = attn_mask.clone() | ||
| swa_mask = swa_mask.masked_fill( | ||
| window_mask.unsqueeze(0).unsqueeze(0), float("-inf") | ||
| ) | ||
|
|
||
| attn_out = F.scaled_dot_product_attention( | ||
| q, | ||
| key_cache, | ||
| value_cache, | ||
| attn_mask=swa_mask, | ||
| dropout_p=0.0, | ||
| scale=attn.scaling, | ||
| enable_gqa=True, | ||
| ) | ||
| attn_out = attn_out.transpose(1, 2).reshape(bsz, seq_len, -1) | ||
| attn_out = attn.o_proj(attn_out) | ||
|
|
||
| h = residual + attn_out * res_mult | ||
|
|
||
| residual = h | ||
| h = post_attn_ln(h) | ||
| h = mlp(h) | ||
| h = residual + h * res_mult | ||
|
|
||
| return h, key_cache, value_cache | ||
|
|
||
| return torch.compile(block_forward, dynamic=False) | ||
|
|
||
|
|
||
| def prepare_for_spyre(model): | ||
| """Apply Spyre adaptations to a GraniteSWA model in-place.""" | ||
| from transformers.models.granite_swa.modeling_granite_swa import GraniteSWARMSNorm | ||
|
|
||
| sliding_window = model.config.sliding_window | ||
| prepare_rope_and_heads(model) | ||
| patch_rmsnorm(GraniteSWARMSNorm) | ||
| pad_lm_head(model) | ||
| model._spyre_compiled_blocks = [ | ||
| ( | ||
| _make_compiled_block(layer, sliding_window) | ||
| if getattr(layer, "layer_type", "full_attention") == "sliding_attention" | ||
| else make_standard_gqa_block(layer, True) | ||
| ) | ||
| for layer in get_backbone(model).layers | ||
| ] |
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
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.
Uh oh!
There was an error while loading. Please reload this page.