Repository navigation
liger-kernels: sync changes for transformers - #948
Conversation
vasqu
left a comment
There was a problem hiding this comment.
Self-review to clarify a few things
|
|
||
|
|
||
| # NOTE: Not compile-friendly --> large deviations to the original implementation under compile | ||
| class LigerRMSNorm(nn.Module): |
There was a problem hiding this comment.
There are a few rms norm alts, will check if this is worth it to add, e.g. for gemma iirc
| def extra_repr(self) -> str: | ||
| return f"num_channels={self.num_channels}, num_groups={self.num_groups}, eps={self.variance_epsilon}" | ||
|
|
||
| class LigerLinear(nn.Module): |
There was a problem hiding this comment.
This can be used to exchange a torch native nn.Linear but using chunked/tiled forwards and backwards. This can be seen as something similar to what the other tiled MLPs do. This won't land on main transformers immediately but I'm optimistic that it should and can
| down_proj: nn.Linear | ||
| num_shards: int | ||
|
|
||
| def _mlp_forward(self, module, x): |
There was a problem hiding this comment.
NOTE: this adds an "attribute" / self reference to something the original modules do not have --> cannot be properly exchanged via kernelize as it fails validation
| ) | ||
|
|
||
|
|
||
| def liger_rotary_pos_emb( |
There was a problem hiding this comment.
Could be used instead of rotary tbh, would need to check between FA ops and this what's more worthwhile but it was simple enough to add so why not
| # NOTE: We have this intentional graph break as we encounter issues such as IMAs and Cublas errors. | ||
| # We know that this is an optimized kernel already so there is less ways to | ||
| # fuse it either way; we rely on torch compile to go through the base model to optimize. | ||
| @torch.compiler.disable |
There was a problem hiding this comment.
Let's keep this for now, adding fake ops etc will take a bit more effort. We can always lift this restriction later tbh
| hidden_states, | ||
| lm_head_weight, | ||
| shift_labels, | ||
| bias=lm_head_bias, |
There was a problem hiding this comment.
Was missed --> a few lm heads do have a bias it seems
| "LigerFusedLinearCrossEntropyLoss", | ||
| "LigerJSD", | ||
| "LigerKLDIVLoss", | ||
| "LigerTVDLoss", |
There was a problem hiding this comment.
Like mentioned we can gradually readd some of these when actually needed. Let's keep it simple for now
| hidden_size = x.shape[-1] | ||
| # x.shape could be [bs, seqlen, in_features] or [seqlen, in_features] (moe experts) | ||
| in_features = x.shape[-1] | ||
| out_features = grad_output.shape[-1] |
There was a problem hiding this comment.
This is to support any mlp going in->out; the basis here was that we have in->in shapes which does not hold for anything arbitrary
| liger_rotary_pos_emb.can_torch_compile = True | ||
| LigerForCausalLMLoss.can_torch_compile = True |
There was a problem hiding this comment.
Maybe it's worth writing these as layers now already, since we are going to deprecate FuncRepository?
There was a problem hiding this comment.
Tried something along
class LigerForCausalLMLoss(nn.Module):
# NOTE: We have this intentional graph break as we encounter issues such as IMAs and Cublas errors.
# We know that this is an optimized kernel already so there is less ways to
# fuse it either way; we rely on torch compile to go through the base model to optimize.
@torch.compiler.disable
def forward(
self,
logits: None, # to match transformers signature
labels: torch.Tensor,
vocab_size: int, # to match transformers signature
num_items_in_batch: Optional[int] = None,
ignore_index: int = -100,
shift_labels: Optional[torch.Tensor] = None,
hidden_states: torch.Tensor | None = None,
lm_head_weight: torch.Tensor | None = None,
lm_head_bias: torch.Tensor | None = None,
**kwargs,
):
# To match signature we hide these behind the kwargs but we expect a few kwargs to exist
hidden_size = kwargs.pop("hidden_size", None)
final_logit_softcapping = kwargs.pop("final_logit_softcapping", None)
if hidden_size is None or hidden_states is None or lm_head_weight is None:
raise ValueError(
f"`LigerForCausalLMLoss` requires the LLM's weight (found `{lm_head_weight is not None}`),"
f"the last hidden state (found `{hidden_states is not None}`), and the `hidden_size`"
f"(found `{hidden_size is not None}`). Please make sure to pass the necessary kwargs."
)
applicable_params = inspect.signature(liger_fused_linear_cross_entropy).parameters
kwargs = {k: v for k, v in kwargs.items() if k in applicable_params}
if shift_labels is None:
labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
shift_labels = labels[..., 1:].contiguous()
hidden_states = hidden_states.view(-1, hidden_size)
shift_labels = shift_labels.view(-1).to(hidden_states.device)
reduction = "sum" if num_items_in_batch is not None else "mean"
loss = liger_fused_linear_cross_entropy(
hidden_states,
lm_head_weight,
shift_labels,
bias=lm_head_bias,
reduction=reduction,
ignore_index=ignore_index,
softcap=final_logit_softcapping,
return_token_accuracy=False,
return_predicted_tokens=False,
**kwargs,
)
if reduction == "sum":
loss = loss / num_items_in_batch
return lossbut the signatures don't match because we do simple func_sig = inspect.signature(func) which does not work atm. So we will need huggingface/kernels#622 to land first (as it properly checks whether something is a class or fn).
We can update afterwards, wdyt?
|
/kernel-bot build liger-kernels |
|
Build request processed. Command: Dispatched (1):
|
|
/kernel-bot merge-and-upload liger-kernels |
|
Build request failed. Command: Failure: Failed to merge PR before build/upload. Check mergeability and required checks. |
|
/kernel-bot build-and-stage liger-kernels |
|
Build request processed. Command: Dispatched (1):
|
|
/kernel-bot merge-and-upload liger-kernels |
|
Build request processed. Command: Merge result: PR is already merged. Continuing with build/upload. Dispatched (1):
|
As per title, I need a few changes for transformers to work properly
NOTE: This discards a few non-used modules/funcs in layers. We will rebuild them gradually if needed. But this is breaking either way so we will need a new version regardless