Skip to content

🚨 [Kernels] Sync to latest version - #46039

Merged
vasqu merged 26 commits into
huggingface:mainfrom
vasqu:causallm-kernels
Jun 17, 2026
Merged

vasqu merged 26 commits into
huggingface:mainfrom
vasqu:causallm-kernels

Conversation

@vasqu

@vasqu vasqu commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator

🚨 Breaking change

Breaking by design as kernels no longer accepts model type repos (e.g. see my newly builts kernels for the tests for exactly that reason). This is more of a breaking change on kernels than on us but we cannot avoid this!

General initial overview

Additional targeted issues fixed with this PR

  • Remove unnecessary logic needed for previous versions (try catch logics especially)
  • Fixes security vulnerabilities
    • register_kernel_replacements_and_fusions disregarded the context manager bypassing any safety mechanisms on lower kernel versions
      • Essentially allows any kernel to be loaded via kernel config
    • We now mostly relay a lot of this logic to the original kernels package as well
  • Allows the inclusion of metadata (version/revision/trust_remote_code)
    • For our existing kernels, this acts as BC as we fallback to version 1 which is equivalent to what we currently use
    • For new kernels, it allows user more control --> version, remote code etc
      • This is especially handled within the kernel config as a new entry style
      • Prev: Simple str of the layer name with the attached class layer dummy-kernel:DummyLayer
      • Now: Optional tuple structure to pass the necessary data (dummy-kernel:DummyLayer, {"version": 0, "trust_remote_code": True})
  • Fixed various side effects during testing
    • A lot of patching was not working as expected --> isolated tests passed but in succession failed
  • Fix kernelize pattern not inheriting the default mapping

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

looks nice!

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

BTW make sure to put benches on perfs wins /. doc

@vasqu

vasqu commented May 19, 2026

Copy link
Copy Markdown
Collaborator Author

Yep, will do 🫡 thinking about memory benchmarks mostly since this is the key behind the new loss kernel from liger

vasqu added 3 commits May 29, 2026 21:29
i red herred that maybe the registry was not properly working for fn repos, but thats all fine. still need small upstream changes tho
@vasqu vasqu changed the title [Kernels] Sync and add SwigluMLP + CausalLMLoss [Kernels] Sync to latest version and add new kernels (SwiGLU, CE) Jun 1, 2026
Billy1900 added a commit to Billy1900/sglang-omni that referenced this pull request Jun 3, 2026
…sglang 0.5.12

sglang==0.5.12 requires torch==2.11.0, torchaudio==2.11.0, and torchvision
(no hard pin from sglang, installs 0.26.0). Update all three in pyproject.toml
to match.

Also add kernels<0.15 to uv override-dependencies: kernels>=0.15 introduced a
breaking change (LayerRepository now requires version or revision) that is not
yet handled by transformers 5.6.0, causing sglang's hf_transformers_patches to
fail at import time. Tracked upstream at huggingface/transformers#46039.

Discovered while running unit tests against the upgraded stack.
@jiqing-feng

Copy link
Copy Markdown
Contributor

Hi @vasqu, thanks a lot for taking this on! 🙏

We're currently hitting the incompatibility between the latest transformers and the latest kernels, and this PR looks like exactly the fix we need, so we've been following it closely.

I completely understand it's still a Draft and depends on a few upstream pieces landing first (the kernels-community sync PRs #906 / #907 / #928, kernels#607, and the follow-up version bump). I just wanted to gently check in on the current status — is there anything still blocking it, and is there an estimated path to getting it out of Draft?

More importantly, is there anything I can help with to move this forward? A few things I'd be happy to take on:

  • Run and provide benchmarks (including the memory benchmarks for the new liger loss kernel) that @ArthurZucker requested for the docs — note that I can only test on XPU.
  • Test the compatibility of this branch against kernels>=0.15.0 on my setup and report back any issues.
  • Collaborate on the upstream kernels-community and kernels PRs that this one depends on.
  • Validate the remaining TODOs (e.g. propagating the decorator to other models / models that don't want the loss overwrite) on real models.

Just let me know what would be most useful and I'll jump on it. Thanks again for the great work! 🚀

@vasqu

vasqu commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

Hey @jiqing-feng 👋 thanks for checking in!

I was out for the past 2 days mostly so it got a bit delayed. The main concern is having a proper liger kernels version that has the proper flags. I.e. it needs some thorough testing to match the expected losses.

I think, I will split this PR a bit to ease the merge of this PR

  1. Only make syncing possible with existing kernels
  2. Move to new liger kernels to be used (swiglu etc)
    • I feel like we should add another feature here to make sure the exchange can only happen on certain conditions, e.g. no bias on linear projections (mixture of kernels and transformers side)
    • Verify the losses across kernels and compile vs eager (no compile)
  3. Then we can enable and propogate this to all the models

What I need the most help is verifying this across different stacks (torch versions, compile, etc). The development moved fast.

@vasqu

vasqu commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

Note that the kernels need to manually patched based on the PRs I opened on the kernels community. They are not uploaded atm

@jiqing-feng

jiqing-feng commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Hey @vasqu 👋 I ran a cross-stack verification on Intel XPU (Data Center GPU Max 1550) against this branch. TL;DR: everything works on XPU, including the torch.compile + kernels combo. 🎉

Environment

  • torch 2.12.0+xpu (release)
  • kernels 0.15.2 (matches the PR's >=0.15.2,<0.16 pin)
  • transformers @ this PR branch (5.8.0.dev0)
  • device: xpu, dtype: bfloat16

Coverage note

The new SwiGLUMLP (LigerSwiGLUMLP) and ForCausalLMLoss (LigerForCausalLMLoss) kernels are cuda-only in the mapping, so on XPU they fall back to the eager / Python implementations — I could not exercise the liger kernels themselves here. What this run actually validates on XPU is:

  • the framework-side changes (fused-loss fallback when logits=None, the logits is None skip, mode switching, torch.compile), and
  • the existing RMSNorm + rotary XPU kernels (kernels-community/rmsnorm, kernels-community/rotary), which load and run fine.

Results

Scenario loss diff vs eager
eager reference (use_kernels=False) 7.75389 —
ForCausalLMLoss: hidden_states path vs logits path 7.75389 0.00e+00
use_kernels=True, inference 7.75361 2.79e-04
use_kernels=True, training (logits is None ✓) 7.75362 2.65e-04
torch.compile, no kernels 7.75394 5.44e-05
torch.compile + use_kernels=True 7.75368 2.09e-04

Notes

  • The new fused-loss fallback (logits=None → compute from hidden_states + lm_head_weight) is numerically identical to the old logits path (diff = 0). Note this exercises the transformers Python fallback, not the liger CUDA kernel.
  • The RMSNorm + rotary XPU kernels load and run fine, and the torch.compile + kernels combo works without the IMA/cublas issues you saw on CUDA — losses stay within bf16 noise (~1e-4). The fused-loss path correctly skips logit materialization (logits is None) in both train and inference.
  • I couldn't exercise the cuda-only LigerForCausalLMLoss / LigerSwiGLUMLP or the memory benchmark on XPU. Happy to help validate those (and re-run on CUDA) once the patched liger kernels are uploaded — or to add XPU entries to the mapping if you'd like the liger kernels covered there too.

Repro script

"""Verification for transformers PR #46039 (SwiGLU + fused ForCausalLMLoss kernels) on Intel XPU.

Run inside an XPU container:
    HF_HOME=/path/to/cache python verify_pr46039.py
"""

import torch
import transformers
from transformers import AutoConfig, AutoModelForCausalLM
from transformers.loss.loss_utils import ForCausalLMLoss

DEVICE = "xpu" if torch.xpu.is_available() else "cpu"
DTYPE = torch.bfloat16


def build():
    cfg = AutoConfig.for_model(
        "llama", vocab_size=2048, hidden_size=512, intermediate_size=1376,
        num_hidden_layers=4, num_attention_heads=8, num_key_value_heads=4,
        max_position_embeddings=512, tie_word_embeddings=False,
    )
    torch.manual_seed(0)
    return AutoModelForCausalLM.from_config(cfg, dtype=DTYPE).to(DEVICE).eval()


def make_kernel_model(ref, train=False):
    m = build()
    m.load_state_dict(ref.state_dict())
    m.train() if train else m.eval()
    m.set_use_kernels(True)
    return m


def main():
    import kernels
    print(f"transformers {transformers.__version__} | torch {torch.__version__} | "
          f"kernels {kernels.__version__} | device {DEVICE} | dtype {DTYPE}")

    torch.manual_seed(1)
    input_ids = torch.randint(0, 2048, (2, 64), device=DEVICE)
    labels = input_ids.clone()
    ref = build()
    results = []

    # 0) eager reference
    with torch.no_grad():
        out = ref(input_ids=input_ids, labels=labels)
    ref_loss = out.loss.item()
    results.append(("eager reference (use_kernels=False)", ref_loss, None))

    # 1) new fused-loss fallback: logits=None -> compute from hidden_states + lm_head_weight
    with torch.no_grad():
        hidden = ref.model(input_ids=input_ids).last_hidden_state
    common = dict(labels=labels, vocab_size=ref.config.vocab_size)
    l_logits = ForCausalLMLoss(logits=ref.lm_head(hidden), **common).item()
    l_hidden = ForCausalLMLoss(logits=None, hidden_states=hidden,
                               lm_head_weight=ref.lm_head.weight, **common).item()
    results.append(("ForCausalLMLoss: hidden_states path vs logits path", l_hidden, abs(l_hidden - l_logits)))

    # 2) kernels, inference
    with torch.no_grad():
        out = make_kernel_model(ref)(input_ids=input_ids, labels=labels)
    results.append(("use_kernels=True, inference", out.loss.item(), abs(out.loss.item() - ref_loss)))

    # 3) kernels, training (fused loss path, logits should be None)
    out = make_kernel_model(ref, train=True)(input_ids=input_ids, labels=labels)
    tag = "use_kernels=True, training" + ("  [logits is None ok]" if out.logits is None else "  [logits NOT None FAIL]")
    results.append((tag, out.loss.item(), abs(out.loss.item() - ref_loss)))

    # 4) torch.compile, no kernels
    mc = build(); mc.load_state_dict(ref.state_dict()); mc.eval()
    with torch.no_grad():
        out = torch.compile(mc)(input_ids=input_ids, labels=labels)
    results.append(("torch.compile, no kernels", out.loss.item(), abs(out.loss.item() - ref_loss)))

    # 5) torch.compile + kernels
    with torch.no_grad():
        out = torch.compile(make_kernel_model(ref))(input_ids=input_ids, labels=labels)
    results.append(("torch.compile + use_kernels=True", out.loss.item(), abs(out.loss.item() - ref_loss)))

    print(f"\n{'scenario':<52}{'loss':>12}{'diff vs eager':>16}")
    print("-" * 80)
    for name, loss, diff in results:
        diff_s = "-" if diff is None else f"{diff:.2e}"
        print(f"{name:<52}{loss:>12.5f}{diff_s:>16}")


if __name__ == "__main__":
    main()

@vasqu

vasqu commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator Author

@jiqing-feng I think they could potentially work on XPU as well, just need to adjust the mapping to add them to XPU as well. I expect this to work OOB as it's triton and not somethig device specific. But that's already nice news!! 🥳

I also wanted to check the tiled swiglu version, especially across different seq lens.

@vasqu vasqu changed the title [Kernels] Sync to latest version and add new kernels (SwiGLU, CE) [Kernels] Sync to latest version Jun 11, 2026
@vasqu

vasqu commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Failing CI is related to something different opening another PR to fix (see #46695)

@vasqu vasqu changed the title [Kernels] Sync to latest version 🚨 [Kernels] Sync to latest version Jun 16, 2026
Comment on lines -156 to +155
@use_kernel_forward_from_hub("Llama4TextMoe")
# @use_kernel_forward_from_hub("Llama4TextMoe")

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.

should we make it use experts impl now ? so that it wouldn't get extremely slower for users

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

yeah, low prio as usage is not that high

Comment on lines 89 to 96
if not is_kernels_available():
raise ImportError(
"finegrained-fp8 kernel requires the `kernels` package. Install it with `pip install -U kernels`."
"finegrained-fp8 kernel requires the `kernels` package. "
f"Please install a compatible version ({KERNELS_MIN_VERSION} <= version < {KERNELS_MAX_VERSION}), "
f"e.g. `pip install kernels=={KERNELS_MIN_VERSION}`"
)

kernel = lazy_load_kernel("finegrained-fp8")

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.

does lazy_load_kernel raise the error when kernels is not available or return None ? if it raises it maybe we don't need the check above

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.

Nope, it has a fallback mechanism so it's not as clear as doing it this way

@IlyasMoutawwakil IlyasMoutawwakil left a comment

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.

LGTM thanks !

@github-actions

Copy link
Copy Markdown
Contributor

Comment on lines +87 to +88
f"Please install a compatible version ({KERNELS_MIN_VERSION} <= version < {KERNELS_MAX_VERSION}), "
f"e.g. `pip install kernels=={KERNELS_MIN_VERSION}`"

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.

We could also recommend pip install transformers[kernels] and remove the MIN/MAX_VERSION imports.

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.

Would like to keep, at some point we want to remove the dedicated kernels tbh so this seems more explicit

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice it looks cleaner!

Comment on lines -156 to +155
@use_kernel_forward_from_hub("Llama4TextMoe")
# @use_kernel_forward_from_hub("Llama4TextMoe")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

yeah, low prio as usage is not that high

Comment thread tests/kernels/test_kernels.py Resolved
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: llama4, mra, rwkv, sam3_video, yoso, mxfp4

@vasqu
vasqu enabled auto-merge June 17, 2026 15:40
@vasqu
vasqu added this pull request to the merge queue Jun 17, 2026
Merged via the queue into huggingface:main with commit 9fd7b67 Jun 17, 2026
102 checks passed
@vasqu
vasqu deleted the causallm-kernels branch June 17, 2026 15:59
stevhliu pushed a commit to stevhliu/transformers that referenced this pull request Jul 30, 2026
* working version --> need to fix upstream kernels to match signature and everything (pass validate layer must pass)

* add swiglu mlp

* well well well, rms norm was the culprit all along...

i red herred that maybe the registry was not properly working for fn repos, but thats all fine. still need small upstream changes tho

* fix mode logic and bump version (will need another bump)

* no longer maintained

* fix switching mode only on changing base flags (train<->eval)

* new format to be used

* revert this one

* bump version

* update to newest state

* revert actual usage on models

* sync all versions and fix kernels config

* current changes, only need to update the other kernels now

* try this

* oops

* last fixes

* also allow updating remote code trust

* small refinement to kernelize pattern through set use kernels always forcing to inherit the proper mapping

* oops

* nit

* less dirty

* make it a revision just to be sure
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.

6 participants