-
Notifications
You must be signed in to change notification settings - Fork 33.8k
GptOss experts implementation #43227
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
Merged
Changes from 11 commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
2aff4a8
experts impl gpt oss
IlyasMoutawwakil 9958efb
no need to transpose dequantized experts
IlyasMoutawwakil b23e1ff
skip test_reverse_loading_mapping
IlyasMoutawwakil e28f155
fix custom gating
IlyasMoutawwakil e57d0a8
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil be08fe4
revert transposition and simply support transposed experts to avoid m…
IlyasMoutawwakil e1dba4d
style
IlyasMoutawwakil 0261a46
don't rely on weight shapes as they can be square matrices
IlyasMoutawwakil 5bd25c7
no need to relaod
IlyasMoutawwakil 846adca
fallback to eager
IlyasMoutawwakil b1a71a7
Update src/transformers/models/gpt_oss/modeling_gpt_oss.py
IlyasMoutawwakil 9dbed89
fix
IlyasMoutawwakil 2f3fd11
force 16 bytes alignmenet during weight loading
IlyasMoutawwakil dd377e1
simplify logic
IlyasMoutawwakil 52e0778
quantization conversions should be applied first
IlyasMoutawwakil 1c49112
avoid baddbmm as it is less performant / less optimizable by max-auto…
IlyasMoutawwakil 4b0323c
no need for logger
IlyasMoutawwakil aa34996
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil f094c31
add comment explaining limitation
IlyasMoutawwakil 221f9bd
standarize operations and only reshape when needed
IlyasMoutawwakil 944afb5
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil 1fc01dc
fixup conversion and test
vasqu d820713
Update src/transformers/conversion_mapping.py
IlyasMoutawwakil 71fdb18
force alignment docstring
IlyasMoutawwakil e852cbb
move default apply gate
IlyasMoutawwakil d698dcb
offsets
IlyasMoutawwakil 5c2ca3c
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil d6631bb
add docs and make kernel_config optional
IlyasMoutawwakil 4f7226d
use reshapes as they are equivalent to views when memory is contiguous
IlyasMoutawwakil 2117303
fix and better notes
IlyasMoutawwakil 944a0ec
reshapes instead of views
IlyasMoutawwakil 1a0ea12
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil 16e6536
keep model saving and reloading in grouped_mm test to catch misalignm…
IlyasMoutawwakil 75ab275
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil 711a652
Merge branch 'main' into gpt-oss-experts-impl
IlyasMoutawwakil 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,7 +27,7 @@ | |
| from ... import initialization as init | ||
| from ...cache_utils import Cache, DynamicCache | ||
| from ...generation import GenerationMixin | ||
| from ...integrations import use_kernel_forward_from_hub, use_kernelized_func | ||
| from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernelized_func | ||
| from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask | ||
| from ...modeling_layers import ( | ||
| GenericForSequenceClassification, | ||
|
|
@@ -64,86 +64,54 @@ def extra_repr(self): | |
| return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" | ||
|
|
||
|
|
||
| @use_experts_implementation(transposed_experts=True) | ||
| class GptOssExperts(nn.Module): | ||
| def __init__(self, config): | ||
| super().__init__() | ||
| self.intermediate_size = config.intermediate_size | ||
| self.num_experts = config.num_local_experts | ||
| self.hidden_size = config.hidden_size | ||
| self.expert_dim = self.intermediate_size | ||
| self.gate_up_proj = nn.Parameter(torch.zeros(self.num_experts, self.hidden_size, 2 * self.expert_dim)) | ||
| self.gate_up_proj_bias = nn.Parameter(torch.zeros(self.num_experts, 2 * self.expert_dim)) | ||
| self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.expert_dim, self.hidden_size))) | ||
| self.down_proj_bias = nn.Parameter(torch.zeros(self.num_experts, self.hidden_size)) | ||
| self.experts_are_transposed = True | ||
|
IlyasMoutawwakil marked this conversation as resolved.
Outdated
|
||
| self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.intermediate_size)) | ||
| self.gate_up_proj_bias = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_size)) | ||
| self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.intermediate_size, self.hidden_size))) | ||
| self.down_proj_bias = nn.Parameter(torch.empty(self.num_experts, self.hidden_size)) | ||
|
vasqu marked this conversation as resolved.
Outdated
|
||
| self.alpha = 1.702 | ||
| self.limit = 7.0 | ||
|
|
||
| def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor: | ||
| """ | ||
| When training it is more efficient to just loop over the experts and compute the output for each expert | ||
| as otherwise the memory would explode. | ||
| def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor: | ||
| gate, up = gate_up[..., ::2], gate_up[..., 1::2] | ||
| gate = gate.clamp(min=None, max=self.limit) | ||
| up = up.clamp(min=-self.limit, max=self.limit) | ||
| glu = gate * torch.sigmoid(gate * self.alpha) | ||
| gated_output = (up + 1) * glu | ||
| return gated_output | ||
|
Comment on lines
+81
to
+87
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is fine, makes it more readable! |
||
|
|
||
| For inference we can sacrifice some memory and compute the output for all experts at once. By repeating the inputs. | ||
|
|
||
| Args: | ||
| hidden_states (torch.Tensor): (batch_size, seq_len, hidden_size) | ||
| selected_experts (torch.Tensor): (batch_size * seq_len, top_k) | ||
| routing_weights (torch.Tensor): (batch_size * seq_len, top_k) | ||
| Returns: | ||
| torch.Tensor | ||
| """ | ||
| batch_size = hidden_states.shape[0] | ||
| hidden_states = hidden_states.reshape(-1, self.hidden_size) # (num_tokens, hidden_size) | ||
| if hidden_states.device.type == "cpu" or self.training: | ||
| next_states = torch.zeros_like(hidden_states, dtype=hidden_states.dtype, device=hidden_states.device) | ||
| def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor: | ||
| next_states = torch.zeros_like(hidden_states, dtype=hidden_states.dtype, device=hidden_states.device) | ||
| with torch.no_grad(): | ||
| expert_mask = torch.nn.functional.one_hot( | ||
| router_indices, num_classes=self.num_experts | ||
| ) # masking is also a class | ||
| expert_mask = expert_mask.permute(2, 1, 0) | ||
| # we sum on the top_k and on the sequence length to get which experts | ||
| # are hit this time around | ||
| expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() | ||
| for expert_idx in expert_hit: | ||
| # expert_idx only have 1 element, so we can use scale for fast indexing | ||
| expert_idx = expert_idx[0] | ||
| # skip masking index | ||
| if expert_idx == self.num_experts: | ||
| continue | ||
| with torch.no_grad(): | ||
| expert_mask = torch.nn.functional.one_hot( | ||
| router_indices, num_classes=self.num_experts | ||
| ) # masking is also a class | ||
| expert_mask = expert_mask.permute(2, 1, 0) | ||
| # we sum on the top_k and on the sequence length to get which experts | ||
| # are hit this time around | ||
| expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() | ||
| for expert_idx in expert_hit[:]: | ||
| # expert_idx only have 1 element, so we can use scale for fast indexing | ||
| expert_idx = expert_idx[0] | ||
| # skip masking index | ||
| if expert_idx == self.num_experts: | ||
| continue | ||
| with torch.no_grad(): | ||
| top_k_pos, token_idx = torch.where(expert_mask[expert_idx]) | ||
| current_state = hidden_states[token_idx] | ||
| gate_up = current_state @ self.gate_up_proj[expert_idx] + self.gate_up_proj_bias[expert_idx] | ||
| gate, up = gate_up[..., ::2], gate_up[..., 1::2] | ||
| gate = gate.clamp(min=None, max=self.limit) | ||
| up = up.clamp(min=-self.limit, max=self.limit) | ||
| glu = gate * torch.sigmoid(gate * self.alpha) | ||
| gated_output = (up + 1) * glu | ||
| out = gated_output @ self.down_proj[expert_idx] + self.down_proj_bias[expert_idx] | ||
| weighted_output = out * routing_weights[token_idx, top_k_pos, None] | ||
| next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype)) | ||
| next_states = next_states.view(batch_size, -1, self.hidden_size) | ||
| else: | ||
| num_tokens = hidden_states.shape[0] | ||
| hidden_states = hidden_states.repeat(self.num_experts, 1) | ||
| hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size) | ||
| gate_up = torch.bmm(hidden_states, self.gate_up_proj) + self.gate_up_proj_bias[..., None, :] | ||
| gate, up = gate_up[..., ::2], gate_up[..., 1::2] | ||
| gate = gate.clamp(min=None, max=self.limit) | ||
| up = up.clamp(min=-self.limit, max=self.limit) | ||
| glu = gate * torch.sigmoid(gate * self.alpha) | ||
| next_states = torch.bmm(((up + 1) * glu), self.down_proj) | ||
| next_states = next_states + self.down_proj_bias[..., None, :] | ||
| next_states = next_states.view(self.num_experts, batch_size, -1, self.hidden_size) | ||
|
|
||
| full_routing_weights = torch.zeros( | ||
| num_tokens, self.num_experts, device=routing_weights.device, dtype=routing_weights.dtype | ||
| ) | ||
| full_routing_weights.scatter_(1, router_indices, routing_weights) | ||
| full_routing_weights = full_routing_weights.transpose(0, 1).view(self.num_experts, batch_size, -1, 1) | ||
| top_k_pos, token_idx = torch.where(expert_mask[expert_idx]) | ||
| current_state = hidden_states[token_idx] | ||
| gate_up = current_state @ self.gate_up_proj[expert_idx] + self.gate_up_proj_bias[expert_idx] | ||
| gated_output = self._apply_gate(gate_up) | ||
| out = gated_output @ self.down_proj[expert_idx] + self.down_proj_bias[expert_idx] | ||
| weighted_output = out * routing_weights[token_idx, top_k_pos, None] | ||
| next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype)) | ||
|
|
||
| next_states = next_states * full_routing_weights | ||
| next_states = next_states.sum(dim=0) | ||
| return next_states | ||
|
|
||
|
|
||
|
|
@@ -157,7 +125,6 @@ def __init__(self, config): | |
| self.bias = nn.Parameter(torch.zeros(self.num_experts)) | ||
|
|
||
| def forward(self, hidden_states): | ||
| hidden_states = hidden_states.reshape(-1, self.hidden_dim) | ||
| router_logits = F.linear(hidden_states, self.weight, self.bias) # (num_tokens, num_experts) | ||
| router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (num_tokens, top_k) | ||
| router_top_value = torch.nn.functional.softmax(router_top_value, dim=1, dtype=router_top_value.dtype) | ||
|
|
@@ -173,9 +140,12 @@ def __init__(self, config): | |
| self.experts = GptOssExperts(config) | ||
|
|
||
| def forward(self, hidden_states): | ||
| batch_size, sequence_length, hidden_dim = hidden_states.shape | ||
| hidden_states = hidden_states.view(-1, hidden_dim) | ||
| _, router_scores, router_indices = self.router(hidden_states) | ||
| routed_out = self.experts(hidden_states, router_indices, router_scores) | ||
| return routed_out, router_scores | ||
| hidden_states = self.experts(hidden_states, router_indices, router_scores) | ||
| hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) | ||
| return hidden_states, router_scores | ||
|
|
||
|
|
||
| class GptOssRotaryEmbedding(nn.Module): | ||
|
|
||
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.