Skip to content

Studio: honour MIG masks and size MIG cards by their slice - #13927

Merged
danielhanchen merged 9 commits into
mainfrom
r7d-studio-mig
Oct 16, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
r7d-studio-mig

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Problem

Studio mishandled NVIDIA MIG in three places:

  • MIG UUID mask: CUDA_VISIBLE_DEVICES=MIG-<uuid> (or the old MIG-GPU-<uuid>/gi/ci form) was treated as "no mask" by llama.cpp's GPU sizing. _get_gpu_memory then 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.
  • GPU count: the physical GPU count included MIG child rows. On one A100 with two slices the picker offered three GPUs and could write CUDA_VISIBLE_DEVICES=2, which leaves the worker with no device.
  • Numeric mask on a MIG card: auto-select and llama.cpp were told the whole card's free memory, not the slice's.

Fix

  • llama.cpp sizing: a CUDA_VISIBLE_DEVICES value that does not map to nvidia-smi rows (MIG UUIDs, mixed GPU-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.
  • Child mask (_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.
  • MIG card with a numeric mask: llama.cpp takes the NVML branch, so the card counts as the slice CUDA exposes. Auto-select ranks it by the slice's NVML reading, and treats it as unknown when there is no reading.
  • nvidia.get_mig_gpu_indices(): reads the MIG rows of the cached nvidia-smi -L.
  • Physical GPU count: uses only the 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.
  • One slice per MIG card: each MIG card is one row backed by a single visible slice, and the child is pinned to that slice's UUID. It is the first slice the mask names, otherwise the slice with the least free memory, so the budget never exceeds the device the child gets. This holds for llama.cpp, diffusion and training alike. On R570+ drivers, where one process can see several GPU instances of a card, Studio uses one of them: conservative, never over budget, and still far closer than the whole-card size used before.
  • Multi-slice MIG mask: when torch enumerated every inherited 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.
  • Numeric-prefix masks (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

  • New 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.
  • Base vs head: the behavioural tests fail on main and pass here, plus guards for the new helpers. Also covers R570-style multi-slice rows (one slice per card, least free when none is named), repeated indices, torch ordinals beside cached rows, numeric-prefix masks and a missing slice reading.
  • Updated existing tests:
    • One existing assertion expected whole-card rows for an unresolvable UUID mask, which was the bug. It now expects no rows.
    • Two count stubs accept gpu_rows_only.
  • 57 related test files: the same failures on main and here, all pre-existing environment failures.

No MIG-partitioned card was available, so this is proven with spoofed nvidia-smi and NVML output.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T06:02:17.011658Z e2640cb New commits
🔒 Security Review ⚠️ Failed 2026-10-15T19:58:59.850770Z d087ddb PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +155 to +156
``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."""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +15067 to +15072
_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 = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +168 to +171
except Exception:
return set()
if result.returncode != 0 or not isinstance(result.stdout, str):
return set()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines 6339 to +6341
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +15076 to +15078
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 = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +14871 to +14874
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +14957 to +14961
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +6264 to +6265
from core.inference.llama_cpp import LlamaCppBackend
slices = {idx: (free, total) for idx, free, total in LlamaCppBackend._get_gpu_memory_nvml()}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +6253 to +6254
if IS_ROCM or not devices:
return devices

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e94c1cd6da

ℹ️ 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".

… of summing R570 instances; torch ordinals never map through cached NVML rows; a repeated mask index hides every GPU
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 51367fc269

ℹ️ 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".

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 16, 2026
…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

# Conflicts:
#	studio/backend/core/inference/llama_cpp.py
@danielhanchen
danielhanchen merged commit 23bbee0 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the r7d-studio-mig branch October 16, 2026 07:52
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 16, 2026
…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>
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.

1 participant