Repository navigation
feat(device_type): add Ascend NPU device detection - #10686
Conversation
get_device_type() and get_device_count() did not recognize Ascend NPU devices, falling through to raise NotImplementedError even though torch.accelerator correctly reports 'npu' as the active accelerator. This adds: - NPU detection in get_device_type() via hasattr(torch, 'npu') and the torch.accelerator accelerator branch - NPU device count via torch.npu.device_count() in get_device_count() - NPU stats display in get_device_stats() This is the first step towards NPU support: correct device detection at import time, removing the misleading NotImplementedError.
|
Confirmed get_device_type() in unsloth/device_type.py has no NPU branch today and falls through to the NotImplementedError, and that get_device_count() returns 1 for it. Will get this reviewed. |
|
Checked this against unsloth/device_type.py and the new npu branches sit alongside the existing cuda/xpu ones without touching them, so import stops raising on Ascend hosts. Since detection alone does not make the rest of the stack NPU ready, could you say which paths you actually ran end to end on the 910B before I review? |
Probing the new backend needs to be defensive, because get_device_type() runs at import time for every user, not just Ascend ones. - Probe npu after xpu, not before it. A host exposing both used to select xpu and must keep doing so. - Add npu_is_available(), which guards every probe. torch_npu without CANN or a driver raises on import (missing libascend_hal.so) and torch.npu.is_available() can raise rather than return False, either of which would have escaped get_device_type() and broken `import unsloth` on CUDA, ROCm and XPU hosts too. - Detect Ascend on torch_npu < 2.5.1 as well. Only 2.5.1 onwards registers torch.npu via the torch.backends entry point during `import torch`, so hasattr(torch, "npu") alone missed older installs and anyone running with TORCH_DEVICE_BACKEND_AUTOLOAD=0. - Drop the `accelerator == "npu"` early return in favour of the existing "torch is broken" RuntimeError. Returning "npu" there meant torch.npu was missing or unusable, so it only deferred the failure to torch.npu.device_count() as an unhelpful AttributeError. - Report the toolkit in the stats snippet like the cuda and xpu arms do, instead of repeating the device name that is already in `name`. Adds six tests covering cuda-over-npu, xpu-over-npu, a raising is_available, an unavailable device, blank device names, and the count/stats/cache dispatch.
"Unsloth currently only works on NVIDIA, AMD, Intel and Ascend NPU GPUs." told a
user what is supported but not what they were running, which is the part they
need in order to report it. Where torch can name the accelerator, say it:
Unsloth does not currently work on privateuseone.
torch.accelerator only exists from torch 2.6, so below that there is no name to
report and the message says "this device".
b559f6c to
4fda0d4
Compare
|
@danielhanchen Thanks for the question. This PR (#10686) only adds NPU detection to
The full end-to-end training pipeline on NPU (model loading, forward/backward, LoRA adapters, generation) is a much larger scope that we are exploring via the RFC #10772 thread — that's where the community can discuss the preferred architecture for a proper NPU backend. This PR alone merely makes |
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
DEVICE_TYPE npu fell through to the else arm, which builds CUDA_STREAMS with torch._C._cuda_getCurrentRawStream. An Ascend build has no CUDA runtime for that, so a positive DEVICE_COUNT raised 'Torch not compiled with CUDA enabled' during import unsloth. Take the same empty-stream arm mlx already takes; the cuda, hip and xpu arms are untouched.
get_statistics runs on every FastLanguageModel.from_pretrained, and its memory probe sent every non-XPU device to torch.cuda.get_device_properties(0), which an Ascend build has no CUDA runtime for. The xpu and cuda arms are unchanged.
Two names in kernels/utils.py had no npu arm, and rope_embedding.py imports both at module scope: - torch_gpu_device was bound only for cuda/hip and xpu under DEVICE_COUNT > 1, so a multi-NPU host left the name undefined and import unsloth failed with an ImportError. - torch_device_stream fell back to torch.cuda.current_stream, which the RoPE forward synchronizes on, reaching a CUDA backend an Ascend build does not have. torch_npu exports both device and current_stream from torch_npu/npu/__init__.py and registers them via torch._register_device_module. The cuda, hip and xpu arms are unchanged.
Two more places that only special-cased xpu: - torch_amp_custom_fwd/bwd kept the cuda default, and a device_type that does not match the running device makes those decorators inert rather than raising (pytorch#165730), so the fused LoRA autograd functions would silently lose autocast on NPU. torch_npu's own deprecated wrappers delegate to torch.amp.custom_fwd(device_type='npu'), which is the documented form. - prepare_device_map built an npu:<local_rank> device map but called set_device only for cuda and xpu, so every torchrun worker kept NPU 0 as its current device while its model sat on another rank. The cuda, hip and xpu arms are unchanged.
Neither bf16 dispatch had an npu arm, so SUPPORTS_BFLOAT16 stayed at its module-level False. Loaders consult is_bfloat16_supported(), so a bf16-capable Ascend host defaulted to float16 and rewrote an explicit dtype = torch.bfloat16 while warning that the device does not support it. torch.npu.is_bf16_supported is exported by torch_npu, so ask it rather than hardcoding a capability. The cuda, hip and xpu arms are unchanged.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4b10f6434c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # After xpu: a host exposing both keeps selecting xpu, as it did before Ascend. | ||
| elif npu_is_available(): | ||
| return "npu" |
There was a problem hiding this comment.
Add NPU detection to the device source used by import
On an Ascend-only host with the declared unsloth_zoo>=2026.9.3 dependency, import unsloth still fails before this branch is reached: unsloth/__init__.py imports _gpu_init, and _gpu_init.py:218-225 obtains DEVICE_TYPE from unsloth_zoo.device_type, whose 2026.9.3 implementation has no torch.npu probe and raises the original NVIDIA/AMD/Intel-only NotImplementedError. The NPU detection therefore also needs to be implemented in the Zoo device source with an appropriate dependency bump, or _gpu_init must source these constants from this module.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and this is the third time it has been raised; my earlier answers were removed by a thread-pruning pass, so restating it here for the record.
Reproduced on a simulated Ascend host against unsloth_zoo 2026.9.3:
File ".../unsloth_zoo/__init__.py", line 383, in <module>
from .device_type import (
File ".../unsloth_zoo/device_type.py", line 405, in <module>
DEVICE_TYPE : str = get_device_type()
NotImplementedError: Unsloth currently only works on NVIDIA, AMD and Intel GPUs.
On the second of your two remedies: sourcing the constants in _gpu_init from this module does not work. _gpu_init.py imports unsloth_zoo before it reaches the device_type import, and the zoo runs DEVICE_TYPE = get_device_type() at module scope, so it raises first regardless of where _gpu_init later reads the value from. I checked unsloth-zoo main as well, and it still has no npu branch.
That leaves your first remedy, which cannot land in this repository: it needs a companion unsloth_zoo PR plus a dependency bump. Keeping this item open and unfixed on purpose rather than marking it resolved. Everything in this PR is inert on non-Ascend hosts, which the cuda, hip, xpu, mlx and cpu paths in the test suite cover.
| # After xpu: a host exposing both keeps selecting xpu, as it did before Ascend. | ||
| elif npu_is_available(): | ||
| return "npu" |
There was a problem hiding this comment.
Route the public memory helpers through torch.npu
Once an NPU is selected, the public GPU-memory API remains unaware of it: unsloth/__init__.py:1557-1578 checks only XPU and CUDA, so get_gpu_memory_stats() reports Unknown GPU, zero usage, and a fabricated 1 GiB total on Ascend, while clear_gpu_memory() at lines 1580-1589 silently does nothing. NPU callers relying on these exported helpers receive incorrect capacity data and cannot release the NPU cache; both paths should dispatch to torch.npu like the helpers added in this change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. get_gpu_memory_stats() checked xpu then cuda and otherwise returned _UnslothDeviceStats('Unknown GPU', 0) with a fabricated 1.0 GiB total, and clear_gpu_memory() silently no-opped on npu. Both now dispatch to torch.npu, with the npu probe placed last in each so no existing device changes which branch it takes. Verified the cuda path still reports the real device and totals; 3199 device tests pass.
get_gpu_memory_stats() checked only xpu and cuda, so an Ascend host fell through to 'Unknown GPU' with zero usage and a fabricated 1 GiB total, and clear_gpu_memory() silently did nothing. The npu probe goes last in both, so no existing device changes which branch it takes.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a3a8ce625f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| elif DEVICE_TYPE == "npu": | ||
| # A device_type that does not match the running device makes these decorators inert | ||
| # rather than raising (pytorch#165730), so leaving the "cuda" default would silently | ||
| # drop autocast in the fused LoRA autograd functions. | ||
| torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "npu") | ||
| torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "npu") |
There was a problem hiding this comment.
Preserve the legacy AMP path for older NPU Torch
On Ascend installations paired with PyTorch 2.2 or 2.3, this branch overwrites the version-gated legacy decorators selected at lines 45–47 with torch.amp.custom_fwd/custom_bwd, which are unavailable before PyTorch 2.4, so importing the kernel module fails with AttributeError. The repository still supports these Torch versions, and the new detector explicitly imports older torch_npu releases, so either enforce a 2.4+ NPU floor or dispatch to the older NPU AMP decorators; the generic NPU path in models/_utils.py needs the same treatment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and this one was mine: the npu arm I added in an earlier round is the only unguarded caller of torch.amp.custom_fwd in that block. xpu is protected by the 2.6 floor at the top of kernels/utils.py, cuda by the explicit < 2.4 legacy branch, and npu had neither, so a torch_npu built against 2.2 or 2.3 would have hit AttributeError mid-import. The detector deliberately reaches older torch_npu releases, so those versions really are reachable.
Took your first remedy in b9b9b16, a 2.4 floor mirroring the xpu one, rather than dispatching to the legacy torch.npu.amp decorators, because I cannot verify the old torch_npu AMP surface without that hardware and would rather fail with a clear message than guess.
models/_utils.py needed it too, as you said, though for a slightly different reason: its generic else already passes device_type = DEVICE_TYPE_TORCH, which is correct for npu, it simply had no version guard. Added a named npu arm there with the same floor.
Checked by exercising the gate across versions: npu on 2.3 raises the floor error, npu on 2.4+ binds amp.custom_fwd(npu), cuda on 2.3 still takes the legacy torch.cuda.amp path unchanged, and cuda/xpu on current torch are unchanged. 3199 device tests pass.
torch.amp.custom_fwd(device_type=...) only exists from 2.4, and the npu arms were not version-gated the way the cuda one is, so a torch_npu built against 2.2 or 2.3 would hit an AttributeError mid-import. The detector deliberately supports older torch_npu releases, so those versions are reachable. Raise the same kind of clear floor xpu already has, in both kernels/utils.py and models/_utils.py. The legacy torch.cuda.amp path for cuda on torch < 2.4 is untouched.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Problem
On Ascend NPU devices, importing
unslothcrashes at module load:torch.accelerator.current_accelerator()correctly reports"npu"on Ascend, butget_device_type()had no NPU branch, so it fell through toNotImplementedError.get_device_count()also returned the wrong value (1) for NPU since it only special-cased CUDA/XPU.Fix
Add Ascend NPU device detection:
get_device_type(): recognizetorch.npu.is_available()and the"npu"accelerator branch, returning"npu"get_device_count(): returntorch.npu.device_count()for NPUget_device_stats(): display Ascend NPU device info instead of the CUDA fallbackThis is device-agnostic (uses the same
hasattr/accelerator pattern already present) and is the first step toward enabling NPU support.Verification (Ascend 910B NPU, torch 2.14.0a0 + torch_npu)
Changes: 10 insertions, 1 deletion in
unsloth/device_type.py.