Skip to content

liger-kernels: sync changes for transformers - #948

Merged
vasqu merged 13 commits into
mainfrom
sync-transformers-liger
Jun 12, 2026
Merged

vasqu merged 13 commits into
mainfrom
sync-transformers-liger

Conversation

@vasqu

@vasqu vasqu commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

As per title, I need a few changes for transformers to work properly

  • Signature fixes
  • Init fixes
  • Torch compile fixes

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

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review to clarify a few things



# NOTE: Not compile-friendly --> large deviations to the original implementation under compile
class LigerRMSNorm(nn.Module):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was missed --> a few lm heads do have a bias it seems

"LigerFusedLinearCrossEntropyLoss",
"LigerJSD",
"LigerKLDIVLoss",
"LigerTVDLoss",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +251 to +252
liger_rotary_pos_emb.can_torch_compile = True
LigerForCausalLMLoss.can_torch_compile = True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's worth writing these as layers now already, since we are going to deprecate FuncRepository?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 loss

but 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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good.

@vasqu

vasqu commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator Author

/kernel-bot build liger-kernels

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Build request processed.

Command: /kernel-bot build liger-kernels
Mode: build only
Target branch: pr-948
PR head SHA: e9fe2b1b291db897ac1d6f2bfcc7047499ed8585
Workflows: build.yaml, build-mac.yaml, build-windows.yaml

Dispatched (1):

@vasqu

vasqu commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator Author

/kernel-bot merge-and-upload liger-kernels

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Build request failed.

Command: /kernel-bot merge-and-upload liger-kernels
Mode: merge, build and upload
Target branch: ``
PR head SHA: e9fe2b1b291db897ac1d6f2bfcc7047499ed8585
Workflows: `build.yaml, build-mac.yaml, build-windows.yaml`

Failure: Failed to merge PR before build/upload. Check mergeability and required checks.

@vasqu

vasqu commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator Author

/kernel-bot build-and-stage liger-kernels

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Build request processed.

Command: /kernel-bot build-and-stage liger-kernels
Mode: build and stage
Target branch: pr-948
PR head SHA: e9fe2b1b291db897ac1d6f2bfcc7047499ed8585
Workflows: build.yaml, build-mac.yaml, build-windows.yaml

Dispatched (1):

@vasqu
vasqu merged commit afb82fe into main Jun 12, 2026
6 of 7 checks passed
@vasqu

vasqu commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator Author

/kernel-bot merge-and-upload liger-kernels

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Build request processed.

Command: /kernel-bot merge-and-upload liger-kernels
Mode: merge, build and upload
Target branch: ``
PR head SHA: e9fe2b1b291db897ac1d6f2bfcc7047499ed8585
Workflows: `build.yaml, build-mac.yaml, build-windows.yaml`

Merge result: PR is already merged. Continuing with build/upload.

Dispatched (1):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants