Skip to content

Studio: read whole-GPU uuid masks from nvidia-smi rows and cache the MIG set - #14017

Merged
danielhanchen merged 14 commits into
mainfrom
r7-studio-mig-ordinary-host
Oct 16, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
r7-studio-mig-ordinary-host

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Problem

Two ordinary-host regressions came in with the Studio MIG change (#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.

…MIG set

Query uuid alongside memory so a whole-GPU uuid mask resolves under any
CUDA_DEVICE_ORDER and without the separate uuid query; a lone non-MIG card
maps any single GPU token. MIG masks stay conservative.

Cache get_mig_gpu_indices (empty and failed results too) per static
generation, published by the physical count probe, so memory polls and
auto selection do no extra nvidia-smi work on ordinary hosts.
@chatgpt-codex-connector

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 🔄 Running since 2026-10-16T15:17:37.674292Z 1b80591 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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 ✅ Completed 2026-10-16T20:49:46.509134Z 315e6bc Manual request
🔒 Security Review ⚠️ Failed 2026-10-16T15:17:43.000722Z 1b80591 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: 1b80591e65

ℹ️ 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 +15159 to +15160
visible = nvidia._uuid_visible_ordinal_map(cvd, uuid_rows)
return set(visible) if visible is not None else 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.

P1 Badge Preserve the UUID mapping when bypassing NVML

When a multi-GPU whole-card UUID mask is used with CUDA_DEVICE_ORDER=FASTEST_FIRST and automatic fitting selects only a subset, this fast path returns physical nvidia-smi rows without storing the UUID-to-index mapping anywhere. Consequently, _child_visibility_for() emits numeric IDs, while _pinned_child_visibility() rejects those IDs as unsafe and returns None; the launch then retains the complete inherited UUID mask, exposing GPUs that were not included in the memory budget and potentially placing or splitting the model on the wrong cards. Preserve the queried UUID mapping so the selected physical rows can be translated back into UUIDs for the child.

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.

Agreed. Fixed in 125d97c: once nvidia-smi answers for a FASTEST_FIRST UUID mask, the NVML rows that _child_visibility_for reads are never filled, so a subset fell back to the whole inherited mask. The memory probe now keeps its index-to-uuid rows, and when the pinned path would otherwise keep the inherited mask it pins the child to the selected cards' UUIDs, only when the ids are physical indices, the current mask names every one of them, and none is a MIG card (CUDA gives a GPU- entry on a MIG card a slice, which only the NVML rows name). Covered by test_a_subset_of_a_uuid_mask_pins_the_child_by_uuid and test_a_uuid_mask_on_a_mig_card_keeps_the_inherited_mask.

Comment on lines +15162 to +15165
if len(tokens) == 1 and len(physical_ids) == 1:
(only,) = physical_ids
if only not in nvidia.get_mig_gpu_indices():
return {only}

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 Keep an unverified UUID mask unresolved

When the combined nvidia-smi response lacks the UUID column on a one-card non-MIG host, this fallback treats every GPU-* token as naming that card without checking the token. A stale, mistyped, or scheduler-supplied UUID that matches no installed GPU should expose no CUDA device, but this path instead returns the sole card and can launch work on a GPU the mask was intended to hide. Keep the mask unresolved unless the UUID can actually be verified against a query result.

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.

Agreed, the lone-card shortcut assumed rather than verified. Fixed in 125d97c: with no uuid column the mask is now checked with the existing index,uuid query (order independent, only membership matters); if that cannot verify it, the mask stays unresolved and keeps the conservative path. Covered by test_without_a_uuid_column_the_mask_is_verified_or_unresolved.

Comment thread studio/backend/utils/hardware/nvidia.py Outdated
and hit[0] == gpu_query._static_gen
and time.monotonic() - hit[1] < _MIG_INDICES_TTL_S
):
return set(hit[2])

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 Tag the MIG cache with the query's starting generation

If invalidate_static() runs while _query_mig_gpu_indices() is in flight, this store reads the new generation after the query completes and tags the potentially pre-invalidation result as current. Subsequent callers then accept that stale MIG set for the full local TTL, defeating the invalidation that is supposed to force a fresh inventory read and potentially causing whole-card memory to be used for a newly reconfigured MIG card. Capture the generation before starting the query and only publish the result for that generation.

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.

Agreed. Fixed in 125d97c: the MIG listing is published under the static generation read before its query started, both in get_mig_gpu_indices and where the physical count probe seeds it; a result from a generation invalidated mid-query is returned but not cached, so the next caller re-reads. Covered by test_a_listing_raced_by_an_invalidation_is_not_cached.

…ache by generation

A subset of a whole-GPU uuid mask chosen from the nvidia-smi rows now pins
the child to those uuids instead of keeping the whole inherited mask. A
mask with no uuid column is verified with the uuid query rather than
assumed to name a lone card. The MIG listing is published under the
generation read before its query, so one raced by an invalidation is
not cached.
@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: 125d97c0c8

ℹ️ 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 thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +165 to +166
if gen == gpu_query._static_gen:
_mig_indices_cache = (gen, time.monotonic(), indices)

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 Do not renew MIG freshness from a cached listing

run_nvidia_smi("-L") is already cached for 60 seconds by gpu_query.py, but this store starts another 60-second TTL from the time that possibly cached result is consumed. For example, a listing created at t=0 and read here at t=59 remains accepted until t=119, even though the underlying inventory cache would refresh at t=60. If MIG is enabled or disabled externally during that interval without an explicit invalidate_static(), memory placement can continue treating slice memory as whole-card memory (or vice versa) for almost twice the configured inventory TTL; use the underlying cache as the sole freshness authority or preserve its original timestamp.

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.

Agreed. Fixed in 244546b: the MIG set now keeps the age of the listing it came from. gpu_query.answered_at returns the start time of the cached -L answer for the current generation, and both get_mig_gpu_indices and the physical count probe stamp the set with the earlier of that and their own query start, so a set read from gpu_query's cache expires with that listing instead of starting a new 60 second window. Covered by test_a_cached_listing_keeps_its_age.

Comment thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +216 to +219
except Exception:
return set()
if result.returncode != 0 or not isinstance(result.stdout, str):
return set()
indices: set[int] = set()
current: Optional[int] = None
for line in result.stdout.splitlines():
if line.startswith("GPU "):
head = line[4:].split(":", 1)[0].strip()
current = int(head) if head.isdecimal() else None
elif current is not None and line.strip().startswith("MIG "):
indices.add(current)
return indices
return frozenset()
if result.returncode != 0:
return frozenset()

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 Avoid caching a failed MIG probe as an empty inventory

When nvidia-smi -L transiently raises or returns nonzero, these branches return the same empty set as a successful non-MIG listing, and get_mig_gpu_indices() then caches it for 60 seconds. On a MIG host where the separate memory query succeeds, every poll during that interval treats the physical row as an ordinary GPU and can budget the whole card instead of the visible slice; retain a failure sentinel and skip publishing it so a subsequent poll can recover, matching gpu_query's existing policy of never serving failures.

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.

Agreed. Fixed in 244546b: a failed nvidia-smi -L is now a distinct result, not an empty inventory. The cache keeps the last answer from the same generation (empty only if there has never been one), marks the entry unanswered and retries after a 5 second backoff, so a MIG host recovers on the next poll after that while a broken nvidia-smi still does not add a query to every memory poll. Covered by test_a_failed_listing_keeps_the_last_answer_and_backs_off and test_a_cold_failure_is_retried_after_the_backoff.

Comment on lines +15102 to +15103
by_index = dict(rows)
return ",".join(by_index[i] for i in ids)

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 UUID mask order when pinning the child

With a reordered multi-GPU UUID mask under FASTEST_FIRST, auto-selection produces ascending physical IDs, and this join emits UUIDs in that ascending order instead of the inherited mask order already recorded in visible. For example, CUDA_VISIBLE_DEVICES=GPU2,GPU1 with IDs [1,2] becomes GPU1,GPU2; because _inherited_child_gpu_order() cannot resolve UUID masks under this device order, its existing pass-through --tensor-split safeguard never runs, so positional shares are assigned to the opposite cards and can cause an OOM or incorrect placement. Order the selected IDs by their ordinal in visible before emitting the child mask.

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.

Agreed on the bug. Fixed in 244546b, in the launch rather than the join: Unsloth's own --tensor-split shares are positional over the pinned ids, so reordering only the emitted mask would move the cards without their shares. _inherited_child_gpu_order now falls back to the mask order of the uuid rows the memory probe matched, so a reordered whole-GPU uuid mask takes the same path as a numeric one: the pinned ids and Unsloth's shares are reordered together, a pass-through --tensor-split keeps ascending order as before, and the child mask is emitted in that order. Covered by test_a_reordered_uuid_mask_orders_the_pinned_child.

…uuid mask order

A MIG set read from gpu_query's cached -L answer keeps that answer's
timestamp instead of starting a new TTL. A failed listing keeps the last
answer of the generation (empty if none) and is retried after 5 s, never
cached as a 60 s empty inventory. A reordered whole-GPU uuid mask now
orders the pinned child ids (and Unsloth's tensor split) the way a
numeric mask already did.
@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: 244546bbaf

ℹ️ 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 thread studio/backend/utils/hardware/nvidia.py Outdated
hit = _mig_indices_cache
now = time.monotonic()
if hit is not None and hit[0] == gpu_query._static_gen:
if now - hit[1] < (_MIG_INDICES_TTL_S if hit[3] else _MIG_FAILURE_RETRY_S):

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 Honor the configured static TTL in the MIG cache

When UNSLOTH_GPU_QUERY_STATIC_TTL is set below 60 seconds (including 0, which the GPU-query tests support), this hard-coded TTL prevents get_mig_gpu_indices() from consulting the newly expired -L inventory until a full minute has elapsed. If MIG is enabled externally during that window, placement can continue treating the physical row as whole-card memory and over-budget the visible slice. Fresh evidence beyond the earlier cache-age report is this mismatch with the supported TTL override; derive this lifetime from gpu_query.ttl_for(gpu_query.STATIC) or otherwise cap it to that value.

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.

Agreed. Fixed in 7fe58a5: the MIG set no longer has its own 60 second lifetime. A good answer lives for gpu_query.ttl_for(gpu_query.STATIC), so UNSLOTH_GPU_QUERY_STATIC_TTL bounds it the same way it bounds the -L inventory, including 0, which re-reads on every call. A failed listing is retried after the shorter of that TTL and the 5 second backoff. Covered by test_the_configured_ttl_bounds_the_mig_set, parametrised over 10 and 0.

Comment on lines +15202 to +15203
visible = nvidia._uuid_visible_ordinal_map(cvd, uuid_rows)
return set(visible) if visible is not None else 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 Normalize UUID case in the NVML fallback

When a lowercase whole-GPU UUID names a MIG-enabled card, this matcher accepts it case-insensitively and proceeds to the MIG correction, but _nvml_rows_visible() only recognizes uppercase GPU-/MIG- tokens and compares UUID prefixes case-sensitively. It therefore returns no slice reading; if the torch fallback is unavailable, the mig_card_rows fallback returns the physical card's whole-memory values and can over-budget the slice. Normalize UUID case consistently in the NVML matcher, or do not accept the mask here unless the slice lookup can resolve it end to end.

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.

Agreed. Fixed in 7fe58a5: _nvml_rows_visible now matches GPU- and MIG- tokens case-insensitively against the NVML uuids, the same way the nvidia-smi uuid matcher and resolve_uuid_mask already read the mask. A lowercase whole-GPU uuid on a MIG card now gets its slice reading, and a lowercase MIG- entry its slice; the child is pinned with the uuid as NVML reports it. Covered by test_a_lowercase_uuid_reads_the_slice.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 16, 2026
…ase-insensitively

The MIG set now expires with gpu_query's static TTL, so
UNSLOTH_GPU_QUERY_STATIC_TTL (0 included) applies to it. The NVML row
matcher reads GPU-/MIG- tokens case-insensitively, like the nvidia-smi
uuid matcher, so a lowercase uuid on a MIG card gets its slice reading.
@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: 7fe58a54d8

ℹ️ 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 thread studio/backend/utils/hardware/nvidia.py Outdated
return None
if result.returncode != 0:
return None
return _parse_mig_gpu_indices(result.stdout)

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 Treat empty MIG listings as failed probes

When nvidia-smi -L exits successfully but transiently produces empty stdout, this returns an empty set rather than the failure sentinel, so get_mig_gpu_indices() caches “no MIG” for the full static TTL. On a MIG host where the separate memory query succeeds, placement can then use the physical card's whole-memory row for up to 60 seconds; this also conflicts with gpu_query.py, which explicitly treats empty output as an unservable failed answer. Check for nonempty string output before publishing the parsed set.

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.

Agreed. Fixed in 8d1db14: an nvidia-smi -L that exits 0 with empty output is now a failed probe, matching gpu_query, which never serves an empty answer. It keeps the last answer from the same generation and is retried after the short backoff instead of being cached as "no MIG". Covered by test_an_empty_listing_is_a_failed_probe.

its conservative path."""
from utils.hardware import nvidia

tokens = [t.strip().lower() for t in cvd.split(",") if t.strip()]

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 Reject UUID masks with leading or interior empty entries

When CUDA_VISIBLE_DEVICES is ,GPU-… or contains an empty entry before a later UUID, CUDA stops at that empty entry (a leading one exposes no devices), but this comprehension discards it and treats every remaining UUID as visible. The new nvidia-smi path can consequently select one of those rows and _pinned_child_visibility() replaces the inherited terminating mask with a valid UUID, exposing a GPU the parent runtime would have hidden; preserve the empty entry's terminator semantics instead of filtering it out.

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.

Agreed. Fixed in 8d1db14: _uuid_visible_ordinal_map now cuts the mask at the first empty entry, as CUDA does. A leading empty entry resolves nothing and the mask stays unresolved, an interior one keeps only the entries before it, and a trailing comma is unchanged. The nvidia-smi row filter, the uuid pin and the child order all go through it, and _nvml_rows_visible also stops at an empty entry, so the NVML fallback reads the mask the same way. Covered by TestAnEmptyEntryEndsAUuidMask.

Comment thread studio/backend/utils/hardware/nvidia.py Outdated
"""When the ``-L`` answer just read was produced: the gpu_query entry's start when it
served a cached one, else when this query began."""
try:
at = gpu_query.answered_at([_nvidia_smi_executable(), "-L"])

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 Tie the MIG timestamp to the returned listing

When an expired static -L refresh exceeds the caller timeout, run_nvidia_smi() can return the previous cached listing while its background flight continues; if that flight (or another caller) publishes a newer listing before this separate answered_at() lookup, this function reads the newer timestamp but the caller caches indices parsed from the older result. A MIG reconfiguration can therefore be tagged fresh for another full TTL and placement may keep using whole-card memory for a newly partitioned GPU. Return the answer timestamp together with the specific cached result, or verify that the cache entry still corresponds to the result being parsed.

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.

Agreed. Fixed in 8d1db14: gpu_query.answered_at now takes the stdout that was parsed and returns the cache entry's start time only when that entry holds exactly that listing. If a newer listing replaced it, the parsed set is returned but not cached, so the next poll reads the newer one; with the cache off, the query's own start time is used. _query_mig_gpu_indices returns the indices and that timestamp together, and the physical count probe uses the same check. Covered by test_a_superseded_listing_is_not_cached.

…, stamp the exact listing

An empty nvidia-smi -L answer is a failed probe, not a host without MIG.
The uuid and NVML matchers stop at the first empty mask entry, as CUDA
does, so a leading one resolves nothing. The MIG set takes the timestamp
of the gpu_query entry holding exactly the listing it parsed, and is not
cached when a newer listing has replaced it.
@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: 8d1db14ce3

ℹ️ 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 +15211 to +15212
ids = nvidia.resolve_uuid_mask(cvd)
return set(ids) & physical_ids if ids else 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 Reject incomplete UUID-mask intersections

When the combined memory query omits the UUID column and also lacks a usable row for one GPU in a multi-GPU UUID mask, intersecting the separately resolved IDs with physical_ids silently accepts only the remaining subset. _get_gpu_memory() can then budget and select that subset, but _pinned_child_visibility() has no UUID rows with which to pin it and leaves the full inherited mask in place, so llama.cpp sees an unbudgeted GPU. Return None unless every resolved mask ID is present in physical_ids.

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.

Agreed. Fixed in 9aa3f59: without a uuid column, the mask verified by the separate uuid query is now accepted only when every card it names has a memory row; if any is missing the mask stays unresolved and keeps the conservative path, so a partial set is never budgeted while the child keeps the full inherited mask. Covered by test_without_a_uuid_column_every_named_card_needs_a_row.

Without a uuid column, a verified mask is accepted only when every card it
names has a row: a partial set would be budgeted but could not be pinned.
@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: 9aa3f59b68

ℹ️ 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 thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +224 to +226
if answer is None:
last = hit[2] if hit is not None and hit[0] == gen else frozenset()
_store_mig_gpu_indices(last, gen, at = time.monotonic(), answered = False)

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 a newer MIG result after a failed probe

When concurrent callers probe after an expired entry, a caller whose -L request fails can resume after another caller has already published a successful result for the same generation; this branch still derives last from its pre-query hit and unconditionally overwrites the newer cache entry with that stale set marked failed. Subsequent memory probes then use the stale MIG classification for the failure backoff window, which can make a newly partitioned card be budgeted as a whole GPU. Recheck the current cache under synchronization before publishing the failure, and do not replace a newer successful entry.

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.

Agreed. Fixed in cd5daf4: a failed probe no longer writes from its pre-query snapshot. Cache writes compare against the current entry under a lock; a failed -L keeps a successful answer another caller published for the same generation within the TTL, and only otherwise records the failure with the last answer of that generation, and a successful write never replaces a newer one. I also added get_mig_gpu_indices_or_none(), which returns None while discovery is unknown (latest probe failed or none answered) and an empty set only when a listing answered with no MIG cards. Covered by test_a_failed_probe_keeps_a_newer_answer_from_another_caller and test_unknown_mig_discovery_is_not_no_mig.

pre-commit-ci Bot and others added 2 commits October 16, 2026 18:59
…nknown discovery

Cache writes compare against the current entry under a lock: a failed -L
keeps an answer another caller published for the same generation, and an
older listing never replaces a newer one. get_mig_gpu_indices_or_none()
returns None while MIG discovery is unknown (failed or never answered),
an empty set only when a listing answered with no MIG cards.
@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: cd5daf41cd

ℹ️ 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 +15212 to +15213
ids = nvidia.resolve_uuid_mask(cvd)
return set(ids) if ids and set(ids) <= physical_ids else 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.

P1 Badge Preserve the fallback UUID-to-index mapping

When the memory command returns rows without the requested UUID column, this fallback verifies the mask but reduces the ordered UUID-to-index mapping to a set while _SMI_UUID_ROWS remains empty. Under FASTEST_FIRST, _smi_uuid_mask_order() and _smi_uuids_for() therefore cannot restore the inherited order or pin an automatically selected subset: tensor-split shares can be assigned to the opposite cards, or the child can retain the complete inherited mask and expose an unbudgeted GPU. Fresh evidence beyond the earlier mapping report is that the new no-UUID-column path accepts these rows after the separate UUID query but discards that query's mapping; preserve it or leave the rows unresolved.

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.

Agreed. Fixed in 19d71ab: without a uuid column the rows carry nothing to order or pin a multi-card subset by, so that path now accepts only a one-card mask, verified by the separate uuid query. A one-card mask needs no ordering and the inherited mask already pins that card; multi-card masks stay unresolved and take the conservative path. Covered by test_without_a_uuid_column_only_a_one_card_mask_resolves.

Comment thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +239 to +240
indices, _answered = _mig_gpu_lookup()
return set(indices or ())

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 Use the failure-aware MIG lookup for placement

When the first nvidia-smi -L probe fails or returns empty output on a MIG host, this compatibility accessor intentionally collapses the new unknown sentinel to an empty set and retains it for the failure backoff. The placement paths in _get_gpu_memory() and _with_mig_instance_memory() still call this accessor, so during that window they treat the host as non-MIG and may budget the physical card's full memory for a slice. Fresh evidence beyond the earlier failed-probe reports is that get_mig_gpu_indices_or_none() now exposes the distinction, but neither safety-critical caller uses it; they should treat None as an inability to trust whole-card rows.

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.

Agreed. Fixed in 19d71ab: _get_gpu_memory and _with_mig_instance_memory now use get_mig_gpu_indices_or_none(). When MIG discovery is unknown, NVML readings replace the CLI rows (NVML gives the slice for a MIG card and the same reading for a whole card); without an NVML answer the CLI rows stand as they did before MIG support, so a failed listing never opens a CUDA context on an ordinary host. Covered by TestUnknownMigDiscovery.

continue
gpus.append((idx, free_mib, total_mib))
rows.append((idx, free_mib, total_mib))
LlamaCppBackend._SMI_UUID_ROWS = uuid_rows

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 Clear stale NVML rows when SMI becomes authoritative

After an earlier NVML fallback populates _NVML_ROWS, a later successful non-MIG SMI probe updates only _SMI_UUID_ROWS, so _child_visibility_for() continues to prefer the old NVML mapping. This is observable when MIG is disabled or reconfigured during the Studio process: the stale rows can still map a whole-GPU UUID to a removed MIG slice, causing _pinned_child_visibility() to emit that obsolete MIG- UUID even though the current SMI inventory reports a whole card. Clear or version the NVML inventory when accepting these SMI rows, or make child visibility use the source associated with the latest memory result.

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.

Agreed. Fixed in 19d71ab: when nvidia-smi answers and MIG discovery reports no MIG cards among those rows, the cached NVML inventory is cleared, so slices from an earlier MIG layout can no longer name the child's devices; when a row is a MIG card, the NVML probe runs and refreshes those rows. Covered by test_cli_rows_retire_an_old_nvml_inventory.

…-card no-uuid masks

Placement and auto selection use get_mig_gpu_indices_or_none: when MIG
discovery failed, NVML readings (slices and whole cards) replace the CLI
rows, and without NVML the CLI rows stand as before. A CLI answer with no
MIG cards clears the cached NVML inventory so stale slices never name the
child's devices. Without a uuid column only a one-card uuid mask resolves.
@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: 19d71ab033

ℹ️ 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 thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +264 to +267
indices, at = answer
if at is not None:
_store_mig_gpu_indices(indices, gen, at = at)
return indices, True

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 Treat a superseded MIG listing as unknown

When a slow expired nvidia-smi -L flight returns after a newer flight has published a different listing, _listing_taken_at() returns None because the result was superseded. This branch correctly avoids caching it but still returns its parsed indices as an authoritative answer; _get_gpu_memory() can therefore use a stale “no MIG” result for the current placement and budget a newly partitioned card using its whole-card memory. Fresh evidence beyond the earlier cache-timestamp issue is this unconditional one-shot consumption after publication has been rejected; return an unknown result or the current cached classification instead.

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.

Agreed. Fixed in ffd99c4, as part of rewriting the MIG cache into one entry replaced only by the latest-started probe of a generation (failed, empty, superseded and invalidated probes are all unknown): a superseded listing is now neither published nor acted on. The caller gets the current fresh entry, or unknown (get_mig_gpu_indices_or_none() returns None), so placement never uses a stale "no MIG" even for one probe. Covered by test_a_superseded_listing_is_not_cached and TestTheLatestStartedProbeWins.

Comment on lines +15327 to +15333
if mig_known is None:
# MIG discovery failed: a row may be a whole MIG card. NVML names
# slices and whole cards alike, so its reading wins; without one
# the CLI rows stand, as before MIG support (no CUDA context).
nvml = {g[0]: g for g in LlamaCppBackend._get_gpu_memory_nvml()}
if nvml:
gpus = [nvml.get(g[0], g) for g in 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 Clear stale NVML rows when the fallback probe fails

When MIG was previously enabled, _NVML_ROWS can still contain slice UUIDs; if MIG is then disabled while the -L discovery is temporarily unknown and this NVML probe also fails, the code keeps the successful whole-card CLI rows but leaves that old inventory intact. _pinned_child_visibility() subsequently prefers the stale rows and can emit a removed MIG- UUID, causing the child to see no intended GPU. Fresh evidence beyond the earlier stale-inventory report is the new unknown-discovery branch, which clears nothing when _get_gpu_memory_nvml() returns empty; clear the cached rows before accepting the CLI fallback.

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.

Agreed. Fixed in ffd99c4: when MIG discovery is unknown and the NVML probe returns nothing, the cached NVML rows are cleared before the CLI rows are accepted, so an older slice inventory can no longer name the child's devices. Covered by test_unknown_discovery_without_nvml_retires_old_nvml_rows.

Comment thread studio/backend/utils/hardware/nvidia.py Outdated
Comment on lines +182 to +184
if cur is not None and cur[0] == gen and cur[3] and cur[1] > at:
return
_mig_indices_cache = (gen, at, indices, answered)

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 Do not let an older success replace a newer failure

With UNSLOTH_GPU_QUERY_CACHE=0, concurrent expired MIG probes run independently: a newer probe can fail and publish an answered=False entry, after which an older in-flight successful probe reaches this store. Because the timestamp guard only applies when cur[3] is true, the older result overwrites the newer failure and is treated as authoritative for the full static TTL; after a MIG reconfiguration this can restore a stale no-MIG classification and whole-card budgeting. Compare timestamps regardless of the answered flag so an older probe cannot supersede any newer outcome.

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.

Agreed. Fixed in ffd99c4: each probe takes a sequence number when it starts and may only replace an entry of the same generation from an earlier-started probe, whatever either outcome was, so an older success can no longer replace a newer failure (nor an older failure a newer answer). Covered by TestTheLatestStartedProbeWins.

Replace the MIG cache with a single entry (generation, sequence, taken
at, indices). Every probe takes a sequence number when it starts and may
only replace an entry of its generation from an earlier-started probe.
A failed, empty or superseded listing is unknown (None), never acted on
as no MIG; an invalidated generation is unknown too. Answers live for
the static TTL from when their listing was taken, unknowns for a short
backoff. Unknown discovery without an NVML answer also clears the cached
NVML rows, and the uuid pin requires known MIG discovery.
@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: ffd99c4f2c

ℹ️ 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 +15122 to +15124
mig = nvidia.get_mig_gpu_indices_or_none()
if any(i not in visible for i in ids) or mig is None or set(ids) & mig:
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.

P1 Badge Preserve UUID subset pinning when MIG recheck fails

When a multi-GPU UUID mask is automatically narrowed, a transient -L failure here—or UNSLOTH_GPU_QUERY_STATIC_TTL=0 followed by such a failure—makes mig be None even though the preceding memory probe already selected physical rows and recorded their UUID mapping. _smi_uuids_for() then declines the mapping, _pinned_child_visibility() returns None, and the launch keeps the complete inherited UUID mask, exposing GPUs outside the fitted subset and potentially assigning tensor-split shares to unbudgeted cards. Keep the MIG classification associated with the memory result, or otherwise prevent the launch from falling back to the full mask when this later recheck is unknown.

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.

Agreed. Fixed in ce30435: _smi_uuids_for() now uses the MIG classification the memory probe recorded alongside the uuid rows it maps, so a later failed or uncached MIG recheck can no longer push the child back to the full inherited mask. If discovery was already unknown at probe time, the fitted uuid subset is still pinned, and any card the same probe's NVML rows mark as MIG is excluded (it is pinned to its slice through the NVML rows instead), so no unbudgeted card is exposed. This also drops the extra MIG lookup from the pin step. Covered by TestAUuidSubsetPinSurvivesAFailedMigRecheck.

_smi_uuids_for used to re-query MIG discovery, so a failed recheck left
the child on the whole inherited mask. It now uses the classification
captured with the rows it maps; if that was unknown, NVML rows from the
same probe still exclude MIG cards and the fitted subset is pinned.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: ce30435b01

ℹ️ 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 +139 to +140
# Same listing get_mig_gpu_indices parses: publish it so memory polls reuse it.
_mig_finish(probe, result)

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 Publish raised physical-count probes as unknown

When this -L call raises after a successful MIG classification is already cached, _mig_finish() is skipped even though _mig_probe_start() reserved the newest sequence. The old entry therefore remains authoritative while fresh, so a transient driver timeout during a MIG reconfiguration can make placement continue using a cached no-MIG result and budget the whole card. Unlike _mig_gpu_lookup, this new physical-count seeding path should publish _mig_finish(probe, None) from the exception path so the latest failed probe becomes unknown.

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.

Agreed. Fixed in 315e6bc: when the physical-count -L call raises, its probe now publishes an unknown result through the same path as the MIG lookup, so as the latest-started probe it replaces the older answer and placement treats MIG as unknown (NVML readings, no whole-card budgeting) until the next listing succeeds. Covered by test_a_raised_physical_count_probe_leaves_mig_unknown.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 315e6bc84a

ℹ️ 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 Datta0/unsloth-staging-3 that referenced this pull request Oct 16, 2026
@danielhanchen
danielhanchen merged commit eb0617b into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the r7-studio-mig-ordinary-host branch October 16, 2026 23:21
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 18, 2026
…rs, never blocks the event loop (unslothai#14118)

## Problem

Three small costs in the automatic GPU placement added by unslothai#14020, all on
multi-GPU NVIDIA hosts:

1. `hardware._nvidia_mig_gpu_indices_or_none()` ran its own `nvidia-smi
-L`, bypassing the MIG discovery cache from unslothai#14017. A successful listing
was served by gpu_query's cache, but a failed one had no backoff, and
with `UNSLOTH_GPU_QUERY_CACHE=0` every call spawned nvidia-smi (one per
automatic route, two per catalog refresh).
2. Under `CUDA_DEVICE_ORDER=FASTEST_FIRST` with a numeric mask, a failed
bus-id join was never cached, so every `auto_select_gpu_ids()`
re-spawned the driver-API child (about 300 ms here, up to its 15 s
timeout on a hung driver).
3. nvidia-smi CSV output is not quoted, so a GPU name containing a comma
made `get_card_identities()` return nothing. Every catalog refresh then
ranked live, and identical cards under FASTEST_FIRST got an explicit
card 0 instead of staying unpinned.

4. On a MIG host, automatic image/video placement ranked cards by their
physical nvidia-smi rows and could return card 1, which CUDA maps to a
MIG slice (or to nothing before driver R570). Main before unslothai#13928 stayed
on the current card there.
5. The event-loop gate `auto_cuda_ranking_possible_cached()` called
`get_device()` for non-CUDA hosts, which waits on the hardware-detection
lock while a detection pass runs, stalling the event loop (about 1.3 s
per call in a spoofed run) on Mac, CPU and XPU hosts too.

## Fix

1. `_nvidia_mig_gpu_indices_or_none()` delegates to
`nvidia.get_mig_gpu_indices_or_none()`, so it shares that cache, its
failure backoff and its sequence-number rules.
2. A failed bus-id join is remembered for 300 s per (mask, order, static
generation); hardware re-detection still retires it at once.
3. Card identities rejoin a name that spans several CSV fields, as the
inventory parser already does.

4. A row-ranked winner other than card 0 is only taken when MIG
discovery confirms no MIG card among the visible ones; otherwise card 0
stays explicit.
5. The cached gate answers from memory only: non-CUDA or ROCm is False,
and detection still in flight defers to the worker thread.

Single-GPU, CPU, Apple and ROCm hosts never reach items 1-4.

## Tests

- New `tests/test_media_auto_gpu_mig_and_event_loop.py`: 6 of 7 fail on
main, all pass here.

- New `tests/test_media_auto_gpu_probe_caches.py`: 3 of its 5 tests fail
on main, all pass here.
- `test_mig_listing_parses_slices` disables gpu_query's cache in its
stub now that the helper shares it.
- GPU / hardware / media suites: 3467 passed, 3 skipped. The 3 failures
in `test_rocm_windows_vram_7452.py` are the same on main.

---------

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