Repository navigation
Studio: honour MIG masks and size MIG cards by their slice - #13927
Conversation
A MIG UUID in CUDA_VISIBLE_DEVICES read as no mask in the llama.cpp nvidia-smi probe, so the fit used every whole card and the pin rewrote the child mask to a physical index. Route unresolvable masks and MIG cards to the NVML probe (slice memory, MIG uuids for the child) and keep the inherited mask when the pinned ids cannot be mapped back to it. The physical GPU count also counted MIG instance rows of nvidia-smi -L as GPUs, and auto-select ranked a MIG card by whole-card free memory.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d087ddb3da
ℹ️ 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".
| ``GPU N:`` row in ``nvidia-smi -L``). CUDA sees such a card as one slice, so its | ||
| ``--query-gpu`` memory is the whole card's, not the device's. Empty on failure.""" |
There was a problem hiding this comment.
Preserve multiple MIG instances on R570 and newer drivers
On R570+ hosts, CUDA can enumerate multiple MIG instances from separate GPU instances on the same physical card, so treating every MIG-enabled card as exactly one CUDA device drops valid devices. The new NVML path compounds this because _nvml_rows_visible() deduplicates rows by their shared physical index, causing memory sizing and child pinning to retain only the first slice when CUDA_VISIBLE_DEVICES names multiple slices from one card. Represent the visible MIG instances independently rather than collapsing them to the parent index.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9f8b251. On an R570+ driver (read from the NVML probe's driver_version) the visible slices of a card now merge into one row: memory is the sum of the slices, capped at the card's own reading, and the child is pinned to every slice UUID. Older drivers keep the single slice. Covered by TestR570EnumeratesEverySlice (no mask, 0, and MIG-a,MIG-b) plus a pre-R570 guard.
| _cvd = os.environ.get("CUDA_VISIBLE_DEVICES") | ||
| if allowed is None and _cvd is not None and _cvd.strip(): | ||
| # A MIG / unresolvable UUID mask names devices these rows cannot be | ||
| # matched to: listing every card sizes against GPUs the parent hid. | ||
| # The NVML branch names slices and uuids. | ||
| gpus = [] |
There was a problem hiding this comment.
Preserve CUDA numeric-prefix mask parsing
When CUDA_VISIBLE_DEVICES uses a numeric-prefix token accepted by CUDA, such as 1gpu2, _get_parent_visible_gpu_spec() deliberately resolves it to GPU 1, but _visible_devices_mask() returns None and this new branch discards all nvidia-smi rows. _nvml_rows_visible() also rejects the token, so installations without torch fall through to no GPU even though llama.cpp can see GPU 1; use the same CUDA numeric-prefix parsing already implemented in the hardware visibility parser before declaring the mask unmappable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9f8b251. When the plain parse fails, _get_gpu_memory falls back to _resolve_visible_physical_ids(), the same strtoul-style reading the hardware visibility code uses, so 1gpu2 is GPU 1 and 1,2,abc is GPUs 1 and 2. _nvml_rows_visible reads a numeric prefix the same way. Test: test_a_numeric_prefix_mask_keeps_its_cards.
| except Exception: | ||
| return set() | ||
| if result.returncode != 0 or not isinstance(result.stdout, str): | ||
| return set() |
There was a problem hiding this comment.
Treat a failed MIG inventory as unknown
If nvidia-smi --query-gpu succeeds but the separate cached nvidia-smi -L call times out or fails, get_mig_gpu_indices() returns the same empty set as a confirmed non-MIG host. Both new callers then trust the whole-card memory row instead of taking the NVML path, so a MIG slice can be sized and auto-selected as though it had the parent card's full VRAM. Return a distinguishable unknown result on probe failure and make placement fall back conservatively.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping this as is. If nvidia-smi -L fails, both callers take exactly the pre-PR path and size from the --query-gpu rows, so a failed probe never does worse than main and never drops a card. Treating a failed -L as unknown would route every transient hiccup through an extra NVML subprocess and could swap a good reading for none.
| else: | ||
| from . import nvidia as _smi_mod | ||
| count = _smi_mod.get_physical_gpu_count() | ||
| # MIG slices are indented `-L` rows under their card, not GPUs to offer. | ||
| count = _nvidia_physical_gpu_row_count() |
There was a problem hiding this comment.
Replace a logical fallback count when SMI recovers
On a MIG host where nvidia-smi -L is unavailable during startup, the torch fallback may cache the number of visible MIG instances—for example 7—as _physical_gpu_count. When SMI later recovers, this helper returns the corrected physical count of 1, but _run_physical_gpu_count_probe() rejects every count <= previous, so the cache is never corrected and the picker permanently exposes nonexistent physical IDs. A first SMI-confirmed result should replace a count whose _physical_gpu_count_from_smi flag is false even when it is lower.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9f8b251. The first nvidia-smi answer of 1 or more now replaces a count that came from the torch fallback, even when it is lower. Once the count is SMI-confirmed it still only grows. Test: test_a_lower_smi_count_replaces_a_torch_count.
| if nvidia.get_mig_gpu_indices() & {g[0] for g in gpus}: | ||
| # A MIG card is one slice to CUDA, its row the whole card. | ||
| gpus = [] |
There was a problem hiding this comment.
Retain non-MIG rows when slice probing fails
On a mixed host, detecting one MIG-enabled card clears the entire gpus list, including valid whole-card rows for every non-MIG GPU. If the NVML child probe is disabled, unavailable, or returns an unreadable slice, the later fallbacks can therefore report no GPU at all on a no-torch installation even though the ordinary cards were sized successfully by nvidia-smi. Preserve the non-MIG rows and replace only the detected MIG indices with NVML slice readings.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9f8b251. Only the MIG card's row is swapped for its NVML slice reading; whole cards keep their nvidia-smi rows. A MIG card with no slice reading is skipped, matching how auto-select treats unknown memory, and if every reading fails on a MIG-only host the nvidia-smi rows are returned as before, so the list is never empty. Tests: test_whole_cards_survive_a_missing_slice_reading and test_a_mig_only_host_without_any_reading_keeps_the_card_rows.
…ix masks when MIG telemetry fails
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9f8b2518ec
ℹ️ 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".
| out = dict(slices[0], uuid = ",".join(str(s.get("uuid", "")) for s in slices)) | ||
| for key in ("memory_total_mib", "memory_free_mib"): | ||
| try: | ||
| total = sum(int(s.get(key) or 0) for s in slices) |
There was a problem hiding this comment.
Group R570 MIG rows by GPU instance before summing
On R570+ hosts where one GPU instance is subdivided into multiple compute instances, this sums every NVML child sharing the physical index even though CUDA exposes only one CI per GI; those CIs also share the GI's memory, so the resulting free/total budget can be multiplied and model placement can select a load that immediately OOMs. NVIDIA's MIG enumeration rules explicitly limit enumeration to one CI per GI, so the probe needs GI identity and must merge at most one CI from each GI rather than every child of the card.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 17ab319. The NVML probe now records each MIG slice's GPU instance id, and on R570+ the visible slices are summed one per GPU instance, since compute instances of one GPU instance share its memory. When the id is unavailable there is no sum at all, so the reading never exceeds a single slice.
| and mask == ",".join(str(int(i)) for i in gpu_indices) | ||
| and LlamaCppBackend._visible_devices_mask("CUDA_VISIBLE_DEVICES") is None | ||
| and LlamaCppBackend._visibility_mask_is_unmappable() | ||
| ): | ||
| return None |
There was a problem hiding this comment.
Narrow multi-MIG masks to the selected ordinals
When the NVML probe is unavailable or returns no usable inventory on an R570+ process inheriting multiple MIG UUIDs, the torch fallback still returns relative ordinals and _select_gpus can choose only one of them, but returning None here preserves every UUID in the inherited mask. The launch then records and sizes placement for the selected ordinal while llama.cpp sees all inherited MIG devices, so it may consume a slice that auto-placement deliberately omitted or apply a one-device split to a multi-device child; map selected relative ordinals back to the ordered MIG tokens instead of abandoning the pin.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 17ab319. When the inherited mask is all MIG- entries and torch enumerated every one of them, the child is pinned to the MIG- entries behind the picked torch ordinals instead of the whole mask. Any other shape keeps the inherited mask as before.
…-MIG mask to torch's picked ordinals
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17ab319a56
ℹ️ 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".
| from core.inference.llama_cpp import LlamaCppBackend | ||
| slices = {idx: (free, total) for idx, free, total in LlamaCppBackend._get_gpu_memory_nvml()} |
There was a problem hiding this comment.
Preserve logical MIG ordinals in auto-selection
On R570+ hosts where one physical MIG card contains multiple GPU instances, _get_gpu_memory_nvml() now returns their summed memory under one physical index, and this comprehension passes that collapsed row into the generic selector. Consequently, auto-selection returns a one-element gpu_ids list even though CUDA enumerates one device per GI, as documented by NVIDIA. Fresh evidence after the llama.cpp merge fix is the generic training path: worker.py:4541 uses len(gpu_ids) as the visible-device count and therefore bypasses its required multi-GPU vision/audio budget guard, while _device_budget_gb() at worker.py:1836 cannot map the additional MIG ordinals and may apply another physical card's budget. Preserve the visible MIG ordinal mapping here, or teach generic workers that one selected physical index expands to multiple CUDA devices.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e94c1cd. Auto-selection now reads the NVML rows without the R570 merge and budgets the smallest GPU instance of the card, since a training worker takes one device per selected id. The summed reading stays only on the llama.cpp path, where the child is pinned to every slice UUID and can use all of them. Test: test_auto_select_budgets_one_r570_gpu_instance_not_the_sum.
| if IS_ROCM or not devices: | ||
| return devices |
There was a problem hiding this comment.
Skip the NVIDIA MIG overlay for XPU selection
When Studio selects the Intel XPU backend on a hybrid host that also contains a MIG-configured NVIDIA card, get_visible_gpu_utilization() returns torch.xpu devices, but this guard only excludes ROCm and therefore probes NVIDIA MIG state anyway. Since both inventories normally start at index 0, the intersection succeeds and the helper replaces the XPU's memory with the NVIDIA slice's NVML values—or marks the XPU memory unknown when that probe fails—causing auto-selection to rank or reject the Intel device using unrelated hardware. Gate this overlay on get_device() == DeviceType.CUDA in addition to excluding ROCm.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e94c1cd. The MIG overlay now runs only when the selected backend is CUDA, so XPU (and ROCm, as before) device rows are never matched against NVIDIA indices. Test: test_mig_overlay_skips_a_non_cuda_backend.
…erlay only on the CUDA backend
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
… of summing R570 instances; torch ordinals never map through cached NVML rows; a repeated mask index hides every GPU
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…ctually imports (#1811) ## Summary `Core zoo (HF=default + TRL=default)` on unslothai/unsloth#13927 failed in the serial MLX group: ``` tests/test_mlx_speculative.py:330: in test_only_the_verify_forward_is_built_as_a_verify_block assert seen == [True] and not marked() E assert ([False] == [True] ``` The test was added in #1757. It went unnoticed because the MLX group runs in the same step after the main xdist pass, and `bash -e` stops the step when the main pass fails. Until #1808 and #1809 the main pass failed on every recent run, so the MLX group never ran. Now that the main pass is green, this failure shows up on every run. ## Cause It reproduces on zoo main (81ff9b3) by running the MLX group exactly as CI does (`tests/test_mlx_*.py` minus the three isolated files, serially, alphabetical). In that process: - `from unsloth_zoo.mlx import inference` returns the package attribute. - `sys.modules["unsloth_zoo.mlx.inference"]` is a different module object. The shim tests that run earlier in the group purge and restore `unsloth_zoo.mlx.*`, so the package attribute and `sys.modules` end up holding different copies. `SpeculativeEngine._verify` does `from .inference import verify_block_attention`, which resolves through `sys.modules`. So the product does set the marker, but on the other copy's `_VERIFY_STATE`, and the test reads the stale one. No single earlier file causes it on its own (checked pairwise against each preceding MLX file), only the full sequence. The product path is fine: at runtime nothing purges these modules. ## Change The test now gets `inference` via `importlib.import_module("unsloth_zoo.mlx.inference")`, the same `sys.modules` entry `_verify` imports from, so it reads the state the product writes. ## Testing CI's MLX group command, locally, CPU torch with the MLX shim: - **Before:** 1 failed, 2967 passed (the CI assertion). - **After:** 2968 passed, 560 skipped. - **Sabotage:** making `verify_block_attention` set `attention = False` fails the test again inside the full group, so it still guards the marker.
|
pre-commit.ci run |
# Conflicts: # studio/backend/core/inference/llama_cpp.py
…MIG set (unslothai#14017) ## Problem Two ordinary-host regressions came in with the Studio MIG change (unslothai#13927), both on hosts that have no MIG at all. A valid whole-GPU UUID mask was treated as unresolved in the llama.cpp memory probe whenever the ordinal resolvers could not map it. That happens under `CUDA_DEVICE_ORDER=FASTEST_FIRST`, since those resolvers only trust UUIDs under `PCI_BUS_ID`. It also happens when the separate `index,uuid` query fails while the memory query succeeds. Either way the successful nvidia-smi rows were thrown away. With NVML unavailable the probe then fell through to `torch.cuda.mem_get_info`, which creates a CUDA context, or reported no GPU when torch was absent. The embedding server's auto GPU check reads this result, so it could switch to CPU. Every successful NVIDIA memory probe and every auto selection also called `get_mig_gpu_indices()`. Each call resolved the nvidia-smi path, copied the child environment, went through the query wrapper and parsed `nvidia-smi -L`. That cost was added to the VRAM settle poll loop on every host. ## Fix The memory probe now asks for `index,memory.free,memory.total,uuid` in one nvidia-smi call. A whole-GPU UUID mask that the ordinal resolvers cannot map is matched against those UUIDs. A UUID names its card under any device order, so this needs no second query and no CUDA ordering. When nvidia-smi gives no UUID column, the mask is checked with the separate UUID query and stays unresolved if that cannot verify it. When auto fit picks a subset of such a mask, the child is pinned to those cards' UUIDs (whole cards only, never a MIG card) instead of keeping the whole inherited mask, and a reordered mask orders the child the same way a numeric mask already did (Unsloth's tensor split is moved with it; a pass-through split keeps ascending order). MIG masks, unknown UUIDs and repeated tokens still skip the whole-card rows, so the conservative MIG handling is unchanged. The numeric-prefix resolver now runs only after the in-row UUID match, so a UUID mask no longer triggers the extra `index,uuid` query here. The MIG set is one small cache entry with a simple rule: every `nvidia-smi -L` probe takes a sequence number when it starts, and only the latest-started probe of the current gpu_query static generation may replace the entry, whatever its outcome. A good answer lives for gpu_query's static TTL from the moment its listing was taken (60 seconds by default, `UNSLOTH_GPU_QUERY_STATIC_TTL` honoured, including 0). A failed, empty, superseded or invalidated listing is "unknown" and is retried after at most 5 seconds. `get_mig_gpu_indices_or_none()` returns None while discovery is unknown and a set (empty only for a real "no MIG" answer) otherwise; `get_mig_gpu_indices()` keeps returning an empty set for unknown. The physical GPU count probe already runs `nvidia-smi -L` and publishes through the same path, so a warm memory poll is a generation and age compare with no subprocess and no lock. Placement uses the unknown-aware lookup: when discovery is unknown it reads NVML (slice for a MIG card, the same reading for a whole card), and when NVML also has nothing it keeps the CLI rows and clears any cached NVML rows, without touching CUDA. A CLI answer with no MIG cards also retires cached NVML rows. A UUID mask is cut at its first empty entry, as CUDA reads it, and without a uuid column only a one-card mask resolves. UUID subset pinning uses the MIG classification the memory probe recorded with its uuid rows, so a later failed or uncached recheck cannot widen the child to the whole inherited mask; when that snapshot is itself unknown, cards the same probe's NVML rows mark as MIG are pinned to their slice, never by the whole-GPU uuid. ## Tests New tests in `studio/backend/tests/test_mig_gpu_masks.py`. All of them fail on current main and pass with this change, except the unknown-UUID guard, which passes on both: - A whole-GPU UUID mask (full, short prefix, lowercase) under `FASTEST_FIRST` on a single non-MIG card returns the nvidia-smi row and never calls the torch probe. - The same mask under `PCI_BUS_ID` still reads its card when the separate `index,uuid` query fails and NVML is unavailable. - A two-card UUID mask under `FASTEST_FIRST` on a three-card host keeps only its own cards. - An unknown UUID still ignores the whole-card CLI rows. - With no UUID column, a token is mapped only when the UUID query verifies it; an unknown UUID or a failed query stays unresolved. - A subset of a FASTEST_FIRST UUID mask pins the child by UUID, a card outside the mask is never pinned, and a MIG card keeps the inherited mask. - A MIG listing raced by `invalidate_static` is re-read on the next call. - A UUID subset stays pinned when the MIG recheck after the memory probe fails, and a card the probe's NVML rows mark as MIG is pinned to its slice. - A MIG set served from gpu_query's cache keeps that listing's age; a failed listing is unknown and is retried after the 5 second backoff, not on every poll. - A reordered FASTEST_FIRST UUID mask reorders the pinned child ids to the mask order. - The MIG set follows `UNSLOTH_GPU_QUERY_STATIC_TTL`, including 0. - A lowercase GPU- or MIG- uuid on a MIG card gets its NVML slice reading and pins the child to that slice. - Three memory polls plus three auto-selection overlays run `nvidia-smi -L` once. After the physical count probe they run it zero more times. - `get_mig_gpu_indices` stays cached until the static generation moves. The existing MIG suites and the related GPU memory, NVML fallback, physical count, system poll, SM gate, VRAM settle, unified memory, Tegra and gpu_query cache suites pass on both base and head. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
Studio mishandled NVIDIA MIG in three places:
CUDA_VISIBLE_DEVICES=MIG-<uuid>(or the oldMIG-GPU-<uuid>/gi/ciform) was treated as "no mask" by llama.cpp's GPU sizing._get_gpu_memorythen sized the load against whole 40 / 80 GB cards, and the pin rewrote the child's mask to"0". The child could land on a different slice or the whole parent card.CUDA_VISIBLE_DEVICES=2, which leaves the worker with no device.Fix
CUDA_VISIBLE_DEVICESvalue that does not map to nvidia-smi rows (MIG UUIDs, mixedGPU-a,MIG-b, an unknown UUID) no longer reads the whole-card rows. The existing NVML branch already understands MIG; it reports the slice's memory and hands the child the MIG UUID._pinned_child_visibility): when the mask cannot be mapped, the child keeps the user's original mask instead of a widened"0". ROCm and numeric masks pin as before.nvidia.get_mig_gpu_indices(): reads the MIG rows of the cachednvidia-smi -L.GPU N:rows. The first nvidia-smi answer replaces a count that came from the torch fallback, since torch counts each R570+ MIG slice as a device; after that the count only grows.MIG-entry, the child is pinned to the entries behind the picked torch ordinals instead of the whole mask, and torch ordinals are never mapped through cached NVML rows.1gpu2,0,1,abc) keep their cards, read the way CUDA reads them; a repeated index (1,1,1gpu,1gpu) gives no rows, as CUDA itself rejects it. When the slice reading fails, whole cards keep their nvidia-smi rows; a MIG-only host with no reading at all falls back to the nvidia-smi rows, so the list is never empty.Hosts without MIG take exactly the same paths as before.
Tests
tests/test_mig_gpu_masks.py: covers an A100 with 2x 3g.20gb, three A100s with card 0 split 3x 2g.10gb, mixed MIG and non-MIG cards, new and old MIG UUID forms, a UUID prefix, a numeric mask, no NVML and no MIG.gpu_rows_only.No MIG-partitioned card was available, so this is proven with spoofed
nvidia-smiand NVML output.