Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Docker: stop notebooks from uninstalling the baked packages (#11156)
Nilaye7257b0cfb68
diff --git a/docker/unsloth_pip_shim.py b/docker/unsloth_pip_shim.pyindex 68f6dea1a9a..aa56e3ac652 100644--- a/docker/unsloth_pip_shim.py+++ b/docker/unsloth_pip_shim.py@@ -527,6 +527,9 @@ def _logical_lines(lines):# own cwd, which is what pip always uses. main() sets it for uv._WORKING_DIR = None+# Set for `pip uninstall`, where `pkg[extra]` names pkg itself rather than extras to add.+_UNINSTALLING = False+def _uv_working_dir(tool, argv):"""The directory uv will change to before resolving a relative requirements@@ -616,7 +619,11 @@ def _filter_requirements_file(path, _depth = 0):# every _KEEP package below, and the sidecar only replaces the version:# dropping the whole token loses deepspeed/sentencepiece/... and still# reports ok. The pin is stripped, so this can only ADD.- extras = _extras_only_target(spec) if _is_installed("transformers") else None+ extras = (+ _extras_only_target(spec)+ if _is_installed("transformers") and not _UNINSTALLING+ else None+ )if extras is not None:out.append(extras + ("\n" if group[-1].endswith("\n") else ""))changed = True@@ -625,7 +632,7 @@ def _filter_requirements_file(path, _depth = 0):changed = Truecontinueif _is_protected(name):- extras = _extras_only_target(spec)+ extras = None if _UNINSTALLING else _extras_only_target(spec)if extras is not None:out.append(extras + ("\n" if group[-1].endswith("\n") else ""))changed = True@@ -849,7 +856,11 @@ def _install_index(tool, argv):outcome available here: the install runs unfiltered and unconstrained, free toreplace the baked torch/CUDA stack. _VALUE_FLAGS is the same set the tail scanneruses and _selfcheck_value_flags() holds it to the real CLIs at build time."""- expect = ["install"] if tool == "pip" else ["pip", "install"]+ return _subcommand_index(tool, argv, "install")+++def _subcommand_index(tool, argv, sub):+ expect = [sub] if tool == "pip" else ["pip", sub]got = _positionals(argv)if len(got) < len(expect):return None@@ -859,6 +870,82 @@ def _install_index(tool, argv):return got[len(expect) - 1][0]+def _uninstall_file(path, dropped):+ """Filtered path, or None when nothing is left: pip errors on an empty file."""+ filtered, _, drp = _filter_requirements_file(path)+ dropped.extend(drp)+ if filtered == path:+ return filtered+ with open(filtered, encoding = "utf-8") as f:+ if any(ln.strip() and not ln.strip().startswith("#") for ln in f):+ return filtered+ return None+++def _uninstall(tool, argv, i):+ global _UNINSTALLING+ _UNINSTALLING = True+ head, tail = argv[: i + 1], _expand_short_clusters(argv[i + 1 :])+ child_env = None+ if tool == "pip":+ env_tail = [x for val in os.environ.get("PIP_REQUIREMENT", "").split() for x in ("-r", val)]+ if env_tail:+ tail = env_tail + tail+ child_env = {k: v for k, v in os.environ.items() if k != "PIP_REQUIREMENT"}+ keep, dropped = [], []+ has_target = False+ pending = None+ for tok in tail:+ if pending is not None:+ if pending in _REQ_FILE_FLAGS:+ tok = _uninstall_file(tok, dropped)+ if tok is not None:+ keep += [pending, tok]+ has_target = True+ else:+ keep += [pending, tok]+ pending = None+ continue+ if tok.startswith("--") and "=" in tok:+ flag, _, val = tok.partition("=")+ if flag in _REQ_FILE_FLAGS:+ filtered = _uninstall_file(val, dropped)+ if filtered is not None:+ keep.append(flag + "=" + filtered)+ has_target = True+ continue+ keep.append(tok)+ continue+ if len(tok) > 2 and tok[:2] in _REQ_FILE_FLAGS:+ filtered = _uninstall_file(tok[2:], dropped)+ if filtered is not None:+ keep += [tok[:2], filtered]+ has_target = True+ continue+ if tok in _VALUE_FLAGS:+ pending = tok+ continue+ if tok.startswith("-"):+ keep.append(tok)+ continue+ name = _canon(tok)+ if _is_protected(name) or (name == "transformers" and _is_installed(name)):+ dropped.append(tok)+ continue+ keep.append(tok)+ has_target = True+ if dropped:+ print("[unsloth-nb] kept baked versions, skipped: " + " ".join(dropped))+ if not has_target and dropped:+ print("[unsloth-nb] nothing to uninstall after keeping the baked stack; ok.")+ return+ cmd = [REAL[tool]] + head + keep+ sys.stdout.flush()+ if child_env is not None:+ os.execve(REAL[tool], cmd, child_env)+ os.execv(REAL[tool], cmd)++def _positionals(argv):"""(index, token) for every positional, skipping options AND their values.@@ -984,10 +1071,13 @@ def _installs_elsewhere(tool, argv):baked interpreter, so it keeps the protective behaviour. Environment variablescount only for the tool that actually reads them; a flag is left unscoped becausea tool that does not accept one fails loudly on it rather than silently."""+ # pip uninstall has no --target/--prefix/--root and ignores their variables, so+ # they still leave it pointed at the baked venv+ dest_env = not (tool == "pip" and _subcommand_index(tool, argv, "uninstall") is not None)dirs = _flag_values(argv, _DEST_DIR_FLAGS)- dirs += [os.environ[v] for v in _DEST_DIR_ENV[tool] if os.environ.get(v)]+ dirs += [os.environ[v] for v in _DEST_DIR_ENV[tool] if dest_env and os.environ.get(v)]roots = _flag_values(argv, _DEST_ROOT_FLAGS)- roots += [os.environ[v] for v in _DEST_ROOT_ENV[tool] if os.environ.get(v)]+ roots += [os.environ[v] for v in _DEST_ROOT_ENV[tool] if dest_env and os.environ.get(v)]# a root re-anchors the venv's OWN paths beneath it, so resolve where each one# actually lands rather than classifying the root value itselfdirs += [_relocated_under_root(r, _base_venv_root()) for r in roots]@@ -1027,6 +1117,11 @@ def main():_wd = _uv_working_dir(tool, argv)_WORKING_DIR = os.path.abspath(_wd) if _wd else None+ i = _subcommand_index(tool, argv, "uninstall")+ if i is not None:+ _uninstall(tool, argv, i)+ return+i = _install_index(tool, argv)if i is None:os.execv(REAL[tool], [REAL[tool]] + argv)diff --git a/tests/python/test_docker_pip_shim_training_stack.py b/tests/python/test_docker_pip_shim_training_stack.pyindex 2838849813e..f3415cd28ea 100644--- a/tests/python/test_docker_pip_shim_training_stack.py+++ b/tests/python/test_docker_pip_shim_training_stack.py@@ -74,16 +74,17 @@ def _run(shim,args,tool = "pip",+ sub = "install",):- """Args after `install`, or None when the shim no-op'd; constraints pair dropped."""- argv = ["uv", "pip", "install", *args] if tool == "uv" else ["pip", "install", *args]+ """Args after the subcommand, or None when the shim no-op'd; constraints pair dropped."""+ argv = ["uv", "pip", sub, *args] if tool == "uv" else ["pip", sub, *args]with pytest.MonkeyPatch.context() as mp:mp.setattr(shim.sys, "argv", argv)try:shim.main()return Noneexcept _Exec as exc:- i = exc.argv.index("install")+ i = exc.argv.index(sub)execd = exc.argv[i + 1 :]if (len(execd) >= 2@@ -313,3 +314,87 @@ def test_forwarded_installs_pin_the_protected_set_for_the_resolver(shim):assert all(n in shim._KEEP or n == "transformers" or n.startswith("nvidia-") for n in names), sorted(names)+++# --- uninstall: the other direction the notebooks take ------------------------------+++def test_the_shipped_falcon_cell_cannot_remove_unsloth(shim, capsys):+ assert _run(shim, ["unsloth", "-y"], sub = "uninstall") is None+ assert "skipped: unsloth" in capsys.readouterr().out+++def test_the_shipped_qwen_moe_cell_keeps_torchcodec(shim):+ assert _run(shim, ["-y", "sentence-transformers", "torchcodec"], sub = "uninstall") == [+ "-y",+ "sentence-transformers",+ ]++[email protected]("pkg", ["torch", "vllm", "trl", "transformers", "nvidia-cublas-cu12"])+def test_uninstall_of_the_baked_stack_is_dropped(shim, pkg):+ assert _run(shim, ["-y", pkg], sub = "uninstall") is None+ assert _run(shim, [pkg], tool = "uv", sub = "uninstall") is None+++def test_uninstall_of_an_unbaked_package_still_runs(shim):+ assert _run(shim, ["-y", UNBAKED], sub = "uninstall") == ["-y", UNBAKED]+ assert _run(shim, ["-qy", UNBAKED], sub = "uninstall") == ["-q", "-y", UNBAKED]+++def test_uninstall_of_a_protected_package_the_image_never_baked_still_runs(shim_without_vllm):+ assert _run(shim_without_vllm, ["-y", MISSING], sub = "uninstall") == ["-y", MISSING]+++def test_uninstall_protection_survives_a_requirements_file(shim, tmp_path):+ req = tmp_path / "remove.txt"+ req.write_text(f"torchcodec\n{UNBAKED}\n")+ for args in (["-y", "-r", str(req)], ["-y", f"-r{req}"], ["-y", f"--requirement={req}"]):+ execd = _run(shim, args, sub = "uninstall")+ assert execd is not None, args+ path = execd[-1].partition("=")[2] if execd[-1].startswith("--requirement=") else execd[-1]+ assert Path(path).read_text().split() == [UNBAKED], args+++def test_uninstall_protection_survives_the_pip_requirement_env(shim, tmp_path, monkeypatch):+ req = tmp_path / "remove.txt"+ req.write_text(f"torchcodec\n{UNBAKED}\n")+ monkeypatch.setenv("PIP_REQUIREMENT", str(req))++ def _fake_execve(path, argv, env):+ assert "PIP_REQUIREMENT" not in env+ raise _Exec(path, argv)++ monkeypatch.setattr(shim.os, "execve", _fake_execve)+ execd = _run(shim, ["-y"], sub = "uninstall")+ assert execd is not None and execd[0] == "-r" and execd[2] == "-y", execd+ assert Path(execd[1]).read_text().split() == [UNBAKED]+++def test_uninstall_requirements_file_extras_do_not_reach_the_baked_package(shim, tmp_path):+ req = tmp_path / "remove.txt"+ req.write_text(f"torch[opt]\ntransformers[torch]\n{UNBAKED}\n")+ execd = _run(shim, ["-y", "-r", str(req)], sub = "uninstall")+ assert Path(execd[-1]).read_text().split() == [UNBAKED]+++def test_uninstall_requirements_file_of_only_baked_packages_is_a_no_op(shim, tmp_path, capsys):+ req = tmp_path / "remove.txt"+ req.write_text("# baked\ntorchcodec\nunsloth[colab-new]\n")+ for args in (["-y", "-r", str(req)], ["-y", f"-r{req}"], ["-y", f"--requirement={req}"]):+ assert _run(shim, args, sub = "uninstall") is None, args+ assert "nothing to uninstall" in capsys.readouterr().out+ assert _run(shim, ["-y", "-r", str(req), UNBAKED], sub = "uninstall") == ["-y", UNBAKED]++[email protected]("var", ["PIP_TARGET", "PIP_PREFIX", "PIP_ROOT"])+def test_pip_uninstall_ignores_install_destination_variables(shim, monkeypatch, tmp_path, var):+ monkeypatch.setenv(var, str(tmp_path / "outside"))+ assert _run(shim, ["-y", "torch"], sub = "uninstall") is None+ assert _run(shim, ["-y", UNBAKED], sub = "uninstall") == ["-y", UNBAKED]++[email protected]("tool", ["pip", "uv"])+def test_targetless_uninstall_reaches_the_real_cli(shim, tool):+ assert _run(shim, ["--help"], tool = tool, sub = "uninstall") == ["--help"]+ assert _run(shim, ["-y"], tool = tool, sub = "uninstall") == ["-y"]