Repository navigation
🚨 [Kernels] Sync to latest version - #46039
Conversation
…nd everything (pass validate layer must pass)
|
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
left a comment
There was a problem hiding this comment.
BTW make sure to put benches on perfs wins /. doc
|
Yep, will do 🫡 thinking about memory benchmarks mostly since this is the key behind the new loss kernel from liger |
i red herred that maybe the registry was not properly working for fn repos, but thats all fine. still need small upstream changes tho
Kernels] Sync and add SwigluMLP + CausalLMLossKernels] Sync to latest version and add new kernels (SwiGLU, CE)
…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.
|
Hi @vasqu, thanks a lot for taking this on! 🙏 We're currently hitting the incompatibility between the latest I completely understand it's still a Draft and depends on a few upstream pieces landing first (the More importantly, is there anything I can help with to move this forward? A few things I'd be happy to take on:
Just let me know what would be most useful and I'll jump on it. Thanks again for the great work! 🚀 |
|
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
What I need the most help is verifying this across different stacks (torch versions, compile, etc). The development moved fast. |
|
Note that the kernels need to manually patched based on the PRs I opened on the kernels community. They are not uploaded atm |
|
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 Environment
Coverage noteThe new
Results
Notes
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() |
|
@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. |
Kernels] Sync to latest version and add new kernels (SwiGLU, CE)Kernels] Sync to latest version
|
Failing CI is related to something different opening another PR to fix (see #46695) |
Kernels] Sync to latest versionKernels] Sync to latest version
| @use_kernel_forward_from_hub("Llama4TextMoe") | ||
| # @use_kernel_forward_from_hub("Llama4TextMoe") |
There was a problem hiding this comment.
should we make it use experts impl now ? so that it wouldn't get extremely slower for users
There was a problem hiding this comment.
yeah, low prio as usage is not that high
| 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") |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Nope, it has a fallback mechanism so it's not as clear as doing it this way
…forcing to inherit the proper mapping
|
View the CircleCI Test Summary for this PR: |
| f"Please install a compatible version ({KERNELS_MIN_VERSION} <= version < {KERNELS_MAX_VERSION}), " | ||
| f"e.g. `pip install kernels=={KERNELS_MIN_VERSION}`" |
There was a problem hiding this comment.
We could also recommend pip install transformers[kernels] and remove the MIN/MAX_VERSION imports.
There was a problem hiding this comment.
Would like to keep, at some point we want to remove the dedicated kernels tbh so this seems more explicit
ArthurZucker
left a comment
There was a problem hiding this comment.
Nice it looks cleaner!
| @use_kernel_forward_from_hub("Llama4TextMoe") | ||
| # @use_kernel_forward_from_hub("Llama4TextMoe") |
There was a problem hiding this comment.
yeah, low prio as usage is not that high
|
[For maintainers] Suggested jobs to run (before merge) run-slow: llama4, mra, rwkv, sam3_video, yoso, mxfp4 |
* 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
🚨 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
FuncRepository] Add ability of detecting flags kernels#607Kernels] Add new kernels to models: CE, Swiglu, Geglu(, Linear) #46575Additional targeted issues fixed with this PR
register_kernel_replacements_and_fusionsdisregarded the context manager bypassing any safety mechanisms on lower kernel versionsdummy-kernel:DummyLayer(dummy-kernel:DummyLayer, {"version": 0, "trust_remote_code": True})