Repository navigation
Add Unsloth Docker images (base + Studio) for any NVIDIA GPU host, Ampere through Blackwell - #5748
Conversation
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c6d92160f6
ℹ️ 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".
left a comment
There was a problem hiding this comment.
Code Review
This pull request introduces a Dockerized environment for Unsloth and unsloth-zoo, specifically optimized for NVIDIA Blackwell GPUs (sm_100 and sm_120). The changes include a multi-stage Dockerfile, build and freeze scripts, and a comprehensive smoke test to verify GPU compatibility and training functionality. Review feedback suggests optimizing the Dockerfile by removing a redundant installation of the uv tool, correcting a version mismatch for torchaudio to ensure consistency with the PyTorch stack, and relocating cache directories outside of the workspace to prevent issues when mounting host volumes at runtime.
| HF_HOME=/workspace/.cache/huggingface \ | ||
| TRITON_CACHE_DIR=/workspace/.cache/triton \ |
There was a problem hiding this comment.
Setting HF_HOME and TRITON_CACHE_DIR to subdirectories of /workspace (the WORKDIR) can lead to issues when users mount a host directory to /workspace at runtime. The mount will obscure the directories created during the build, forcing the application to recreate them at runtime, which can cause permission issues or redundant downloads. Moving these caches to a location outside of the workspace, such as /opt/cache, avoids these issues.
HF_HOME=/opt/cache/huggingface \
TRITON_CACHE_DIR=/opt/cache/triton \
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58693c4c73
ℹ️ 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".
| import transformers | ||
|
|
||
| print(f"transformers {transformers.__version__}") |
There was a problem hiding this comment.
Import unsloth before transformers in smoke test
The default execution path runs training (check_tiny_train) but check_imports imports transformers first, which contradicts the later requirement that Unsloth be imported first for patched training behavior. This means the smoke test is not validating the intended Unsloth training path and can produce misleading pass/fail results (e.g., patches not applied or warnings/fallback paths during the LoRA step).
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: acbb16c8a1
ℹ️ 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".
The Dockerfile uses BuildKit-only features (the # syntax=docker/dockerfile:1.7 parser directive and RUN ... <<'PY' heredocs added in dockerfile 1.3+). The legacy builder rejects the --progress flag at the CLI level and would fail later at the heredocs anyway. Detect docker buildx and use it when available (preserves --progress=plain output). Otherwise fall back to plain `docker build` with DOCKER_BUILDKIT=1 exported, which gets the BuildKit features without buildx's nicer formatting. Reproduces the failure path seen on Docker 28.2.2 without buildx installed: unknown flag: --progress ERROR docker build exited 125
Docker 28 removed the legacy image builder entirely. Setting
DOCKER_BUILDKIT=1 no longer falls back to a builtin builder -- it
delegates to buildx, which then errors out if buildx isn't installed:
ERROR: BuildKit is enabled but the buildx component is missing
or broken.
The Ubuntu docker.io package omits buildx by default, so users on
that path hit this immediately. Detect missing buildx up front and
print exact install commands for apt / dnf / manual binary instead
of attempting a fallback that cannot work.
If the user is not in the 'docker' group, every docker command after the pre-flight returns "permission denied while trying to connect to the Docker daemon socket at /var/run/docker.sock". This used to surface as a confusing buildx failure mid-Block-2, but the actual problem is a host permissions issue that's settable up front. Detect by running 'docker info' and checking its exit code (not just grep on its output -- a permission failure prints to stderr and returns non-zero, so the old grep-based check was a silent skip). Also clarify the nvidia-runtime WARN: on Docker 28+ with CDI mode this is a false positive most of the time. The real GPU-attach test is the smoke run in Block 3a, where the container entrypoint catches missing GPUs with an actionable message.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23a5b43180
ℹ️ 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".
Ubuntu 24.04 (noble) marks the system Python interpreter as externally-managed per PEP 668, so: curl get-pip.py | python python -m pip install -U pip uv fails inside the builder image with: error: externally-managed-environment This environment is externally managed The system-level pip and uv were never used: the very next RUN creates the venv at /opt/unsloth-venv, which bootstraps its own pip via the ensurepip module (provided by the python3.12-venv apt package). uv is then installed INTO the venv with the venv's pip, and used from there. Drop the two system-pip bootstrap lines. The venv path is unchanged. Reproduces on any Docker build of the unsloth-blackwell image against a noble base image (which our nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 is).
… / peft
unsloth_zoo/__init__.py guards against being imported standalone:
if "UNSLOTH_IS_PRESENT" not in os.environ:
raise ImportError("Please install Unsloth via `pip install unsloth`!")
The env var is set by unsloth/__init__.py at import time, so importing
unsloth must happen first. The old check_imports() imported xformers,
bnb, transformers, trl, peft, then unsloth_zoo -- which fired the guard
because unsloth had not been imported yet.
Reorder check_imports() to import unsloth (and unsloth_zoo) first, then
the rest. check_unsloth_import() becomes a thin re-import to keep the
"FastLanguageModel reachable" banner in the output.
Same fix the unsloth README has been recommending for years: "import
unsloth at the top of your file, before transformers/trl/peft."
Triton's nvidia backend lazily JIT-compiles a small C extension
(CudaUtils, in triton/backends/nvidia/driver.py) on first GPU access.
Without a C compiler and Python headers in the runtime image, the
very first forward pass of any Unsloth model dies with:
RuntimeError: Failed to find C compiler.
Please specify via CC environment variable.
The builder stage has build-essential and python3.12-dev so this
worked during the build's verification step (no GPU = no Triton kernel
call = no C extension build). But the runtime stage stripped those
out for size, so the failure only surfaces when a real user runs
training inside the container.
Add gcc + g++ + python3.12-dev to the runtime stage. Increases the
runtime image by ~250MB, which is the cost of letting Triton JIT
correctly. Pre-compiling CudaUtils at build time would need a real
CUDA device (the constructor calls cuda runtime functions), so
shipping the toolchain is the right trade-off.
commented
May 24, 2026
Smoke-test validation on a fresh deploy host (AWS B200, not the build host)End-to-end validated What was validated
Unsloth's own banner inside the container: Loss progressionBit-for-bit identical to the internal validation on a GCP B200 (different host, same image): Bugs caught and fixed during validationEach was a real defect surfaced only by running the image on a fresh host:
Full gpt-oss-20B fine-tuning notebook run still pending; will post follow-up. |
…ia.com/cuda/gpus TORCH_CUDA_ARCH_LIST now covers the full set of compute capabilities NVIDIA publishes on https://developer.nvidia.com/cuda/gpus for x86_64 hardware, from Turing onward: sm_75 Turing T4, RTX 20-series, Quadro RTX sm_80 Ampere DC A100, A30 sm_86 Ampere A40, RTX A6000, RTX 30-series sm_89 Ada L4, L40, L40S, RTX 40-series sm_90 Hopper H100, H200, GH200 sm_100 Blackwell DC B100, B200, GB200 sm_103 Blackwell DC B300, GB300 sm_120 Blackwell RTX 50-series, RTX PRO 6000 Blackwell sm_121 Blackwell GB10 (DGX Spark) with +PTX on the highest entry so future arch revisions can JIT. Setting TORCH_CUDA_ARCH_LIST only affects nvcc invocations for any source build the user adds on top of this image (e.g. flash-attn, a custom CUDA op). The prebuilt cu128 wheels already include SASS for sm_70/75/80/86/90/100/120 (verified at build time via torch._C._cuda_getArchFlags()). Ada (sm_89), B300 (sm_103) and DGX Spark (sm_121) GPUs run via JIT-PTX from the nearest available arch. Jetson archs (sm_87 Orin, sm_110 Thor) are intentionally NOT included -- they require aarch64 wheels and this image is linux/amd64 only. Also lower the entrypoint's compute-capability gate from sm_80 to sm_75. Turing GPUs work, with the caveat that bfloat16 is unavailable; the entrypoint prints a NOTE in that case so Unsloth's fp16 fallback isn't a surprise.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dde5170e7a
ℹ️ 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".
| ("sm_120", "Blackwell", "RTX 50-series, RTX PRO 6000 Blackwell"), | ||
| ("sm_121", "Blackwell", "GB10 (DGX Spark)"), | ||
| ) | ||
| if major < 7 or (major == 7 and minor < 5): |
There was a problem hiding this comment.
Reject pre-Ampere GPUs in entrypoint check
The entrypoint claims to fail fast on GPUs older than Ampere, but this condition only rejects devices below sm_75, so Turing (sm_75) is allowed through. That contradicts both the script’s own header (Unsloth requires sm_80+) and smoke_test.py, which exits on any cap[0] < 8; on T4/RTX20 hosts the container starts successfully and then fails later during validation/workloads instead of giving the intended immediate, actionable error.
Useful? React with 👍 / 👎.
HF Hub does not act as a generic OCI registry for arbitrary Docker images -- the registry.hf.space endpoint only serves images that Spaces have built, not images pushed by `docker push`. So we cannot do `docker push huggingface.co/user/repo:tag` for an Unsloth image. For cross-host testing where we want one canonical place to pull from (and Docker Hub credentials are not yet configured), wrap the manual flow into push/pull-shaped commands: hf_push.sh: docker save | pigz | huggingface-cli upload hf_pull.sh: huggingface-cli download | gunzip | docker load This is approximation, not real OCI semantics -- every push uploads the full ~4 GB blob, no layer dedup, no manifest negotiation. Good for testing across A100 / H100 / RTX 6000 boxes; the real release should go through .github/workflows/docker-publish.yml to Docker Hub, which gets layer dedup, multi-arch manifest support, and standard `docker pull` UX for users. Usage: bash docker/hf_push.sh unsloth-blackwell:test danielhanchen/unsloth-blackwell-docker bash docker/hf_pull.sh danielhanchen/unsloth-blackwell-docker unsloth-blackwell-test.tar.gz unsloth-blackwell:test
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4bfb4b891a
ℹ️ 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".
…face-cli` In huggingface_hub >= 0.27 the `huggingface-cli` binary is deprecated and prints a "Use hf instead" notice then exits without doing the operation. The previous wrappers ran `huggingface-cli upload/download` silently, treated the deprecation exit as success, and uploaded nothing. Detect the new `hf` binary first and use that. If only the legacy `huggingface-cli` is on PATH (older installs), fall back with a WARN so users know the failure mode if anything goes sideways. Also: hf_pull.sh now asserts the downloaded file is non-empty (`test -s`) so we catch silent download failures before the `docker load` step.
…t call
`jupyter nbconvert --to script nb.ipynb --output nb 2>/dev/null` was
silently exiting 0 without producing the output file in some
environments (likely because jupyter/jupyter_core wasn't on PATH or
nbconvert's --output handling differed across versions). The 2>/dev/null
hid the underlying error, and `set -e` did not catch the missing-output
case because nbconvert itself returned 0.
Switch to a direct nbformat-based conversion:
pip install -q nbformat
python -c "import nbformat; nb=nbformat.read('nb.ipynb', as_version=4);
code='\n\n'.join(c.source for c in nb.cells if c.cell_type == 'code')
open('nb.py','w').write(code + '\n')"
Smaller dep set, no shell-out to a jupyter wrapper script, and an
explicit `test -s nb.py` afterwards catches any silent failure
before downstream steps try to read the file.
Reproduces the failure on RTX PRO 6000 Blackwell (sm_120, docker
29.2.1, ubuntu 24.04) where nbconvert's CLI silently no-op'd.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8344fa0a56
ℹ️ 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".
The previous nbformat-based conversion dumped raw cell.source for every code cell. The gpt-oss-20B notebook's first cell uses Jupyter !shell magic to install dependencies: !pip install --upgrade -qqq uv !uv pip install -qqq ... \ git+https://github.com/triton-lang/triton.git@0add68... ... Dumped verbatim, the `@0add68...` token tripped the Python parser with "SyntaxError: invalid decimal literal" before training could even start. The container already has unsloth, triton, transformers, etc. baked in, so we don't need the notebook's install cell. Skip any cell whose source contains pip/install markers, and comment out stray !cmd / %magic lines in any other cells. Then assert nb.py parses with ast.parse() before trying to run it -- catches conversion failures up front instead of at training time. Reproduces on RTX PRO 6000 Blackwell (sm_120, fresh Docker 29.2.1 host) where the previous conversion produced an invalid nb.py.
commented
May 24, 2026
Cross-host validation #2: sm_120 (RTX PRO 6000 Blackwell, 96GB) — full gpt-oss-20B fine-tuningEnd-to-end validated on a fresh GCP RTX PRO 6000 Blackwell Server Edition host. Image pulled from HF (huggingface.co/danielhanchen/unsloth-blackwell-docker), loaded into Docker, and exercised with both the smoke test AND the full gpt-oss-20B fine-tuning notebook. Setup
Smoke test (5-step LoRA on Llama-3.2-1B-bnb-4bit)``` Loss is ~0.4% off the B200 (sm_100) run (4.1108 → 3.7511); expected because sm_100 vs sm_120 Triton kernels produce slightly different bf16 rounding paths, deterministically. Full gpt-oss-20B fine-tuning (10 LoRA steps, MXFP4 + MoE)10 SFT steps on `HuggingFaceH4/Multilingual-Thinking` with the gpt-oss-20B MXFP4 model. Real workload, real MoE expert LoRA, real Harmony format inference at multiple reasoning_effort levels: ``` Unsloth: Detected MoE model with num_experts = 32 and target_modules = [...]. Trainable parameters = 3,981,312 of 20,918,738,496 (0.02% trained) step 1: loss=1.071 grad_norm=2.805 train_runtime = 141.7s (2.36 minutes) Post-train inference at `reasoning_effort="medium"` and `"high"` produced coherent French reasoning output via the Harmony format -- confirming MXFP4 weights are loading correctly, MoE expert routing works, and the Triton kernels JIT-compile for sm_120 at first use. What this validates
Additional bugs caught and fixed during this validation
|
Make the docker image multi-arch so DGX Spark (GB10, sm_121, aarch64) and
the Grace-Hopper / Grace-Blackwell SoCs (GH200 arm64, GB200 arm64) pull a
natively-built arm64 child from the same manifest. Runtime emulation is
NOT involved -- QEMU is used only for the cross-compile step on x86_64
CI runners; consumers on aarch64 hosts get a normal arm64 image and CUDA
works as on any other host.
Dockerfile:
* ARG TARGETARCH; switch unsloth extras between cu128-ampere-torch2100
(amd64, with xformers) and huggingface (arm64, no xformers -- there
is no cu128 aarch64 xformers wheel as of 0.0.34, so we fall back to
Unsloth's native SDPA path; ~5-10% slowdown but functionally complete).
* Build-time torch._C._cuda_getArchFlags() assertion: amd64 still
requires sm_120, arm64 accepts sm_120 or sm_121.
* Same TORCH_CUDA_ARCH_LIST on both arches; nvcc emits whatever's listed.
docker/setup_qemu.sh (new):
One-time host setup -- registers binfmt_misc handlers via
tonistiigi/binfmt and creates a 'unsloth-multiarch' docker-container
buildx builder. Required only on x86_64 build hosts targeting arm64.
docker/test_locally.sh:
--platform amd64|arm64 flag. Cross-builds verify QEMU is registered,
then build through the in-image arch-flags assertion. Smoke + notebook
blocks auto-skip when image arch != host arch (CUDA cannot run under
user-space QEMU + nvidia-container-toolkit cannot bridge a QEMU guest
to a real GPU).
.github/workflows/docker-publish.yml:
platforms: linux/amd64,linux/arm64 (single manifest, two children).
Timeout bumped 60 -> 150 min for the slower arm64-under-QEMU leg.
docker/setup-qemu-action@v3 with platforms: arm64 (was implicit before).
commented
May 24, 2026
|
DGX Spark / linux/arm64 support added via QEMU at build time (e7cfcea). The image is now multi-arch: one Docker manifest with linux/amd64 + linux/arm64 children. What changed:
Arm64 GPU SoCs supported by the new variant:
End-to-end arm64 validation on actual hardware is pending -- the build-time assertion exercises the wheel resolution and the cu128 aarch64 fat binary, but the final proof is |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e7cfceadab
ℹ️ 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".
| print(f"cuda build {torch.version.cuda}") | ||
| print(f"arches {arches}") | ||
| assert "sm_100" in arches, f"sm_100 missing: {arches}" | ||
| assert "sm_120" in arches, f"sm_120 missing: {arches}" |
There was a problem hiding this comment.
Accept sm_121 in smoke-test arch validation
This assertion hard-requires sm_120, but the same commit’s Dockerfile build validation explicitly treats arm64 Blackwell as valid when either sm_120 or sm_121 is present. As written, a valid arm64 build that reports only sm_121 will fail the smoke test with a false negative, even though the image is intended to support GB10/DGX Spark.
Useful? React with 👍 / 👎.
GitHub announced free linux/arm64 hosted runners for public repos (GA Aug
2025) under labels `ubuntu-24.04-arm` / `ubuntu-22.04-arm`. Switching the
arm64 leg from QEMU-on-amd64 to a native arm64 matrix runner is ~3x
faster and avoids QEMU's occasional flakiness on long cu128 installs.
The workflow now:
* builds amd64 and arm64 in parallel on their native runners,
pushing each as a single-arch image *by digest* (no tag)
* stitches both digests into one multi-platform manifest in a
follow-up `merge` job, using `docker buildx imagetools create`
* keeps a separate buildx cache scope per platform to avoid
cross-arch cache collisions
Smoke-test job now needs `merge` (was `build`) so it only runs once the
final manifest is published.
Dockerfile header: replace the speculative aarch64 SASS list with the
verified one from pytorch/pytorch v2.10.0 .ci/manywheel/build_cuda.sh
(8.0;9.0;10.0;12.0 on aarch64), and note that sm_120 is forward-compatible
to sm_121 per PyTorch maintainers -- which is what makes DGX Spark work
without an explicit sm_121 SASS section in the wheel.
setup_qemu.sh / test_locally.sh --platform stay in place: they're for
the local-dev path on x86_64 boxes that don't have arm64 hardware.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 131f1d3065
ℹ️ 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".
Empirical reality (cuobjdump on the downloaded cu128 wheels):
amd64: sm_70 sm_75 sm_80 sm_86 sm_90 sm_100 sm_120
arm64: sm_80 sm_90 sm_90a sm_100 sm_100a sm_120 sm_120a
Earlier comments claimed sm_89 native and a "+PTX JIT to sm_121" fallback;
both are wrong. cu128 wheels ship NO PTX. Ada (sm_89) runs on sm_86 SASS,
B300/GB300 (sm_103) on sm_100, DGX Spark (sm_121) on sm_120 -- all
forward-compat WITHIN a major architecture, which is the canonical CUDA
rule and ptrblck (PyTorch maintainer) confirmed it directly:
"the compatibility ... is also used for e.g. sm_89 with sm_86 and sm_80."
Build-time assertion was `any(a in ("sm_120", "sm_121"))` on arm64. Since
sm_121 is never in any cu128 wheel, the OR was misleading and could mask
a real wheel regression. Tightened to just `assert "sm_120" in arches`
on both arches.
…same class The unreadable-state guard added last round covered the section 1b reader and not the refresh child's, which is the one that runs in the default configuration. The child's redirect fails, LAST stays empty, every notebook is counted kept rather than recorded, and TMPSTATE publishes empty with failed still 0, so the marker is stamped. Section 1b's own recovery drops the marker, which guarantees the child does not exit early and walks straight into it. Reproduced: 3 recorded, then 0 updated and 3 kept, state size 0, exit 0. The test that was meant to prove this passed only because its helper sets UNSLOTH_SKIP_NOTEBOOK_REFRESH=1; the new one does not. The populate merge reader had the same -f-only gate and now requires -r. The rollback test measured the wrong rollback. Across the durability suite drop_unrecordable was called seven times and removed nothing, because every call site handed it either a user-edited file, which its hash gate declines, or a missing one. Mutating its removal to a no-op left the suite green. The unchanged branch is the reachable one that must remove, and reaching it needs notebooks that are valid JSON, since the body-aware comparison can only report SAME for those. Populate no longer publishes a staged state that lost a merge record. Those are the only records for notebooks that exist upstream but not in the baked template and nothing can re-derive them, unlike a failed copy, which the next boot re-walks from the template and which therefore still publishes. Section 1b re-tests its guard inside the loop instead of once, so a doomed rewrite stops restoring, and undoes what it did restore. Those files were absent before it ran, so removing them restores the prior tree exactly, rather than leaving baked content behind a state that describes something else. UNSLOTH_KEEP_REMOVED_NOTEBOOKS keeps the record with the file it keeps, as its KEEP_DELETED sibling already did. Dropping the record while keeping the file made the next refresh read it as a user edit, and turning the option back off never recovered it because by then it is no longer in the state. unsloth_pip_shim.py: seven pip aliases and one uv global were missing from _VALUE_FLAGS, so their separated value was read as the install target and the install forwarded with the protected package kept and no constraint at all. The selfcheck could not have caught them: it scraped --help, which prints one spelling per option, and --python-preference appears in no uv help output. It now introspects pip's own option table, checks uv at all three help levels, probes the undocumented global directly, and fails rather than reporting OK when it cannot inspect something. _is_protected's installed check gains coverage. Deleting it left the suite green, and not by omission: the shared fixture pins _installed_names to an image where every bake succeeded, which is exactly the case where the check cannot fire. The Dockerfile lets the torchcodec and non-amd64 vLLM bakes fail on purpose, so that is the wrong image to test it on.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d5380f95a
ℹ️ 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".
| (?: uv (?:[ \t]+-{1,2}\S+)* [ \t]+ )? | ||
| (?: \S+ [ \t]+ -m [ \t]+ )? | ||
| pip[0-9.]* [ \t]+ | ||
| (?: -{1,2}\S+ [ \t]+ )* |
There was a problem hiding this comment.
Parse option values when scanning install cells
When a valid install places a value-taking option before the subcommand, such as !uv pip --directory /tmp install transformers==5.5.0, this regex consumes only option tokens and therefore returns no pin. The bundled CLI documents --directory <DIRECTORY> as a global option, and uv pip --directory /tmp install --help succeeds; meanwhile the pip shim recognizes and suppresses the Transformers install. Consequently, both the pre-run hook and unsloth-run can start with the base Transformers, and an import later in the same cell permanently freezes the wrong version. Fresh evidence beyond the previously rejected compound-command case is this documented option/value form, which the shim itself was updated to support.
Useful? React with 👍 / 👎.
| _kid = _kid or ("pid-%d" % os.getpid()) | ||
| os.environ["UNSLOTH_NB_TF_MARKER"] = "/tmp/unsloth_nb/requested_transformers." + _kid |
There was a problem hiding this comment.
Clear a reused per-kernel marker before startup
When a Jupyter kernel is restarted, its connection filename—and therefore this marker path—can be reused while the old marker file remains under /tmp; the PID fallback has the same problem after PID reuse. Because the startup path neither removes nor truncates a marker it derives locally, a new kernel whose first cell has no explicit Transformers pin reads the previous kernel's request and activates that stale sidecar before any import. Clear locally derived marker paths on startup while preserving an explicitly inherited marker used by unsloth-run.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d5380f95a
ℹ️ 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".
| keep_args.pop() | ||
| dropped.append(prev_flag + " " + tok) | ||
| elif prev_flag in _REQ_FILE_FLAGS: | ||
| _req_path, _req_rec, _req_drp = _filter_requirements_file(tok) |
There was a problem hiding this comment.
Resolve requirements from uv's effective directory
Fresh evidence after the option-locator fix: when invoked as uv pip --directory /tmp install -r requirements.txt from another directory, this call opens the requirements file relative to the shim's original cwd; on failure, _filter_requirements_file returns the untouched relative path, after which real uv switches to /tmp and installs it without filtering or recording a Transformers pin. uv pip --help documents --directory <DIRECTORY> as “Change to the given directory prior to running the command,” and I confirmed uv resolves -r req.txt from that directory. Resolve relative requirement, constraint, and local-project paths against uv's effective directory before classification.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The premise holds and I confirmed it against uv 0.11.32 directly rather than from the help text: with no requirements.txt in the working directory, uv pip --directory <other> install -r requirements.txt resolved and installed the file from <other>.
Two things beyond what you described, both of which the fix had to cover:
--directoryis a uv global, so it is accepted in every position, not only betweenpipandinstall.uv --directory X pip install ...anduv pip install --directory X ...both work, as does the--directory=Xspelling. uv rejects a repeated--directoryoutright, so there is always exactly one.- uv documents it as
[env: UV_WORKING_DIR=], and that variable alone relocates the file with no flag on the command line at all. The flag wins when both are set, which I checked rather than assumed.
One correction to the impact, because it changes how bad this is. The forwarded install still carries the injected --constraint <protected file> at an absolute path, and that survives the chdir. So a protected package pinned in the relocated file is not silently replaced: uv fails resolution loudly. I tried to reproduce a silent unfiltered install of a pinned protected package through this path and could not. What is genuinely silent is the other half of your sentence, the transformers pin not being recorded, and that I did reproduce: the marker is never written, so the sidecar is never activated and the user gets a hard resolution conflict where the request should simply have worked.
The fix resolves a relative -r or -c path against uv's effective directory before reading it, covering all four argv positions and the environment variable, and leaves pip alone since it has no equivalent and never changes directory. Nested includes follow automatically because the source directory is now derived from the resolved path. On a read failure the original relative path is still forwarded untouched, so uv resolves it itself exactly as before.
I did not change anything for local project paths. _classify_flag_target is pure string classification and never touches the filesystem, so there is nothing there to resolve.
Tests in tests/python/test_unsloth_pip_shim.py cover the four argv positions, UV_WORKING_DIR, the flag beating the variable, a nested include, and a pip regression guard. Seven of the eight fail at 5d5380f; the eighth is the pip guard, which protects behaviour that was already correct and so has no head comparison by design. Mutations of the changed lines, all killed: never resolving, ignoring the variable, ignoring the --directory= spelling, letting the variable beat the flag, and deriving the include directory from the unresolved path.
| # deliberately kept, so the next refresh read it as a user edit -- and | ||
| # turning the option back off never recovered it, because by then it is no | ||
| # longer in LAST. | ||
| record_tmpstate "${LAST[$rel]}" "$rel" || drop_unrecordable "$rel" |
There was a problem hiding this comment.
Retain removed notebooks when state appending fails
When UNSLOTH_KEEP_REMOVED_NOTEBOOKS=1 preserves a pristine notebook that upstream has deleted, this is its only surviving state record. If quota exhaustion or ENOSPC rejects the append, drop_unrecordable deletes the file because its hash matches LAST; unlike an ordinary updated notebook, the clone no longer contains any source from which a retry can restore it. This branch also never increments failed, so the shortened state and remote marker can be published as successful, permanently deleting the notebook the option requested to keep; retain the old record and file while marking the refresh failed instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Correct on both halves, and reproduced at 5d5380f.
Sizing the fault took some care, so for the record: a state record costs 67 + len(rel) = 84 bytes here, so to let the main loop's 499 records through and have the removal loop's single extra append be the only failure, the cap has to satisfy 499 * 84 = 41916 <= cap < 500 * 84 = 42000, and 41 KiB = 41984 is the only multiple of 1024 in that window. At that cap the victim was deleted from disk, was absent from the published state, and $SYNCED was stamped to upstream HEAD with failed at 0 and exit 0.
Both of your specific points check out. Line 616 has already asserted hash_of "$dst" = LAST[$rel] before the branch is reached, so drop_unrecordable's own guard at line 512 can never decline and the rm -f always fires. And this is the only one of the nine record_tmpstate failure handlers in the script with no failed increment, including the EBUSY branch thirteen lines below it, whose comment states the very invariant it breaks: counting it failed is what holds the marker back and makes the retry happen.
One way it is worse than you describe. The deletion does not need the marker to be stamped. At a 40 KiB cap, where twelve other records also fail and failed is 12 so the marker is correctly withheld, the victim is still destroyed, and three subsequent uncapped refreshes recovered it neither with the option on nor with it off. So the missing failed increment is an aggravator and the unconditional drop is the root cause.
One way it is narrower. Line 616 also guarantees the file is pristine, so a notebook the user has edited never reaches this branch at all.
The fix keeps the file and counts the failure. Every other caller may drop a file it could not record, because the clone still holds a copy to republish on the next start. This one may not: upstream deleted it, so the copy in $DEST is the last one in existence.
Something you did not raise that I hit while reproducing this, so I would rather say it than leave it unsaid: the partial append leaves a truncated final line in the published state, which parses as a phantom record for a path named nb. It is inert here, because nb is a directory and hash_of declines it, so I have not changed anything for it.
Test at that 41 KiB window in tests/python/test_docker_nb_refresh_state_durability.py; it fails at 5d5380f on the file being gone. Mutations, both killed: restoring drop_unrecordable, and keeping the file but swallowing the failure.
| # previous record, so it holds no user edit and removing it costs | ||
| # nothing: the next refresh re-copies and re-records it. The unlink | ||
| # also gives back the space that just ran out. | ||
| rm -f "$dst" 2>/dev/null || true |
There was a problem hiding this comment.
Handle EBUSY when rolling back a published notebook
When an existing notebook is a single-file bind mount, the refresh deliberately falls back from mv to an in-place copy, but if the subsequent state append fails this rollback rm returns EBUSY and its failure is ignored. Fresh evidence beyond the earlier record-recovery fix is that the newly published bytes therefore remain while the staged state is published without their record; the next refresh classifies the file as user-edited and can stamp the remote marker, permanently stopping its updates. Preserve and restore the prior bytes, or withhold state publication when the unlink cannot complete.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed in full, and fixed, though not by either of the two remedies you proposed. The reasoning matters, so here it is.
I reproduced the chain on a genuine single-file bind mount rather than a stand-in: docker run -v host_file:container_file, with the parent directory writable and neighbouring files freely creatable and unlinkable, while unlink and rename of the mounted file both return EBUSY and cp through the inode succeeds. That is why the fallback at line 562 exists, and why the rollback at line 578 cannot work on the same file. Under bash -x with line numbers in PS4, all thirteen rollbacks in a capped run were issued from line 578 and all thirteen failed, leaving 500 files published against 487 records. The second, uncapped refresh reported the thirteen as kept (your edits), left failed at 0 and stamped the marker; a third refresh with upstream content genuinely changed showed the file still holding the old bytes. Permanently frozen, exactly as you said.
Neither proposed remedy is an improvement:
Restoring the prior bytes does not unfreeze anything. The file would still carry no record, so the next refresh still takes the empty-record branch and still reads it as a user edit. It would only change which stale bytes it is stuck on, and of the two, the newly published upstream bytes are the fresher.
Withholding the state publication is worse than the bug. With the staged state discarded, $STATE keeps the old records while every notebook the run did update holds new bytes, so on the next refresh each of them mismatches at line 530 and is kept as a user edit. That strands the whole run instead of one file, which is the tradeoff already recorded in the comment at lines 572-573.
The reason neither works is that no further append is possible in the run that loses the record, and any existing file without a record is read as a user edit. So I fixed that second half instead: an unrecorded file that is byte-identical to the clone was never a user edit, and is taken back into the state. It is safe because the bytes on disk already are the bytes we would publish, so nothing of the user's can be lost, and it repairs the orphan class generally rather than this one producer, including the same swallowed rm at lines 583 and 587. Re-running the bind-mount reproduction on the fix: the second refresh adopts all thirteen, records go 487 back to 500, and the third refresh now tracks the changed upstream content instead of freezing.
The honest limit: adoption repairs the file on the next refresh only if upstream has not moved on in between. If it has, the file stays unmanaged. I could not find a way to do better from inside the run that loses the record, and I would rather state that than imply the fix is complete.
Two small corrections to the write-up. The next refresh does not hash the orphan; it takes the [ -z "$rec" ] branch before any hashing. And the first run does increment failed at line 567 and so withholds the marker itself, with the stamp coming from the second refresh, which is what I observed.
Tests in tests/python/test_docker_nb_refresh_state_durability.py: an orphan identical to the clone is adopted, which fails at 5d5380f; and an unrecorded notebook the user really did edit is still left alone and never adopted, which is a regression guard on already-correct behaviour and so has no head comparison by design. Mutations, all killed: adopting unconditionally, never adopting, and comparing the file to itself rather than to the clone.
| mv "$TMPSTATE" "$STATE" 2>/dev/null || { rm -f "$TMPSTATE"; published=0; } | ||
| # recording the commit after a failure makes the next boot exit on remote == last | ||
| if [ "$failed" -eq 0 ] && [ "$published" -eq 1 ]; then | ||
| echo "$remote" > "$SYNCED" 2>/dev/null || true |
There was a problem hiding this comment.
Make the sync marker replaceable across UIDs
When a host-owned notebook bind mount is first populated by a root container and later reused with the documented docker run --user <uid> mode, the initial cp -a leaves $SYNCED root-owned even though the directory is writable by the host UID. After upstream advances, this redirection cannot open the existing marker and its failure is ignored, so the notebooks and state refresh but last remains at the old commit; every subsequent container start clones and reprocesses the entire notebooks repository again. Publish the marker through a same-directory replacement or otherwise preserve the destination directory's owner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, though the mechanism is real and I reproduced it. A root-owned $SYNCED under a uid-writable parent gives EACCES on the redirect at line 654, || true swallows it, and a same-directory create plus rename succeeds where the redirect fails. I also confirmed the real script leaves the marker root-owned after a root populate, because cp -a copies it without going through own_like_dir.
What it needs in order to matter is not something this image ships.
docker run --user <uid> is not documented anywhere. Not in README.md, whose one documented invocation passes only -e, -p, -v and --gpus. Not in docker/run.sh, whose documented env surface has no uid knob and whose final exec docker run never passes --user. Not in the published Docker install docs. The base image has no USER directive at all, and the PR body says the opposite of this under "What this does not cover": services run as root, non-root parity is a follow-up.
It also needs $DEST to be a bind mount, and nothing mounts /workspace/unsloth-notebooks. There is no VOLUME in either Dockerfile, the README mounts $(pwd)/work:/workspace/work, and run.sh mounts $PWD plus the HF and Triton caches. Without that mount the marker never survives to a second container at all, so the root-then-uid sequence cannot arise.
The consequence is narrower than described as well. $STATE is written with a temp plus rename, so it self-heals across uids on the next boot; the marker is the only writer using a direct redirect. Since the state does get published, the re-walk finds every hash matching its record and converges on correct content: this is repeated work, roughly one 219 MB shallow clone per container start in the detached child, not a freeze and not corruption. Bash also reports the failed redirection before applying the 2>/dev/null, so the user sees a Permission denied line on every boot rather than nothing. And every rm -f "$SYNCED" path unlinks the root-owned marker successfully, so a single deleted-notebook restore or populate retry clears it for good.
One thing you have indirectly turned up that I will note rather than fix here: the comment at docker/Dockerfile:552 calls this "documented non-root use", and that documentation does not exist. That is a stale comment rather than a code defect, so I am leaving the behaviour alone.
| rec="${LAST[$rel]:-}" | ||
| if [ -z "$rec" ]; then | ||
| kept=$((kept + 1)) | ||
| continue |
There was a problem hiding this comment.
Migrate state across case-only renames
On a macOS or Windows case-insensitive bind mount, when upstream renames Foo.ipynb to foo.ipynb, the new $dst resolves to the existing old-cased file while LAST still has only the old-cased key. This empty-record branch therefore treats the managed file as a user edit, publishes neither the new bytes nor a replacement state record, and the later CLONED_LOWER check also skips the old record's removal; the refresh can then stamp the commit and permanently stop updates to that notebook. Detect the case-fold-matched prior key here and migrate its content and record to the new spelling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one either, and the control flow is exactly as you describe. I checked it on a real case-insensitive filesystem rather than by reading: ext4 with casefold on a loop mount, running the actual script, with upstream renaming nb/Foo.ipynb to nb/foo.ipynb. $dst resolved onto the existing old-cased file, rec was empty so the empty-record branch kept it, the removal loop then skipped the old record through the CLONED_LOWER check, failed stayed 0 and the marker advanced. Two further boots confirmed the notebook never picks up new upstream content again.
The reason I am not fixing it is the trigger, which this project has never received. unslothai/notebooks has never done a case-only rename. Across all 1442 commits on all refs, git rename detection reports 174 renames and zero case-only ones, and a rename-detection-independent scan that pairs every added path with a removed path having the same lowercased form also finds zero. There are no case-insensitive path collisions at HEAD, and no path has ever existed in more than one casing. The nearest the repo comes are renames that change case together with other characters, such as nb/nemo_gym_sudoku.ipynb to nb/NeMo-Gym-Sudoku.ipynb, where the lowercased paths still differ and no collision arises.
It also needs $DEST bind-mounted from a case-insensitive host, and nothing mounts /workspace/unsloth-notebooks: no VOLUME in either Dockerfile, and neither the README invocation nor docker/run.sh mounts it. On Docker Desktop the container filesystem is itself case-sensitive, so the host would have to be the source of the mount.
One correction to my own comment while I am here, since it would matter to anyone revisiting this: lines 602-603 claim the old path "resolves to the file just published". That premise is wrong, as the run above shows, because the main loop publishes nothing in this case and reports 0 updated. What CLONED_LOWER actually buys is stopping the removal loop from unlinking the live notebook, which would otherwise pass the hash check at line 616 and delete it. So the guard already converts the worst outcome into the milder frozen-and-unmanaged one.
Repo tests (CPU) went red on test_source_read_encoding: the five reads that test_docker_cpu_fallback.py does of run.sh, the two Dockerfiles and the entrypoint used the platform default encoding, so they break on Windows the moment any of those files gains a non-ASCII byte. The sixth open() in the file writes a temp fixture rather than reading a checked-in file, so it is correctly not flagged and is left alone.
uv changes directory before it resolves a relative -r or -c path, so the shim was opening the file from its own cwd, missing, and forwarding the untouched relative path. uv then chdir'd and installed a file the shim had never inspected, recording no transformers pin, so the sidecar never activated and the request failed on the injected constraints instead of working. --directory is a uv global, so it is accepted before pip, between pip and install, and after install, in both the separated and --directory=VALUE spellings; uv rejects it more than once, so there is always exactly one. It is also documented as [env: UV_WORKING_DIR=], and that variable alone relocates the file, with the flag winning when both are set. pip has no equivalent and never changes directory, so nothing changes for it. Nested includes follow, because the source directory is now derived from the resolved path. A read failure still forwards the caller's original path so uv resolves it itself, exactly as before.
Two ways a failed state append could cost a notebook permanently. UNSLOTH_KEEP_REMOVED_NOTEBOOKS dropped the file when its record would not fit. Every other caller may do that, because the clone still holds a copy to republish on the next start. This one may not: upstream had deleted the file, so the copy in the destination was the last one in existence, and no retry recovered it with the option on or off. It was also the only one of the nine record_tmpstate failure handlers with no failed counter, so the truncated state and the sync marker could both be published as a success. Keep the file and count the failure. The publish rollback cannot unlink a single-FILE bind mount, which returns EBUSY there just as it does for the rename the fallback above already works around. The published bytes then stay on disk with no record, and a later refresh reads them as a user edit and stamps the marker over them, so the notebook stops tracking upstream for good. Nothing further can be appended in the run that loses the record, and rolling the bytes back would leave the file just as unrecorded, while discarding the staged state would strand every notebook the run did record. So repair it from the other side: an unrecorded file that is byte-identical to the clone was never a user edit, and is taken back into the state. The bytes on disk already are the bytes we would publish, so nothing of the user's can be lost, and a file that genuinely differs is still left alone.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 359fdc586d
ℹ️ 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".
|
|
||
| global _WORKING_DIR | ||
| _wd = _uv_working_dir(tool, argv) | ||
| _WORKING_DIR = os.path.abspath(_wd) if _wd else None |
There was a problem hiding this comment.
Resolve local targets from uv's effective directory
When a valid command such as uv pip --directory /tmp/work install -e ./unsloth runs from another directory, this stores uv's effective directory only for requirements-file reads; _classify_flag_target → _canon → _local_project_name still resolves ./unsloth against the shim's original cwd. I checked the bundled uv pip install --help, which describes --directory as “Change to the given directory prior to running the command.” The protected project is therefore classified as unknown and forwarded, allowing a matching-version checkout to replace the baked code or otherwise making the valid install fail against the injected constraint. Fresh evidence after the earlier requirements-file fix is that local-project classification still never consults _WORKING_DIR; resolve these paths against it as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed, and this also corrects something I got wrong on the previous round.
In my reply to the requirements-file item I wrote that _classify_flag_target "is pure string classification and never touches the filesystem, so there is nothing there to resolve". That is false. I checked only the body of _classify_flag_target and generalised from it, without following _canon into _local_project_name, which stats the directory at lines 335, 338 and 359 and reads pyproject.toml at line 341. You were right to come back at it.
Reproduced at 359fdc5. With the project present only under --directory, _local_project_name("./unsloth") returns unsloth when resolved from that directory and None when resolved from the shim's cwd, so _classify_flag_target goes from ('drop', None) to ('keep', None) and -e ./unsloth is forwarded to the real tool.
On severity you are right in a way that matters, and it makes this strictly worse than the requirements-file case I fixed last round. There I established that the injected --constraint is an absolute path that survives the chdir, so a protected package is caught loudly. That defence does not hold here, and I tested it rather than assuming: with a constraint pinning a name to the same version the local project declares, uv pip install --dry-run -e ./proj resolves cleanly and installs. It is only rejected when the versions differ. So a checkout whose version matches the baked one replaces the baked code silently, exactly as you describe.
The fix resolves the local path through the same helper as the requirements files, so all four --directory positions and UV_WORKING_DIR are covered, and pip is untouched.
One thing your report did not mention that I found while testing the fix. The stat has to happen on the path with any fragment stripped. #egg= is recognised earlier in _canon and never reaches the directory lookup, but any other fragment does, and ./unsloth#subdirectory=sub arrives intact. I confirmed both spellings still resolve to unsloth, and that a mutant which drops the fragment strip leaks the project. That behaviour predates this change and had no test, so I added one.
Tests in tests/python/test_unsloth_pip_shim.py: the four argv positions, editable and positional forms, UV_WORKING_DIR, the two fragment spellings, plus two guards. Seven fail at 359fdc5. The two guards do not, and I want to be explicit about that rather than let the count imply otherwise: a local project relative to the cwd is still classified, and an unprotected local project still reaches the real tool. Both protect behaviour that was already correct, so neither has a possible head comparison and the mutation is their only evidence.
Mutations of the changed line, all killed: resolving from our own cwd, keeping the fragment attached, and never identifying a local project at all. The first table I ran had the fragment mutant SURVIVING, which is what prompted the test above.
| # Adopting the record costs nothing, because the bytes on disk already | ||
| # ARE the bytes we would publish, so nothing of the user's can be lost. | ||
| adopted="$(hash_of "$dst")" | ||
| if [ -n "$adopted" ] && [ "$adopted" = "$(hash_of "$f")" ]; then |
There was a problem hiding this comment.
Preserve recovery when upstream advances before retry
When a state append fails after the single-file bind-mount fallback publishes notebook bytes from upstream commit A, and upstream advances to commit B before the next container start, this equality check cannot adopt the unrecorded A copy. Because the truncated state has no prior record, the branch then treats A as a user edit, omits it from state again, and stamps B's sync marker with failed == 0, permanently stopping updates to a notebook the user never edited. Fresh evidence after the rollback fix is that its new recovery succeeds only while the upstream bytes remain unchanged; preserve enough provenance to recover the published copy across upstream revisions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and reproduced end to end. I am not fixing it in this PR, and I want to set out exactly why rather than let a thumbs-up imply a fix is coming quietly.
Reproduced on the real single-file bind mount: publish from commit A under a state-append cap leaves thirteen orphans, upstream then changes the orphaned path to B, and the next refresh reports them as kept (your edits), leaves failed at 0, stamps B's marker, and the notebook is still holding A's bytes two commits later with the user having edited nothing.
One refinement and one aggravation:
The precondition is not "upstream advances", it is "upstream changes that path". If upstream moves but leaves the path alone, adoption still fires and the notebook recovers, which I confirmed as a control.
It is worse than you state in one respect. The body-aware escape hatch at line 549 is gated on [ -n "$rec" ], so the orphan branch continues before reaching it. Adoption is strict byte equality, which means even a purely cosmetic header or footer rewrite of the orphaned path defeats it, and those are routine upstream.
Now the part that decides it. The remedy as written, "preserve enough provenance to recover the published copy", requires a durable write in exactly the run whose write just failed. I measured what is writable on a full ext4 filesystem at that moment: the content write fails, a fresh file fails, mkdir fails, and setting an xattr fails. Under RLIMIT_FSIZE or a per-user quota a side file does succeed, but ENOSPC is the case the rollback exists for, so a side-channel record covers the easy half and silently fails on the hard half, which is the same shape as the bug it would be fixing.
Withholding the marker while an unrecorded file sits at a clone path does not work either, and this one I tested rather than argued. A user who bind-mounts a directory already holding their own copy of an upstream notebook, which lines 251-255 explicitly support, is orphan-shaped permanently: unrecorded and different from the clone, byte for byte the same signal as a real orphan. Under that rule their container would re-clone and re-walk on every start forever and never stamp the marker again.
That leaves one thing that actually works, and it is not provenance we save, it is provenance upstream already keeps: match the orphan against the history of that path rather than only against HEAD, by deepening the shallow clone when and only when an unrecorded differing file appears. I prototyped the lookup and it is cheap in isolation, roughly five seconds and twenty megabytes for a fifty-commit deepen, with four historical versions per path to test. The reason I am not shipping it here is that its trigger fires for the legitimate user-edit case above, which is common, so every refresh for those users pays that cost to recover a case that needs a single-file bind mount and a failed state append and an upstream change to that exact path before the next boot. That is a real cost on a common path to fix a compound-rare one, and it is a design decision rather than a patch.
There is also a bigger instance of this same class that argues for doing it properly rather than widening this branch now. No disk-full is needed at all: the refresh publishes notebooks one at a time and publishes the state once at line 672, so an ordinary docker stop part-way through strands everything already written. I killed a refresh two seconds in and got thirty-five notebooks holding new upstream bytes against stale records, with the marker stamped over them on the very next boot and no recovery afterwards. Those take the [ -n "$rec" ] branch at line 544, so the adoption check never sees them, and no amount of extending adoption reaches them. The right answer to both is one reconciliation pass that can re-derive a record from upstream history, not two special cases.
So: the finding stands, the shipped fix remains a strict improvement over freezing every orphan, and I would rather leave the residual visible and documented than close it with a mechanism that fails on the exact filesystem that produces it.
|
|
||
| - name: Boot the full image and probe Studio + Jupyter | ||
| run: | | ||
| TAG="$(jq -r '([.tags[] | select(contains(":sha-"))] | first) // .tags[0] // ""' <<<"$STEPS_META_STUDIO_JSON")" |
There was a problem hiding this comment.
Key smoke images by the full build inputs
In the inspected docker-publish.yml, two workflow-dispatch runs from different refs can share the same github.sha while supplying different zoo, notebook, or llama overrides; their concurrency groups differ by ref, but both publish the same short :sha-<commit> and :core-sha-<commit> tags. This selection can therefore pull an overlapping run's manifest if that run retags the shared SHA name before the pull, causing both the Studio probe here and the base probe above to validate an image other than the one their jobs built. Export the Studio manifest digest as is already done for the base build, and smoke-test both images by digest or by a tag incorporating all resolved inputs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed. The diagnosis is right and the mechanism is worse than the report frames it, so I want to record what I verified.
The export asymmetry is real: merge declares outputs.digest and computes it, merge-studio declared no outputs and computed nothing.
The collision is real and does not need workflow_dispatch. The concurrency group is docker-publish-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}, keyed on the ref and, only on main, the sha, and never on the inputs. So two runs at one commit from two different refs are in different groups and are never serialised against each other. That is reachable through the ordinary release flow rather than a hand dispatch: four of the last five v* tags in this repo are lightweight, so the tag ref resolves to the commit itself and a tag push carries the same github.sha as the main push of that commit. type=sha,format=short then produces byte-identical core-sha-<short> and sha-<short> names from both runs, and the release history shows the tag being cut about sixty seconds after the commit lands, against builds that run for ninety and a hundred and fifty minutes. They overlap for essentially their whole duration.
The consequence is larger than the smoke test. Both probes are behind if: ${{ vars.HAS_GPU_RUNNER == 'true' }} on a [self-hosted, gpu] runner, and this repo has no such variable and no self-hosted runner, so as merged they cannot execute. The ungated path is the one that matters: merge resolves the base digest by inspecting that same colliding :core-sha- name and hands the result to build-studio as BASE_IMAGE, which then publishes as :latest and :studio. If the other ref's run retags between this run's imagetools create and its inspect, this run bakes the other run's base image, silently. That also makes the invariant the file asserts about itself false as written: :core-sha- is immutable across commits, which is the case the tag choice was defending, but not across refs at one commit.
What I did:
Both merge jobs now verify rather than trust. After resolving the digest they inspect the manifest and confirm it contains the per-arch digests this run actually pushed, and fail loudly if it does not. That converts a silent wrong base into a build failure, which matters more than the tag selection itself, because no tag choice can be made collision-proof while two refs legitimately share a short sha.
merge-studio now exports its digest, closing the asymmetry, and both smoke probes pull by digest rather than re-deriving a name.
Resolving by digest also made the two docker/metadata-action steps in smoke-test dead, so I removed them along with the comment requiring their enable= expressions to stay byte-identical to the merge jobs' gates. That coupling only existed because the probes re-derived tags, and it was a standing trap.
I did not adopt --metadata-file on imagetools create, which is the other way to get the digest. The buildx available here does not offer it on that subcommand, and setup-buildx-action is unpinned, so depending on a flag I cannot verify would be trading a verified failure for an unverified one.
On evidence, I want to be straight about the limits. I cannot exercise this workflow: it is introduced by this PR, is not on main, has no prior runs, and the probes are gated off with no runner. So there is no end-to-end proof, only the repo's own workflow-parsing harness. tests/python/test_docker_publish_ref_freeze.py now runs the digest export against a stubbed docker and asserts it refuses a manifest that does not contain this run's arches; that test fails without the verification. I also updated the two existing digest-export tests, which my change correctly broke, and confirmed actionlint reports exactly the same findings before and after, so needs.merge-studio.outputs.digest resolves and no new lint appeared.
One caveat worth stating: pulling by digest means the smoke test no longer incidentally proves the published tag resolves to the built image. If that is wanted it needs its own assertion.
| [ "$_LOCK_HELD" = "1" ] && return 0 | ||
| command -v flock >/dev/null 2>&1 || return 0 | ||
| # group-redirect: bash reports a failed exec redirection before applying it | ||
| { exec 9>>"$LOCK"; } 2>/dev/null || return 0 |
There was a problem hiding this comment.
Keep the sync lock writable across container UIDs
When a root container is the first process to sync a host-writable notebook volume, this append creates .unsloth_sync.lock as root-owned mode 0644 under the normal umask. A later container using the documented --user <uid> mode cannot reopen that file for append, so this failure path returns success with _LOCK_HELD still false; if two such containers share the volume, both then rewrite notebooks and the state concurrently even though the lock is explicitly intended to serialize that case. I reproduced the ownership transition independently: creation produced 644 0, and reopening as another UID failed. Create the lock with cross-UID-safe permissions or safely replace an inaccessible stale lock rather than silently running unlocked.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanical description is accurate and I reproduced it: a root first boot creates .unsloth_sync.lock as 0644 root:root under the default umask, a later --user <uid> boot cannot reopen it for append, the group-redirect at line 133 returns 0, and _LOCK_HELD stays 0 with nothing printed. All three of those check out.
The reason it is not a defect is that the proposed remedy does not do what it is meant to do. I applied it and measured: with the lock file at 0666, cross-UID-writable exactly as suggested, and another process holding an exclusive flock, lock_acquire still returns rc=0 with _LOCK_HELD=0 after LOCK_WAIT expires, silently. Making the permissions cross-UID-safe does not remove the silently-unlocked path, it moves the exit from line 133 to line 134.
And line 134 is not new ground. It was raised on this PR as comment 3659022317, "Stop syncing when the notebook lock times out", against this same function, and answered in 3792888156. The short version of that answer still holds in the tree at 359fdc5: running unlocked cannot lose an edit. A run records only the bytes it wrote itself (staged="$(hash_of "$new")" at line 567), every publish is guarded by hash_of "$dst" != "$rec" which keeps the user's copy (line 568), and every state publish is an atomic same-directory mv. So two unlocked concurrent runs produce over-protection, a notebook stranded as user-edited, rather than the concurrent rewrite the report describes. That is a materially weaker consequence than stated.
Fail-open is also the tested contract rather than an oversight. tests/python/test_docker_nb_sync_race.py:54 pins it, and its message names this exact case: "a host without flock, or a $DEST that cannot hold the lock file, must fall back to running unlocked rather than failing the boot". Failing closed instead would skip the first-boot populate and leave the container with no notebooks at all.
On the trigger, I re-derived the environment facts rather than reusing last round's ruling, and they hold. docker run --user appears in no Markdown file, no user-facing documentation and not in the PR body; docker/run.sh never passes it; there is no USER directive in docker/Dockerfile and Dockerfile.studio sets USER root directly under the comment that non-root parity is a follow-up. PR body line 86 says the same.
Two corrections to my own previous reply on the sibling $SYNCED item, since I would rather fix them than leave them standing. I said flatly that two containers cannot share the notebooks directory. That is too strong. Nothing the project ships or documents makes them share it, there is no VOLUME in either Dockerfile and neither the README invocation nor run.sh mounts it, so under the shipped defaults the directory lives in the container's private overlay. But a user who supplies their own -v over /workspace, or points UNSLOTH_NOTEBOOKS_DIR at one of the two paths that are mounted, can share it. The conclusion is unchanged; the reasoning was overstated. Relatedly, docker/Dockerfile:621 carries a bare comment inviting a /workspace volume, which is another place the code anticipates something the docs never describe.
The full trigger this needs is compound: a persistent shared mount over the destination, a first boot as root, later boots as --user, and two of those concurrent. A volume first written by a --user boot locks correctly, and two root boots lock correctly against each other; only the mixed ordering breaks, and mixed ordering is what line 86 defers.
The requirements-file fix stored uv's effective directory but only used it for `-r` and `-c` reads. A local project target is a filesystem lookup as well: _classify_flag_target goes through _canon into _local_project_name, which stats the directory and reads its pyproject.toml to learn the real project name. That lookup still resolved against our own cwd, so `uv pip --directory X install -e ./unsloth` run from elsewhere reported the protected project as unknown and forwarded it. This one is silent where the requirements-file case was loud. The injected constraints file survives the chdir and rejects a protected package, but only on a version MISMATCH: a local checkout declaring the same version as the baked one resolves cleanly and installs over it. The stat also has to happen on the path with any fragment stripped. `#egg=` is recognised earlier in _canon and never reaches the directory lookup, but every other fragment arrives intact, and leaving it attached makes the stat miss and leaks the project. That behaviour predates this change and had no test.
The sha tags are immutable across commits, which is what the tag selection in the digest export was defending against, but they are not unique across refs. The concurrency group is keyed on the ref and, only on main, the sha, never on the inputs, so a branch push and a lightweight v* tag push at one commit sit in different groups and never wait for each other. Four of the last five v* tags in this repo are lightweight, so the tag ref is the commit and both runs emit byte-identical core-sha-<short> and sha-<short> names, about a minute apart, against builds that run for 90 and 150 minutes. The smoke probes are gated behind HAS_GPU_RUNNER and cannot currently run. The path that does run every push is the base digest export, whose result is baked into the Studio image as BASE_IMAGE and published as :latest and :studio. If the other ref retags between this run's manifest creation and its inspection, this run ships another run's base image with nothing to show for it. So both merge jobs now confirm the manifest they resolved contains the per-arch digests this run pushed, and fail if it does not. No tag choice can be made collision-proof while two refs legitimately share a short sha, so the check is the part that matters. merge-studio also exports its digest, which it never did, and both probes pull by digest instead of re-deriving a name. That made the two metadata-action steps in smoke-test dead, so they are gone, along with the requirement that their enable= expressions stay byte-identical to the merge jobs' gates. That coupling only existed because the probes re-derived tags. This workflow has no runs yet and its probes are gated off, so there is no end-to-end evidence, only the workflow-parsing tests: the digest export is driven against a stubbed docker and must refuse a manifest that does not hold this run's arches.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7011c01353
ℹ️ 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".
| os.execv(REAL[tool], [REAL[tool]] + argv) | ||
| return | ||
|
|
||
| head, tail = argv[: i + 1], _expand_short_clusters(argv[i + 1 :]) |
There was a problem hiding this comment.
Bypass filtering for installs aimed at another environment
When a notebook runs a command such as uv pip install --python /tmp/venv torch==... or pip --python /tmp/venv install torch==..., the shim recognizes the install and unconditionally filters its targets as though they would modify the baked venv, so it drops Torch and can report success while leaving the requested environment empty; the same issue affects --target/--prefix, and the earlier uv pip sync guard also rejects syncs aimed at another environment. I checked the bundled CLI help: pip describes --python as running with the specified interpreter and --target as installing into the specified directory, while uv describes --python as the interpreter into which packages are installed. Detect whether these destination options resolve to the protected base venv and bypass stack filtering otherwise.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed. Reproduced at 7011c01 across every spelling, and the failure is the silent one: the shim recognises the install, filters the protected target out of it, finds nothing left, prints "nothing to install after keeping the baked stack; ok." and returns 0 having installed nothing into the environment the caller named.
I confirmed the premise against the real tools rather than the help text. pip --python <venv>/bin/python install idna==3.6 put 3.6 in that venv and left the base at 3.18, and pip install --target <dir> idna==3.7 wrote into the target directory. So the justification for filtering, that the install would replace the baked stack, is simply false for these.
Two things beyond what you listed:
--root behaves the same way as --target and --prefix and was equally affected.
The destination also moves with nothing on the command line. pip honours PIP_<OPTION> for every option, and uv documents --python as [env: UV_PYTHON=]. I verified both: PIP_TARGET redirected a plain pip install, and UV_PYTHON put idna 3.5 in the target venv while the base stayed at 3.18. PIP_TARGET, PIP_PREFIX, PIP_ROOT, UV_PYTHON and PIP_PYTHON are all handled now.
On the design, I made the bypass deliberately one-sided. It fires only for a destination that positively resolves OUTSIDE the guarded venv. A bare --python python3 or --python 3.12 may well name the baked interpreter, and a --target pointing inside the venv is still the venv, so both keep today's protective filtering. Getting this wrong in the permissive direction would hand over the exact thing the shim exists to prevent, so anything ambiguous stays filtered.
The check sits ahead of the uv pip sync refusal too, since you were right that it rejected syncs aimed elsewhere: pointed at another environment there is no baked stack for sync to strip.
One existing test changed and I want to flag it rather than let it pass unremarked. test_value_taking_options_before_install_do_not_lose_the_command[python] used uv pip --python /usr/bin/python3 install snac and asserted a --constraint pair was injected. Under this change that install is deliberately bypassed, so the assertion no longer holds. That test is about the subcommand search not stopping at a flag's VALUE, and /usr/bin/python3 was incidental to it, so I pointed the case at /opt/unsloth-venv/bin/python instead: same parser path, same assertion, and it now exercises a destination that really is the guarded venv. The redirecting form is covered by the new tests. I did not weaken the assertion.
Tests in tests/python/test_unsloth_pip_shim.py: eleven argv spellings including --target=, -t separated and -t attached, the four environment variables, a sync aimed elsewhere, and six guards. Sixteen fail at 7011c01. The six guards do not, by design, and I will say so plainly rather than let the count carry an implication: plain pip and uv installs, the two bare-name interpreters, and the two in-venv destinations all protect behaviour that was already correct, so they have no possible head comparison and the mutation table is their only evidence.
Mutations, all killed: never bypassing, always bypassing, ignoring the directory environment variables, ignoring the interpreter environment variables, letting a bare name buy a bypass, and dropping the exemption for destinations inside the guarded venv.
--target, --prefix, --root and --python send the install somewhere other than the venv this shim guards, so the reason for filtering does not apply. The shim filtered anyway: it recognised the install, dropped the protected target, found nothing left to run, printed "nothing to install after keeping the baked stack; ok." and returned 0 having installed nothing into the environment the caller named. Verified against the real tools rather than their help text: `pip --python <venv>/bin/python install idna==3.6` puts 3.6 in that venv and leaves the base at 3.18, and --target writes into the target directory. The destination also moves with nothing on the command line. pip honours PIP_<OPTION> for every option and uv documents --python as [env: UV_PYTHON=]; PIP_TARGET redirected a plain `pip install` and UV_PYTHON redirected a plain `uv pip install` in the same way, so PIP_TARGET, PIP_PREFIX, PIP_ROOT, UV_PYTHON and PIP_PYTHON are all recognised. The bypass is one-sided on purpose. It fires only for a destination that positively resolves outside the guarded venv, because getting this wrong in the permissive direction hands over the exact thing the shim exists to prevent. A bare `--python python3` or `--python 3.12` may name the baked interpreter, and a --target inside the venv is still the venv, so both keep filtering. It sits ahead of the `uv pip sync` refusal too: pointed at another environment there is no baked stack for sync to strip. One existing case moved with the behaviour. The subcommand-search test used `uv pip --python /usr/bin/python3 install snac` and asserted the protected constraints were injected; that install is now deliberately bypassed. The test is about not stopping at a flag's value, and the interpreter was incidental, so it now points at /opt/unsloth-venv/bin/python: same parser path, same assertion, and a destination that really is the guarded venv.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9ba9cb1f3
ℹ️ 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".
| # pip honours PIP_<OPTION> for every option and uv documents --python as | ||
| # [env: UV_PYTHON=]; both redirect with nothing on the command line at all. | ||
| _DEST_DIR_ENV = ("PIP_TARGET", "PIP_PREFIX", "PIP_ROOT") | ||
| _DEST_PYTHON_ENV = ("UV_PYTHON", "PIP_PYTHON") |
There was a problem hiding this comment.
Scope destination variables to the invoked installer
When UV_PYTHON points outside the base venv but the notebook invokes pip install, _installs_elsewhere() treats the uv-only variable as a pip redirection and bypasses all stack filtering, allowing commands such as pip install torch==... to replace the baked CUDA stack. The inverse applies to PIP_PYTHON with uv. I checked the bundled CLIs: uv documents --python with [env: UV_PYTHON=], while pip ignores UV_PYTHON (and uv ignores PIP_PYTHON). Fresh evidence in the destination-bypass fix is that both variables are collected unconditionally; select the applicable environment variables based on tool.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and this one is mine from the previous round. Fixed.
I confirmed the scoping against both CLIs rather than from their help text, using a package present in the base environment but absent from the target venv, so "already satisfied" means the base was targeted and "Would install" means it was not:
pip install --dry-run idna==3.18withUV_PYTHONset reportedRequirement already satisfied: idna==3.18 in <base>. pip ignores it.- the same command with
PIP_PYTHONset reportedCollecting idna==3.18andWould install idna-3.18. pip honours it. uv pip install --dry-run idna==3.18withPIP_PYTHONset reportedUsing Python 3.13.12 environment at: <base>. uv ignores it.- the same with
UV_PYTHONset reportedUsing Python 3.13.12 environment at: v1. uv honours it.
So pip install torch==... with UV_PYTHON set was granted a bypass on a variable pip never reads, and the install then landed in the baked venv with no filtering and no constraints at all. That is the permissive direction, and it is worse than the bug the bypass was written to fix: the case I was fixing left an unrelated environment empty, this one replaces the CUDA stack the image is built on. Bypasses now come only from variables the invoked tool actually reads.
Two things I checked while scoping it that your report did not cover:
uv ignores PIP_TARGET, PIP_PREFIX and PIP_ROOT as well, not just PIP_PYTHON; all three left uv pip install pointed at the base environment. So the directory variables needed scoping too, and they are now pip-only.
uv has no environment form for its own --target or --prefix. I checked the help for both and neither carries an [env: ...], so there is nothing to add on the uv side beyond UV_PYTHON. I also confirmed the three pip directory variables really do redirect, with real installs rather than dry runs, since --dry-run reports "already satisfied" for PIP_PREFIX from the current environment and would have made it look ignored: PIP_TARGET wrote to <dir>/idna, PIP_PREFIX to <dir>/lib/python3.13/site-packages/idna, and PIP_ROOT to <dir><base>/lib/python3.13/site-packages/idna.
I left the command-line FLAGS unscoped deliberately. A tool that does not accept a flag fails loudly on it rather than silently doing the wrong thing, so there is no silent-bypass risk there, and scoping them would add a second table to keep in step with two CLIs for no gain.
Tests in tests/python/test_unsloth_pip_shim.py: five cross-tool cases, pip with UV_PYTHON and uv with each of PIP_PYTHON, PIP_TARGET, PIP_PREFIX and PIP_ROOT, all asserting the baked torch is NOT forwarded. All five fail at c9ba9cb. The four existing same-tool cases still pass, which is the point: the real redirections keep working.
Mutations, all killed: both variable tables unscoped, the interpreter variables swapped so each tool reads only the other's, and each table emptied.
| # exactly what the option was set to preserve, unrecoverably -- not by a | ||
| # retry, not by turning the option back off. Counting it failed holds the | ||
| # marker back so the next start retries the record. | ||
| record_tmpstate "${LAST[$rel]}" "$rel" || failed=$((failed + 1)) |
There was a problem hiding this comment.
Preserve the old record when keeping a removed notebook
When UNSLOTH_KEEP_REMOVED_NOTEBOOKS=1 and this append fails from quota exhaustion or ENOSPC, incrementing failed withholds the marker but the truncated $TMPSTATE is still moved over $STATE. On the next start the removed file is absent from both the clone and LAST, so neither loop can retry its record; that run stamps the marker, leaving the notebook permanently unmanaged and preventing a later run with the keep option disabled from removing it. Fresh evidence after the prior fix is that it preserves the file but still publishes the state without its only record; retain the prior state when this unrecoverable append fails.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The diagnosis is correct and I reproduced it exactly. The remedy is not, and I measured that rather than argued it, so let me give you the numbers.
The mechanism first. $TMPSTATE is moved over $STATE at line 672 unconditionally; failed is read only at 674 and gates the marker alone. The main loop walks the clone (done < <(find "$TMP" -type f -print0) at 604), and the removal loop iterates "${!LAST[@]}" at 624, so a path that is in neither is visited by neither. My run: run 1 under a 41 KiB cap keeps the file and loses its record, run 2 stamps the marker with the file still unrecorded, and run 3 with UNSLOTH_KEEP_REMOVED_NOTEBOOKS unset still does not remove it, because the rm -f "$dst" at 647 is inside that same LAST loop. Permanently unmanaged, as you say.
Now the remedy. "Retain the prior state when this unrecoverable append fails" is the option I rejected in an earlier round for stranding the run, so I swept it across seven cap sizes against the status quo under an identical fault, with upstream rewriting every notebook and deleting one:
| cap | status quo | Codex remedy |
|---|---|---|
| 41984 | 1 unrecorded, 0 stranded | 0 unrecorded, 499 stranded |
| 33600 | 1, 0 | 0, 400 |
| 25200 | 1, 0 | 0, 300 |
| 16800 | 1, 0 | 0, 200 |
| 8400 | 1, 0 | 0, 100 |
| 4200 | 1, 0 | 0, 50 |
| 42000 (control, nothing fails) | 0, 0 | 0, 0 |
The stranded count equals the number of notebooks the run had already published, every time. Discarding the staged state leaves $STATE describing bytes that are no longer on disk, so on the next refresh each of those fails hash_of "$dst" != "$rec" at line 544 and is kept as a user edit; refreshes 3 and 4 report the identical count and the marker is stamped, so it is permanent rather than transient. At the exact window you are reasoning about, the remedy trades 1 unmanaged notebook for 499 stranded ones. So I am not taking it as written.
Two variants do work, and I want to record them rather than leave the finding looking unfixable:
Discard AND roll back what the run published, the way section 1b's undo_restores already does. Measured at 0 stranded and 0 unmanaged. It works because it stops the tree from describing a state that was just thrown away, which is the hazard your version runs into.
Better, and cheaper: append the unrecoverable records BEFORE the main publish loop consumes the quota. The records the removal loop protects are the ones nothing can re-derive, since upstream deleted the file, whereas a main-loop record that fails to append is re-derivable, because the file is rolled back at 592 and the next refresh re-copies it from the clone. That is exactly what the status-quo column shows: 0 stranded at every cap. Reordering converts the unrecoverable loss into the recoverable one, with no discard and no rollback bookkeeping. Everything the removal loop reads is already available before the main loop starts: LAST is built at 458, CLONED_LOWER does its own independent find at 618, $TMPSTATE is staged at 485, and the two loops touch disjoint paths because the removal loop only handles rel that is absent from the clone. Only the removed=0 counter at 613 would need hoisting.
I have not made that change here. It reorders the two main loops of the file in this PR with the longest defect history, the trigger needs ENOSPC together with the keep option together with an upstream deletion, and the file itself is never lost in any of this, it only stops being tracked. That is a structural change I would rather make deliberately than fold into a review round, and it belongs with the reconciliation work already queued from the earlier docker stop finding, which strands notebooks through the same publish-then-record ordering with no disk-full needed at all. Flagging it rather than quietly leaving it.
The destination bypass collected PIP_ and UV_ variables unconditionally, so `pip install torch==...` with UV_PYTHON set was granted a bypass on a variable pip never reads, and the install then landed in the baked venv with no filtering and no constraints. That is worse than the bug the bypass was written to fix: that one left an unrelated environment empty, this one replaces the CUDA stack the image is built on. Measured against both CLIs, using a package present in the base environment and absent from the target venv so "already satisfied" means the base was targeted: pip with UV_PYTHON reported already satisfied from the base, pip with PIP_PYTHON reported "Would install", uv with PIP_PYTHON reported "environment at: <base>", and uv with UV_PYTHON reported "environment at: v1". uv also ignores PIP_TARGET, PIP_PREFIX and PIP_ROOT, and has no environment form for its own --target or --prefix, so the directory variables are pip-only. The three pip directory variables were confirmed with real installs rather than dry runs, because --dry-run reports "already satisfied" for PIP_PREFIX from the current environment and would have made it look ignored. Command-line flags stay unscoped: a tool that does not accept one fails loudly rather than silently doing the wrong thing, so there is no silent bypass to prevent there.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4eb5aea08d
ℹ️ 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".
| if any(not _inside_base_venv(d) for d in dirs): | ||
| return True |
There was a problem hiding this comment.
Resolve destination paths from uv's effective directory
When uv is invoked from another cwd as uv pip --directory /opt/unsloth-venv install --target lib/python3.12/site-packages torch==..., this check resolves the relative target against the shim's original cwd and incorrectly concludes that the install is elsewhere. I checked the available uv 0.12.1 help, which documents --directory as changing directory before running the command, so uv actually writes into the protected base venv after this bypass executes it without filtering or constraints, allowing the baked Torch/CUDA stack to be replaced. Resolve relative destination and interpreter paths against uv's effective directory before deciding to bypass protection.
Useful? React with 👍 / 👎.
| if body == flag or body.startswith(flag + " "): | ||
| target = body[len(flag) :].strip() | ||
| elif body.startswith(flag + "="): | ||
| target = body[len(flag) + 1 :].strip() | ||
| elif not flag.startswith("--") and body.startswith(flag) and len(body) > len(flag): | ||
| target = body[len(flag) :].strip() |
There was a problem hiding this comment.
Parse quoted requirement-file option values
When a requirements file contains a valid quoted option value such as -e "./unsloth", this parser returns the quotes as part of the target instead of applying the shell-style parsing used by pip and uv. _local_project_name() consequently stats a nonexistent quote-containing path, classifies the protected project as ordinary, and forwards the original editable install; a checkout reporting the baked version satisfies the injected version constraint and replaces the image's tested Unsloth code. I confirmed both the available pip and uv accept quoted -r option values in requirements files, so option targets need to be unquoted with equivalent parsing before classification and include rewriting.
Useful? React with 👍 / 👎.
| m = _PY_M_PIP.match(body) | ||
| if m: | ||
| out.append(m.group(1) + "!" + m.group(2) + m.group(3) + tail) |
There was a problem hiding this comment.
Preserve explicitly selected Python environments
When a notebook runs !/tmp/venv/bin/python -m pip install ..., this transformer discards the explicitly selected interpreter and executes pip from the image's PATH instead. The destination-bypass logic cannot recover the lost path, so ordinary packages are installed into the shared base venv while the requested venv remains unchanged, and protected-only requests can misleadingly report success without installing anything. Python 3.13's checked --help confirms that -m runs the module through the invoked interpreter; restrict rewriting to the current/base interpreter, or translate other paths into the shim's supported --python form.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4eb5aea08d
ℹ️ 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".
|
|
||
| def main(): | ||
| tool = "uv" if os.path.basename(sys.argv[0]).startswith("uv") else "pip" | ||
| argv = sys.argv[1:] |
There was a problem hiding this comment.
Filter requirements supplied through pip environment variables
When PIP_REQUIREMENT is set and the CLI also names any ordinary target, such as PIP_REQUIREMENT=/tmp/req.txt pip install packaging, this scan sees only packaging and executes the real pip with the environment-supplied requirements file untouched. I checked the available pip: pip install --help documents -r/--requirement, and a dry run with only PIP_REQUIREMENT=r.txt consumed that file. A same-version editable or direct-reference protected package in the hidden file can therefore replace the baked Unsloth/Torch stack despite the injected version constraints; incorporate pip's effective environment options into filtering or reject/clear uninspected requirement inputs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed. Reproduced exactly as you describe, and the surface is wider than the report.
Measured against the bundled pip, using the no-target error as the control:
pip install --dry-runwith nothing set reportsERROR: You must give at least one requirement to install.PIP_REQUIREMENT=r.txt pip install --dry-runreportsWould install idna-3.6, so the variable really is a hidden-r.PIP_REQUIREMENT=r.txt pip install --dry-run packagingreports bothpackagingalready satisfied andWould install idna-3.6, which is your case: the scan sees onlypackagingand the file goes to the real pip uninspected.
Three things beyond what you listed:
PIP_EDITABLE is the same hole. PIP_EDITABLE=<project> pip install --dry-run reported Would install dummyproj26-1.2.3 against that same no-target control, so an editable protected package can arrive with nothing on the command line either. It is fixed alongside the requirements one.
Both variables are whitespace separated when they carry more than one value. PIP_REQUIREMENT="one.txt two.txt" installed from both, so handling only the first would have left a hole.
You were right that the injected constraints do not save this, but not because they are overridden. I checked: a CLI --constraint still binds when PIP_CONSTRAINT is also set, and the two simply conflict rather than one winning, and the same holds for uv with UV_CONSTRAINT. What actually defeats them is the case I confirmed in an earlier round, a same-version editable or direct reference, which resolves cleanly against a matching pin. So the constraint file is intact; it just cannot see this.
The fix folds the variables in as ordinary -r and -e flags so they go through exactly the same filtering as the command line, and clears them from the child environment so the real tool cannot consume them a second time next to our filtered copy. uv is untouched: I checked its help and it has no environment form for --requirements, so folding one in there would hand uv a file it was never asked for.
One thing I did NOT fix, and I would rather state it than let it look complete. The same input can arrive through pip's config file: with PIP_CONFIG_FILE pointing at a pip.conf containing [install] requirement = ..., pip install --dry-run reported Would install idna-3.6 with nothing on the command line and no variable set. I also checked whether setting the variable empty neutralises the config value, and it does not, so there is no free way to cover both. Covering it properly means either parsing pip's config search path or shelling out to pip config list, which does report install.requirement=..., at the cost of a subprocess on every install. I scoped this change to the environment vector because that is what is demonstrably reachable from a notebook, and a hand-written pip.conf is deliberate configuration rather than an accident. Flagging it so the gap is on the record rather than discovered later.
Tests in tests/python/test_unsloth_pip_shim.py: a hidden requirements file alongside a CLI target, a hidden editable, two files in one variable, and two guards. Three fail at 4eb5aea. The two guards do not, and I will say so plainly rather than let the count imply otherwise: uv ignoring a pip-only variable, and the ordinary no-variable case staying byte-identical and not switching to execve, both protect behaviour that was already correct and have no possible head comparison, so the mutation table is their only evidence.
Mutations, all killed: never folding, folding for uv as well, folding without clearing the variable, ignoring the cleared environment at exec time, treating the variable as one path instead of a whitespace separated list, and handling the requirements variable but not the editable one.
| fi | ||
|
|
||
| # shellcheck disable=SC2086 | ||
| "$PY" -m pip install -U $NO_DEPS $SPECS |
There was a problem hiding this comment.
Roll back the Studio venv when validation fails
When the newly installed release is missing a dependency under the default --no-deps mode or otherwise fails the import check below, this command has already overwritten the working Studio environment. Avoiding an immediate supervisor restart preserves only the currently running process; the next container or service restart loads the broken files and can leave Studio in FATAL, including when the Studio home is persisted. Stage or back up the update and restore the previous environment when installation or post-install validation fails.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The diagnosis is right and I reproduced all of it. I have fixed the part I can defend and not the part you asked for, so here is the reasoning and the evidence.
Reproduced with the real script against a venv shaped like the Studio one: a --no-deps upgrade replaced the installed package, import studio.backend.main then failed, the script printed its error and exited 1, and the previous distribution was gone from disk entirely, so recovery needs the network. Under a real supervisord 4.3.0 with this repo's own settings from docker/supervisord.conf, autorestart=true, startretries=3, startsecs=5, the next start gave FATAL Exited too quickly and gave up: studio entered FATAL state. Nothing recovers it: studio_launch.sh and entrypoint.sh do no venv repair, and the script is never exercised against a built image in CI.
Your "including when the Studio home is persisted" is correct and is the worst part. The venv lives under $UNSLOTH_STUDIO_HOME, which is exactly what the script's own header tells people to put on a named volume, so docker rm plus docker run restores nothing.
One thing you understate. "Avoiding an immediate supervisor restart preserves only the currently running process" is true, and even that is narrower than it sounds: the backend defers thousands of imports rather than importing everything at start, so the still-running process starts failing on the first lazily imported module that the replaced tree no longer satisfies. I confirmed that with a live process serving before and failing after the tree was rewritten underneath it.
What I fixed: the message. Line 99 said "NOT restarting Studio: the running process keeps serving", which reads as though nothing is wrong until the operator chooses to restart. It now says the venv on disk is already replaced, that lazily imported code fails from here on, that any restart parks Studio in FATAL, and that a persisted $UNSLOTH_STUDIO_HOME keeps it broken across docker rm and docker run. That is the part of this I am confident is a defect rather than a design tradeoff: the tool was understating its own blast radius.
What I did not do, and why. Every concrete form of "stage or back up" has a real cost or a new destructive failure path, and a broken restore is worse than a broken update:
Copying the venv aside is 2.5 to 3.5 GB. The hardlink trick that would make it cheap does not survive the container case: on overlayfs, creating a hard link forces a copy-up, so cp -al degrades to a full copy into the writable layer precisely when $STUDIO_HOME is on the image rather than a volume.
Reinstalling the previous versions needs the network at the moment the network or index may have just failed, and it does not describe the shipped state anyway: install.sh installs the repo editable, so before the first update the packages resolve through __editable__ finder files rather than a wheel, and after one successful update the previous wheel is gone with the pip cache removed at image build.
--target staging does not do the .dist-info bookkeeping a venv needs and would validate a synthetic layout rather than the real one.
I am aware docker/unsloth_llama_update.sh already does backup-and-restore, so the pattern exists in this directory. That one swaps a self-contained directory tree; a Python venv with editable finders, console scripts and a 3 GB dependency set is a different problem, and I would rather it be designed deliberately with a test that asserts the venv is restored than folded into a review round with no image-level CI for this script.
Separately, and more importantly than this item: I do not think this failure mode is reachable in the shipped image at all, because I do not think the Studio venv has pip. uv venv creates one without it, which I confirmed directly, pip is not in the unsloth dependency closure, install.sh's only ensurepip is inside _install_bnb_rocm on the AMD paths, and install_python_stack.py, which does bootstrap pip, is referenced only in comments by install.sh and never executed by the bash install.sh --local that Dockerfile.studio runs. If that holds, "$PY" -m pip install on line 89 fails with "No module named pip" before it touches anything, which is a bigger problem than the one under review and would make this item moot as shipped. I could not build the image to confirm it, so I am flagging it rather than acting on it.
pip reads PIP_<OPTION> for every option, so a requirements file or an editable target can arrive with nothing on the command line to show for it. The scan only walked argv, so `PIP_REQUIREMENT=/tmp/r.txt pip install packaging` filtered packaging and handed the real pip an uninspected file. Measured against the bundled pip, using its own no-target error as the control: with nothing set it reports "You must give at least one requirement to install", with PIP_REQUIREMENT set it reports "Would install idna-3.6", and with PIP_EDITABLE set it reports "Would install dummyproj26-1.2.3". Both variables are whitespace separated when they carry more than one value. The injected constraints do not cover this, and not because they are overridden: a CLI --constraint still binds when PIP_CONSTRAINT is also set, and the two conflict rather than one winning. What defeats them is a same-version editable or direct reference, which resolves cleanly against a matching pin. So the variables are folded in as ordinary -r and -e flags and go through the same filtering as the command line, and are cleared from the child so the real tool cannot consume them a second time beside our filtered copy. uv has no environment form for --requirements, so folding one into a uv command would hand it a file it was never asked for; this is pip-only. Not covered, and stated rather than implied: the same input can arrive through pip's config file. With PIP_CONFIG_FILE pointing at a pip.conf carrying [install] requirement, pip consumed it with nothing on the command line, and setting the variable empty does not neutralise it. Covering that means parsing pip's config search path or shelling out to `pip config list` on every install.
…venv The failure path printed "NOT restarting Studio: the running process keeps serving", which reads as though nothing is wrong until the operator chooses to restart. Three things were left unsaid, and all three were reproduced. The venv on disk has already been replaced by the time the import check runs, and the previous distribution is gone, so recovery needs the network. "The running process keeps serving" holds only for code it has already imported. The backend defers thousands of imports, so the first lazily imported module the replaced tree no longer satisfies fails in the still-running process. Any restart parks Studio in FATAL. Under a real supervisord with this repo's own autorestart, startretries and startsecs from docker/supervisord.conf, the next start gives "Exited too quickly" and then "gave up: studio entered FATAL state", and nothing in studio_launch.sh or entrypoint.sh repairs it. Because the venv lives under $UNSLOTH_STUDIO_HOME, which the header recommends putting on a named volume, docker rm plus docker run does not restore it either. Message only. Backing the venv up first is a separate design decision: it is a 2.5 to 3.5 GB tree, the hardlink shortcut that would make it cheap forces an overlayfs copy-up inside a container, reinstalling previous versions needs the network at the moment the network may have just failed, and the pre-update state is an editable install rather than a wheel. A broken restore would be worse than a broken update, and this script has no image-level CI.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e458f957e8
ℹ️ 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".
| if any(not _inside_base_venv(d) for d in dirs): | ||
| return True |
There was a problem hiding this comment.
Handle pip's identity root before bypassing filtering
When a command uses pip install --root / torch==... (or PIP_ROOT=/), this check treats / as an external destination and executes pip without filtering or protected constraints. However, pip applies --root as a relocation prefix rather than an installation directory: I checked the bundled pip help (“Install everything relative to this alternate root directory”) and its computed scheme, where root='/' leaves the venv's purelib path unchanged. The command therefore still modifies the baked venv and can replace its Torch/CUDA stack; determine pip's effective installation scheme instead of classifying the root value itself with _inside_base_venv().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed. This is mine, from the destination bypass I added two rounds ago, and it fails in the direction that matters: the install reaches the baked venv with no filtering and no constraints.
Confirmed against the real pip rather than from the scheme calculation. In a throwaway venv, pip install --root / idna==3.6 put idna-3.6.dist-info in that venv's own purelib. The control, pip install --root <dir> packaging==24.0, put it under <dir><venv purelib> and left the venv purelib untouched. So the root is a relocation prefix exactly as you say, and / is the identity.
The fix stops classifying the root value and resolves where the install actually lands: --root now re-anchors the venv's own path beneath the given root, and only counts as elsewhere if the result falls outside the venv. / and // therefore keep the protective filtering, and a genuine relocation still bypasses, which matters because that is the case the bypass exists for.
Two details worth recording:
PIP_ROOT is the environment spelling of the same option and had the same defect, so it moved with it. --target and --prefix are unaffected and still name a destination directly, so they keep their existing handling; the three had been lumped together and only --root is a prefix.
While anchoring this I found the two halves of the check were derived differently: the relocation had to agree with _inside_base_venv, which resolves the venv from the real pip's own path, whereas the site-packages helper falls back to the current interpreter's purelib when that venv is absent. Anchoring the relocation on the venv root makes them agree by construction rather than by coincidence.
Tests in tests/python/test_unsloth_pip_shim.py: separated, --root= and doubled-slash spellings of the identity root, the environment form, and a guard that a genuine relocation still bypasses. Four fail at e458f95. The guard does not, by design: it protects behaviour that was already correct and has no possible head comparison, so the mutation table is its only evidence.
Mutations, all killed: treating the root as a destination directory again, putting --root back with --target/--prefix, dropping PIP_ROOT from the root handling, and making the relocation an identity so a real root looks like the venv.
| _dref = re.match( | ||
| r"^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*@(?:\s|git\+|hg\+|bzr\+|svn\+|[a-z]+://)", | ||
| token, |
There was a problem hiding this comment.
Normalize direct-reference schemes before classifying them
When a valid direct reference omits whitespace around @ and uses an uppercase or mixed-case scheme, such as pip install 'unsloth@GIT+HTTPS://github.com/unslothai/unsloth.git', this case-sensitive regex misses the explicit protected name and _canon() returns None, so the VCS target is forwarded. I checked the bundled pip parser, which accepts this spelling and normalizes the link to git+https; a checkout reporting the baked version also satisfies the injected constraint and replaces the tested Unsloth code. Match URL/VCS schemes case-insensitively or classify the explicit distribution name independently of scheme casing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed. Verified against the shim itself rather than by reading the regex:
unsloth@git+https://github.com/unslothai/unsloth.git -> ('drop', None)
unsloth@GIT+HTTPS://github.com/unslothai/unsloth.git -> ('keep', None)
unsloth@Git+Https://github.com/unslothai/unsloth.git -> ('keep', None)
unsloth @ GIT+HTTPS://github.com/unslothai/unsloth.git -> ('drop', None)
so it is specifically the no-whitespace spelling with a non-lowercase scheme, exactly as you describe. The spaced form survives because the alternation also accepts whitespace after the @.
One more instance of the same root cause that is worth recording, because it is quieter: unsloth@HTTPS://example.com/unsloth-2026.6.9-py3-none-any.whl did not return None, it returned u. With the direct-reference match failing, the token fell into the URL branch and the wheel-name fallback took the stem of whatever the URL happened to end with. So the failure is not only "unknown and forwarded", it can be "confidently wrong about which distribution this is".
Fixed by matching the scheme case insensitively in both places it is tested: the name@scheme form, and the bare scheme prefix a little further down.
That second one needed evidence before I kept it. My first mutation run had the bare-prefix change SURVIVING, so I checked whether it was an equivalent mutant. It is not: GIT+FILE:/tmp/checkout#egg=unsloth carries no ://, so the prefix test is the only thing that recognises it as a direct reference at all, and with the mutant it returns None and is forwarded. pip accepts that spelling; my probe of it failed on the missing path rather than the syntax. I added a test for it, which kills the mutant.
Tests: uppercase and mixed-case VCS spellings, the uppercase wheel URL, an extras form, the no-:// case above, and a guard that an unprotected direct reference such as snac@GIT+HTTPS://... still reaches the real tool, since making the match case insensitive must not start dropping things that were never protected.
Three of those fail at e458f95. Two do not, and I would rather name them than let the count imply otherwise. The unprotected-reference guard protects already-correct behaviour and has no head comparison. And the uppercase WHEEL URL already passed at the parent, by accident: the wheel-name fallback recovered unsloth from the filename, so that spelling happened to be classified correctly for the wrong reason. It is a real case worth pinning, but it is not evidence of the bug.
Mutations, all killed: reverting each of the two case-insensitive matches.
| keep_args.append(tok) | ||
| if prev_flag in _TARGET_VALUE_FLAGS: | ||
| has_target = True |
There was a problem hiding this comment.
Inspect dependency-group targets before forwarding them
When --group, --upgrade-group, or --requirements-from-script supplies the install targets, this branch only marks that a target exists and forwards the referenced group or script without inspecting its package specifications. I checked the bundled pip, which accepts a dependency group containing a direct reference such as unsloth @ file:///tmp/checkout; if that checkout reports the baked version, the generated version constraint remains satisfied and pip replaces the protected code. Parse and filter these package-bearing inputs like -r, or refuse them when their contents cannot be inspected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Partially correct, and fixed for the two flags that are real. One third of the claim does not hold.
--group is genuinely affected. On the bundled pip 25.3 and on uv 0.11.32, pip install --group dirgroup with a [dependency-groups] table holding unsloth @ file:///checkout at the baked version installed over it, with the injected constraints satisfied throughout. The identical requirement given on the command line, or in a -r file, is dropped, so the group really is the hole.
--requirements-from-script is genuinely affected, but only on pip 26 and later. The bundled pip 25.3 has no such option; I checked pip's own option table rather than its help text. It matters anyway, because docker/Dockerfile line 82 installs pip unpinned, so an image built today bakes pip 26 and the flag is live.
--upgrade-group is NOT affected, and this is the part I am pushing back on. pip has no such option at all, and uv pip install rejects it outright: it is a uv lock / uv sync / uv add flag. Since _install_index only matches pip install and uv pip install, it can never supply a target on any command line this shim sees. Listing it among the affected flags is over-generalisation, not a hole.
Two refinements to the mechanism, both measured:
On pip the bypass needs a local PATH or sdist. pip's resolver reinstalls a same-version candidate only when the source link is a local file that is not a wheel; a same-version local WHEEL is skipped with "already installed with the same version as the provided wheel", and a remote URL or VCS reference is skipped too. Your example, unsloth @ file:///tmp/checkout, is exactly the case that does replace it. On uv the local wheel replaces as well, so uv has the wider hole.
The constraints are not useless here: a group pinning a DIFFERENT version is still rejected. What they cannot stop is the same-version local path, which is the case you named.
I took your second option rather than the first. Parsing these would mean reading a PEP 735 table, following its include-group chains, and rewriting the result into a filtered requirements file, or parsing a PEP 723 header, and getting any of that subtly wrong reintroduces the very bypass it is meant to close. So an install that carries one of these flags is now refused, with a message pointing at -r, which is filtered. That matches the existing refusal for uv pip sync, which likewise trades a working command for one the shim can reason about.
Two things I want to be explicit about rather than let them pass.
I changed a contract an earlier round had pinned. test_dependency_group_flags_are_install_targets asserted these flags reach the real tool, because before that round the shim treated them as ordinary option/value pairs, found no target, and printed "ok" having installed nothing. Refusing contradicts the letter of that test but not its purpose, which was that these must never quietly succeed. I rewrote it to assert the refusal and kept all five of its spellings, including the sub/pyproject.toml:dev and = forms.
While placing the refusal I had it wrong first: it sat before the install check, so any subcommand merely mentioning --group would have been refused. It now runs after the install check and after the destination bypass, so a non-install command is untouched and a group installed into another environment is still allowed, which I pinned with a test.
Tests: five refusal shapes across pip and uv, plus guards that a group aimed elsewhere is not refused and that an ordinary install is not. Mutations, all killed: refusing nothing, and refusing --group but not --requirements-from-script.
| for m in _PIN_RE.finditer(_install_lines(text)): | ||
| if _norm_req(m.group(1)) == "transformers": | ||
| return m.group(2) |
There was a problem hiding this comment.
Honor environment markers when selecting a sidecar
When a valid requirement has a false environment marker, for example transformers==4.57.6; python_version < "3.0", this regex still returns its version and the pre-run hook activates that sidecar before pip evaluates the marker. I confirmed the bundled pip reports that this requirement is ignored on the image's Python while pin_in_cell() returns 4.57.6; a notebook that should retain the base Transformers can thus be forced onto an older sidecar and fail on newer model APIs. Parse and evaluate the PEP 508 marker before treating the pin as active.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in both places it occurs. Reproduced directly:
!pip install transformers==5.5.0 -> 5.5.0
!pip install "transformers==5.5.0; python_version < '3.0'" -> 5.5.0
!pip install "transformers==5.5.0; sys_platform == 'win32'" -> 5.5.0
while the real tools skip those outright, pip with "Ignoring transformers: markers ... don't match your environment" and uv with "Would make no changes". No marker is parsed anywhere in the module.
You reported one site. There are two, and fixing only the one you named would have left the behaviour intact. unsloth_pip_shim._version_pin is a bare re.search(r"==\s*(...)") and independently writes the same bogus pin to the sidecar marker file, which requested_version() then feeds to every later cell:
pip install "transformers==4.57.6; python_version < '3.0'"
[unsloth-nb] notebook requested transformers==4.57.6; will activate its sidecar
MARKER=4.57.6
So the pre-run hook is one route and the shim is another. Both now evaluate the marker.
One correction to the example, since it changes what an operator would see. On the shipped image there is no 4.57.6 sidecar: the vLLM floor drops it, so a false-marker pin of 4.57.6 is clamped UP to the 5.5.0 sidecar rather than activating a 4.57.6 one. The consequence you describe still holds, because 5.5.0 is older than the transformers the image bakes and the notebook is pushed off the base it should have kept, but it is a clamp rather than the literal version.
One case I deliberately left alone. Unquoted, !pip install transformers==5.5.0; python_version < "3.0" is cut at the ; by the shell, so pip only ever receives the bare pin and it really is unconditional. Treating that as vetoed would break a working notebook. The fix splits the line the way a shell does and only evaluates a marker that survives quoting, so the quoted form is vetoed and the unquoted form still pins. Both are pinned by tests.
Implementation follows the module's existing convention that packaging is optional, as it already is for the sidecar version ordering: if the import fails or the requirement does not parse, nothing is vetoed and the previous behaviour stands. There is a test for that path too, since a silent hard dependency would be a worse failure than the one being fixed.
Tests in tests/python/test_docker_nb_compat_pre_run_cell.py and tests/python/test_unsloth_pip_shim.py: false markers on python_version, sys_platform and implementation_name, true markers on python_version and platform_system which must keep working, the unquoted form, and the no-packaging fallback. Three fail at e458f95; the true-marker and no-marker cases pass there by design, since they pin behaviour that was already correct.
Mutations, all killed: never vetoing on either side, inverting the marker test on either side so true markers are dropped instead, and splitting the line on whitespace rather than the way a shell quotes.
Four ways an install could reach the baked venv without being filtered, or could pin the wrong transformers version. --root is a relocation prefix, not a destination directory, so --root / is the identity and the install lands in the venv it was supposed to be diverted away from. It is now resolved against the venv root instead of being treated as an external target on sight, and it is classified apart from --target and --prefix, which really are directories. Direct-reference detection was case sensitive, so GIT+FILE:/checkout or HTTPS://... slipped past the scheme test and the local-project lookup. Both the scheme prefix test and the direct-reference match are now case insensitive, which is what PEP 508 and pip both do. --group and --requirements-from-script name install targets that live in a pyproject table or a PEP 723 header rather than on the command line, so the shim cannot see or filter them. Parsing either would mean following include-group chains and rewriting the result, and getting that subtly wrong reintroduces the bypass. An install carrying one of them is refused instead, pointing at -r, which is filtered. The refusal runs after the install-index check and after the destination bypass, so a non-install subcommand and a group aimed at another environment are both untouched. A PEP 508 marker on a pin was ignored, so transformers==5.5.0 with a marker that evaluates false still produced a 5.5.0 pin even though pip and uv skip the requirement outright. Both sites that read a pin now evaluate the marker: the pre-run hook in unsloth_nb_compat and the sidecar marker written by the shim. Lines are split the way a shell splits them, so an unquoted marker, which the shell cuts before pip sees it, still pins unconditionally. packaging stays optional, as it already is for sidecar version ordering: if it is missing or the requirement does not parse, nothing is vetoed. test_dependency_group_flags_are_install_targets asserted these flags reach the real tool, which the refusal contradicts. Its purpose was that they must never quietly succeed, so it is rewritten to assert the refusal, keeping all five of its spellings.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b26fdce7b0
ℹ️ 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".
| if tool == "pip": | ||
| for _var, _flag in _PIP_TARGET_ENV.items(): | ||
| for _val in os.environ.get(_var, "").split(): | ||
| env_tail += [_flag, _val] | ||
| if env_tail: | ||
| child_env = {k: v for k, v in os.environ.items() if k not in _PIP_TARGET_ENV} |
There was a problem hiding this comment.
Inspect package-bearing pip configuration files
When PIP_CONFIG_FILE or a user/site pip config defines install.requirement = /tmp/req.txt, this branch inspects only PIP_REQUIREMENT and PIP_EDITABLE, then leaves the config active for the real pip process. I confirmed the available pip consumes such an install-scoped requirement, consistent with pip config --help saying configuration keys use a command-and-option name; consequently, pip install packaging can also install an uninspected same-version editable/direct-reference Unsloth or Torch entry from that hidden file, bypassing the baked-stack filter despite the generated version constraints. Fresh evidence beyond the environment-variable fix is that pip's configuration-file input remains forwarded unchanged; inspect or disable package-bearing config values before invoking pip.
Useful? React with 👍 / 👎.
| && { /opt/unsloth-venv/bin/python -c \ | ||
| "import torchcodec; print('torchcodec', torchcodec.__version__)" \ | ||
| || echo ">> torchcodec unavailable on this arch (audio decode falls back)"; } |
There was a problem hiding this comment.
Remove a TorchCodec install that fails its import probe
When the TorchCodec wheel installs but its NPP dependency or native loading is broken, this probe prints the fallback message and lets the image publish while leaving torchcodec metadata installed. The notebook shim classifies protected packages solely by installed distribution metadata, so a later pip install torchcodec is then dropped as an attempt to replace a working baked package even though this probe already proved the package unusable; users cannot repair audio decoding with a compatible wheel from an install cell. Remove the failed distribution in this branch, as the arm64 vLLM failure path does, or record functional availability separately from metadata presence.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2aeffde941
ℹ️ 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".
| _arch = _sdist_name(token.split("#", 1)[0].split("?", 1)[0].rstrip("/").rsplit("/", 1)[-1]) | ||
| if _arch: | ||
| return _arch | ||
| if re.match(r"^[a-z]+\+", token): |
There was a problem hiding this comment.
Handle uppercase bare VCS URLs when classifying targets
When a protected checkout is supplied as a bare mixed-case VCS URL such as pip install GIT+HTTPS://github.com/unslothai/unsloth.git, the outer test accepts the scheme case-insensitively but this second test does not, so _canon() returns None and the shim forwards the checkout. I verified with the available pip 26.0.1 that GIT+file://... is normalized and cloned; if the checkout reports the baked version, the generated version constraint still permits it to replace the tested Unsloth code. Fresh evidence after the named direct-reference fix is that the bare-VCS branch retained this separate case-sensitive match; apply the same case-insensitive normalization here.
Useful? React with 👍 / 👎.
| for m in _PIN_RE.finditer(lines): | ||
| if _norm_req(m.group(1)) == "transformers" and m.group(2) not in skipped: | ||
| return m.group(2) |
There was a problem hiding this comment.
Evaluate false markers per requirement occurrence
When one install command contains both a false-marked and an active requirement for the same version, such as pip install "transformers==5.5.0; python_version < '3.0'" transformers==5.5.0, _marker_skipped_versions() stores only the version and this condition consequently rejects both regex matches. I confirmed pin_in_cell() returns None, while pip reports that it is ignoring only the marked requirement and proceeds to resolve the active one; an import later in that cell therefore freezes the base Transformers before the shim's marker can help. Fresh evidence after the environment-marker fix is this loss of occurrence identity; evaluate the marker attached to each matched requirement rather than vetoing every occurrence of its version.
Useful? React with 👍 / 👎.
| tmp = state_path + ".tmp" | ||
| try: | ||
| with open(tmp, "w", encoding = "utf-8") as f: |
There was a problem hiding this comment.
Create the state temporary without following symlinks
When a root container is started after an untrusted UID has written the default world-writable notebook volume, that UID can pre-create .unsloth_sync_state.tmp as a symlink to any container path. This open(..., "w") follows the link and writes the migration's state as root; malformed state lines are deliberately preserved verbatim, so a crafted state plus one cleanable notebook can create attacker-controlled files such as /etc/profile.d/evil.sh. I reproduced the underlying behavior with the sibling notebook temporary: _stage_clean() followed an existing .tmp symlink and overwrote its target. Create a unique same-directory temporary with exclusive, no-follow semantics rather than opening a predictable pathname.
Useful? React with 👍 / 👎.
commented
Sep 4, 2026
|
@codex review |
commented
Sep 4, 2026
|
You have reached your Codex usage limits for security reviews. Please try again later. |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2aeffde941
ℹ️ 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".
| _UNINSPECTABLE_TARGET_FLAGS = {"--group", "--requirements-from-script"} | ||
| _PIP_TARGET_ENV = {"PIP_REQUIREMENT": "-r", "PIP_EDITABLE": "-e"} |
There was a problem hiding this comment.
Inspect package targets supplied by pip environment options
When PIP_GROUP or PIP_REQUIREMENTS_FROM_SCRIPT is set, this mapping neither folds the value into argv nor clears it before executing real pip, while the new uninspectable-target guard only scans command-line flags. I checked the available pip 26.1: its help describes --group as installing a named dependency group, and both environment variables caused their group/script dependencies to be resolved. Thus PIP_GROUP=x pip install packaging can still install a same-version direct reference to Unsloth/Torch from the hidden group, satisfying the generated version constraint while replacing the baked stack; reject or inspect these environment-supplied targets too.
Useful? React with 👍 / 👎.
| if os.path.isfile(os.path.join(path, "setup.py")) or os.path.isfile(_pyproject): | ||
| _base = os.path.basename(os.path.normpath(path)) | ||
| return _norm_name(_base) |
There was a problem hiding this comment.
Refuse legacy local projects when their name is unknown
When a legacy checkout is stored under a generic directory such as /tmp/src and its setup.py declares setup(name="unsloth", version=<baked version>), this fallback classifies the target as src rather than using the distribution name. A direct or editable install is therefore forwarded as unprotected, and the exact-version constraint still permits that same-version source tree to overwrite the tested Unsloth installation. Indeterminate setup.py projects should be inspected for metadata or refused instead of trusting the directory basename.
Useful? React with 👍 / 👎.
| cache-from: type=gha,scope=build-${{ matrix.platform }} | ||
| cache-to: type=gha,scope=build-${{ matrix.platform }},mode=max |
There was a problem hiding this comment.
Bust the build cache for floating vLLM releases
When a scheduled or manually dispatched build resolves the same Unsloth and zoo SHAs as a previous run, this persistent GHA cache can reuse the Dockerfile layer containing the unpinned --pre ... vllm installation because no resolved vLLM version or run-specific cache-busting input changed. The resolver therefore never checks the nightly index, and the newly published core-nightly/nightly manifests can retain an arbitrarily old vLLM and its previously derived Transformers sidecar floor even after a new nightly is available. Resolve the vLLM build once in prepare and pass it as a build argument, or otherwise invalidate that layer for scheduled nightly builds.
Useful? React with 👍 / 👎.
A root boot leaves .unsloth_sync_commit root-owned 0644 inside a notebook directory the host user owns. A later boot as that user renames the state file into place without trouble, because that only needs the directory, but the marker was written with a plain redirect and the truncate fails. The refresh then printed its success line while the marker stayed at the old commit, and every start after that re-synced all 1241 notebooks. Reproduced in the shipped base image: root boot, rewind the marker as root, boot as 1000:1000. The state came back owned 1000:1000 and the marker did not. Write the marker to a sibling temp file and rename it, the same path the state already takes, and say so when even that fails instead of swallowing it. The group redirection also keeps the shell's own open() error from leaking, which the old trailing 2>/dev/null could not do because redirections apply left to right. The test models the root-owned marker with a read-only one, which fails the same open(O_TRUNC), and is skipped under root. It fails on the previous script.
commented
Sep 4, 2026
|
You have reached your Codex usage limits for security reviews. Please try again later. |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dff3e8171c
ℹ️ 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".
| if [ "$stage_ok" = 1 ] && [ "$merge_lost" -eq 0 ]; then | ||
| mv "$STATE.tmp" "$STATE" 2>/dev/null || rm -f "$STATE.tmp" |
There was a problem hiding this comment.
Keep population retryable when state publication fails
When the populated state cannot be renamed onto $STATE—for example, when that file is a single-file bind mount and mv returns EBUSY—this failure is swallowed and the staged state is deleted, but stage_ok and populate_failed remain successful. The branch below consequently removes $PARTIAL and advances $SYNCED, even though the notebooks copied during this pass were never recorded; later refreshes either exit at the new marker or classify those unrecorded files as user edits and stop updating them. Treat this final publication failure like the other population failures and leave the partial/commit markers in their retry state.
Useful? React with 👍 / 👎.
commented
Sep 11, 2026
|
tested the images on windows 11 + docker desktop 4.90 (wsl2) with an rtx 5060 ti (sm_120). overall it works end to end: gpu detected, studio, gguf chat, lora training, jupyter,
|
Summary
Two Docker images for Unsloth, built without a GPU on free GitHub-hosted runners and published as multi-arch manifests to
docker.io/unsloth/unsloth:docker/Dockerfile, tagscore/core-<git tag>/core-nightly/core-sha-<short>): the training stack attorch 2.11.0+cu128with Unsloth and unsloth_zoo, TRL / PEFT / accelerate, bitsandbytes, triton, xformers (amd64), vLLM, plus llama.cpp for GGUF tooling, JupyterLab, and the Unsloth notebooks baked in. Run it headless for training,unsloth-run <notebook|url>, orjupyter lab.docker/Dockerfile.studio, tagslatest/studio/<git tag>/nightly/sha-<short>): the base image plus Unsloth Studio, running Studio on 8000, JupyterLab on 8888 and key-only sshd on 22 under supervisord, with an optional Cloudflare tunnel for JupyterLab.The runtime floor is Turing, sm_75. The entrypoint refuses anything older with the supported table printed, and forward-compat PTX covers sm_103 (B300/GB300) and sm_121 (GB10) through a runtime NVRTC/ptxas swap to CUDA 13, since CUDA 12.8's nvcc cannot compile those two.
amd64 and arm64 are built in parallel on native runners (
ubuntu-latestandubuntu-24.04-arm, both free on public repos), pushed by digest, then merged into one manifest per image, sodocker pullselects the right child. Native arm64 is the DGX Spark and Grace path and involves no QEMU.Why the build needs no GPU
Four places where a naive Docker build couples to the build host's GPU, and what the Dockerfile does instead.
--torch-backend=auto, noinstall.sh. The pin is explicit:torch==2.11.0 torchvision==0.26.0 torchaudio==2.11.0against--extra-index-url https://download.pytorch.org/whl/cu128.pip installcalls letbitsandbytes' transitivecuda-toolkitdep upgrade torch to a cu130 build in a later pass, stranding the cu128 xformers. Everything collapses into oneuv pip installwith--index-strategy unsafe-best-matchso the resolver sees all constraints at once.torch.cuda.get_arch_list()returns[]with no GPU visible, so the build asserts ontorch._C._cuda_getArchFlags(), which reads compiled wheel metadata directly, and additionally pins that the resolved version still starts with2.11.0and still carries+cu128. Required packages are checked withimportlib.metadata.version()rather than by importing them, becauseimport unslothreachestorch.cuda.get_device_properties(0).UNSLOTH_COMPILE_DISABLE=1,UNSLOTH_COMPILE_OVERWRITE=0,UNSLOTH_DISABLE_GPU_PROBE=1andCUDA_VISIBLE_DEVICES="", so nothing JITs kernels keyed to a build host and bakes them intounsloth_compiled_cache/.This works because cu128 PyTorch wheels are already fat binaries cross-compiled upstream for every architecture in range. The build host's GPU was never needed for the binary content, only by code that assumed it.
The build is host-independent, not bit-reproducible:
pip freezeomits wheel hashes, and unsloth and the vLLM nightly float. A pin record is written to/opt/unsloth-venv/requirements.lock.txtinside the image for a later pinned rebuild.What is in the images
Base
TORCH_CUDA_ARCH_LIST="7.5;8.0;8.6;8.9;9.0;10.0;12.0+PTX"in both stages, so any source build inside the container honours the full range and the+PTXon the top arch gives forward-compat JIT for newer consumer Blackwell parts.nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04; runtime isnvidia/cuda:12.8.1-base-ubuntu24.04, which drops roughly 2.7 GB of system CUDA libraries the venv ships anyway.cuda-nvcc-12-8andcuda-nvcc-13-0are kept in the runtime image on purpose, for flash-linear-attention's TileLang JIT and the sm_103/sm_121 ptxas path.unslothai/notebooksbaked in as a read-only template and synced to/workspace/unsloth-notebookson boot, with an edit-preserving refresh from GitHub when reachable.pip/uvshim that keeps the validated GPU stack pinned while letting a notebook install its own extras, per-notebook transformers sidecars, a Colab-compat input transformer, andunsloth-runfor headless execution of any notebook or URL.[huggingface]extra.Studio
docker/jupyter/unsloth_branding.pyis an integrity guard for that attribution, since it is a license condition, anddocker/NOTICEcarries the AGPLv3 section 7(b) terms.Publishing
.github/workflows/docker-publish.ymlruns on pushes tomain, onv*tags, on a weekly schedule, and onworkflow_dispatch. Apreparejob first freezes four upstream refs (llama.cpp release tag, unsloth, unsloth-zoo, notebooks) to immutable SHAs and tags, hard-erroring rather than falling back to a mutable name. Then the base image is built per arch and merged, the Studio image is built against the base manifest by digest, and merged in turn.tests/python/test_docker_publish_ref_freeze.pyparses the workflow and fails if any unfrozen ref is ever forwarded.Nothing builds from this PR: there is no
pull_requesttrigger.Changes outside
docker/Four of these are user-visible outside the images and are worth reviewing on their own terms.
unsloth/_gpu_init.pyNVIDIA_VISIBLE_DEVICESnames specific ids andCUDA_VISIBLE_DEVICESis absent, which is the fingerprint ofdocker --gpus '"device=N"', forcesTORCHINDUCTOR_COMPILE_THREADS=1and setsUNSLOTH_FORCE_SINGLE_COMPILE_WORKER=1. The Inductor compile-worker pool cannot enumerate a cgroup-pinned GPU and dies with "Could not find an active GPU backend". It then re-asserts the setting past unsloth_zoo's own snapshots of the option. This fires for any user with a pinnedNVIDIA_VISIBLE_DEVICES, not only these images; opt out withUNSLOTH_FORCE_SINGLE_COMPILE_WORKER=0. The consumer half lives in unslothai/unsloth-zoo#694.unsloth/models/vision.pylogits_to_keep/num_logits_to_keeparch-walk injection inunsloth_base_fast_generateis gated to transformers below 5.0. On 5.x,generate()sets it itself, so the code instead strips only the kwargs the strict validator would reject, while leaving an explicitlogits_to_keep=0alone.unsloth/dataprep/synthetic.pySyntheticDataKithangs or falsely fails against vLLM 0.19 and newer.unsloth/models/_utils.pytorch.cuda.is_available(), since a CUDA-built torch on a driverless host keepsDEVICE_TYPE == "cuda"and then raises inside_lazy_init().install.sh,studio/install_python_stack.pyUNSLOTH_ZOO_REFthrough the--localzoo overlay, so the Studio image can pin one frozen zoo ref for both builds. Unset means the previous behaviour, byte for byte.studio/install_llama_prebuilt.pyEXDEVwhen staging and install land on different overlayfs layers: copy-fallback on activation, and amove_install_dir_asidehelper that refuses to copy a linked install, stages to a uniquified temp then publishes atomically, and preserves symlinks so a bundle's soname links are not duplicated.Two things to know when running it
The base image wants a GPU.
docker/entrypoint.shrefuses to start without one, then checkstorch.cuda.is_available()and a compute capability of at least 7.5, printing the driver floor on failure (570.26 for cu128, 580 for sm_103/sm_121).UNSLOTH_ALLOW_CPU=1continues on CPU with a warning, which covers Jupyter, GGUF tooling and llama.cpp Studio chat but not training or loading an Unsloth model.UNSLOTH_SKIP_GPU_CHECK=1bypasses the checks entirely.The in-app llama.cpp update banner never appears in the Studio image, by design.
Dockerfile.studiosymlinks${UNSLOTH_STUDIO_HOME}/llama.cppat/opt/unsloth/llama.cpp. Studio's update flow treats an install reached through a symlink as externally managed and returns alocal_linkstatus before doing any network work, so no update is ever offered./usr/local/bin/unsloth-llama-updateis the intended path: it reuses the same build-time fetcher and swaps the bundle atomically.unsloth-studio-updateis the equivalent for Studio itself and refuses to activate a broken new backend.Validation
Everything below was run by hand on a B200 (sm_100) host. There is no GPU-backed CI (see the next section), so this is the only evidence that the images work.
torch 2.11.0+cu128, triton 3.6.0, vLLM 0.26.0, with arch flags covering sm_75 through sm_120.docker/smoke_test.pyon GPU 0: imports unsloth, loadsLlama-3.2-1B-Instruct-bnb-4bitin 4-bit, and completes LoRA steps with the loss decreasing..soand run real kernels inside the image: flash-attn 2.8.1, causal-conv1d 1.6.1, mamba-ssm 2.3.1 and flash-linear-attention. They resolve+cu12torch2.10assets through the{"2.11": "2.10"}reuse mapping already documented instudio/backend/utils/wheel_utils.py, since no native 2.11 wheels exist.unsloth runandunsloth startwere exercised, and image and video generation both work (Z-Image-Turbo, Wan2.2-TI2V-5B-GGUF).unsloth-blackwell-base.tar.gzandunsloth-blackwell-studio.tar.gz, re-downloaded, sha256 matched,docker loaded to an exact image-ID match, and then run from those bytes rather than from the local build. Until the publish workflow has run onmain, that repo is the only way to obtain the images this PR builds.What this does not cover
smoke-testjob is gated onvars.HAS_GPU_RUNNER == 'true'andruns-on: [self-hosted, gpu], so with the default repo variables it is skipped. No GitHub-hosted standard runner has a GPU of any vendor, so every Docker-side check that does run on a PR is a static-source assertion over the Dockerfile, the workflow YAML or the TypeScript.Dockerfile.studio, sojlpm build:prodis not exercised here either.smoke-testruns after publishing, not before: itneedsboth merge jobs. There is no pre-publish gate.mainin quick succession can race to retagcoreandlatest. It is self-correcting on the next push, and the workflow says so.Tests
23 new test files and three extended ones, all CPU-only and container-free, plus
tests/validate_studio_features.py, whichstudio-backend-ci.ymlnow runs explicitly. They cover the parts of the Docker surface that are checkable without building: the pip shim's keep-list against the validated training stack and itsexecvargv, the notebook sync and populate state machines against real scripts (first-boot retry, refresh-versus-save races, bind-mount ownership, view-symlink ownership), the Colab strip's scope and idempotence, notebook pin scanning including the pre-run-cell hook and the dead-code rules that keep a commented-out install from supplying a pin, sidecar selection against the vLLM floor, the entrypoint's CUDA JIT tool selection, the llama.cpp CUDA backend and prebuilt probe, the update helpers' failure and rollback paths, the branding guard, the publish workflow's ref freezing, and the EXDEV handling ininstall_llama_prebuilt.py.Setup required before this can publish
DOCKERHUB_USERNAMEandDOCKERHUB_TOKENvars.HAS_GPU_RUNNER=trueonce a self-hosted GPU runner is registered, so the post-publish smoke test exercises real GPU paths