Skip to content

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.

Installer: keep status messages off the progress bar line (#8052)

oobabooga5659a9c47e5c
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 3bc9f845203..0e04ca8769a 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -387,7 +387,7 @@ def _repair_bad_anyio() -> None:
installed = _installed_anyio_version()
if installed is None or installed < _ANYIO_BAD_FLOOR:
return
- _safe_print(_dim(f" anyio {installed[0]}.{installed[1]} found -- reinstalling anyio<4.14..."))
+ _note(f"anyio {installed[0]}.{installed[1]} found -- reinstalling anyio<4.14...")
pip_install(
"Repairing anyio version",
"--no-cache-dir",
@@ -696,13 +696,13 @@ def _pick_visible_index(num_tokens: int, warn: bool = True) -> int:
# warns the same). Callers with a deduplicated list pass warn=False: there the
# index space is arches, not devices, so out of range is normal.
if warn:
- print(
+ _safe_print(
f" [WARN] {_env}={_first} is out of range ({num_tokens} GPU(s) "
f"detected); defaulting to GPU 0 for arch selection."
)
except ValueError:
if warn:
- print(
+ _safe_print(
f" [WARN] {_env}={_val} is not a device index; defaulting to "
f"GPU 0 for arch selection. Use UNSLOTH_ROCM_GFX_ARCH to choose "
f"the arch directly."
@@ -755,7 +755,7 @@ def _detect_windows_gfx_arch() -> str | None:
and any(_windows_rocm_index_url(t) for t in _distinct)
):
_usable = [t for t in _distinct if _windows_rocm_index_url(t)]
- print(
+ _safe_print(
f" [WARN] the pinned GPU is {_pick}, which has no AMD Windows "
f"wheels, so torch will be CPU-only. {', '.join(_usable)} on this "
f"host does have wheels -- clear the visible-device mask or point "
@@ -779,17 +779,17 @@ def _detect_windows_gfx_arch() -> str | None:
# Not always device 1: on gfx1036,gfx1010,gfx1200 it is device 2, and
# saying "mask 1" would expose the gfx1010 the wheels do not target.
_other_idx = tokens.index(_other)
- print(
+ _safe_print(
f" multiple AMD GPUs detected ({', '.join(_distinct)}); "
f"installing for {_other} instead of the integrated {_pick}."
)
- print(
+ _safe_print(
f" Run 'setx HIP_VISIBLE_DEVICES {_other_idx}' and reopen your "
f"terminal so Unsloth uses {_other} at runtime too, not just at "
f"install time."
)
return _other
- print(
+ _safe_print(
f" multiple AMD GPUs detected ({', '.join(_distinct)}); "
f"installing for {_pick}. Set HIP_VISIBLE_DEVICES to the GPU index "
f"you want (then rerun) to install for a different device."
@@ -942,11 +942,11 @@ def _detect_windows_gfx_arch() -> str | None:
# resolved and reported against the adapter list above.
_pick = _dedup_pick(_tokens, warn = False) if len(_tokens) == len(_names) else _named
if _pick:
- print(f" gfx arch inferred from GPU name (WMI): {_pick}")
+ _safe_print(f" gfx arch inferred from GPU name (WMI): {_pick}")
return _pick
if _names and not _pick:
# No arch means CPU-only torch; name the adapter instead of failing silently.
- print(
+ _safe_print(
f" [WARN] could not map '{_names[_sel]}' to a gfx arch, so torch "
f"will be CPU-only. Set UNSLOTH_ROCM_GFX_ARCH to your GPU's arch "
f"(e.g. gfx1200) to install AMD wheels."
@@ -1295,7 +1295,7 @@ def _persist_bnb_rocm_version(version: str) -> bool:
finally:
tmp_path.unlink(missing_ok = True)
except (OSError, UnicodeDecodeError) as exc:
- print(
+ _safe_print(
f" Warning: could not persist BNB_ROCM_VERSION={version} "
f"to {sitecustomize_path}: {exc}"
)
@@ -1545,7 +1545,7 @@ def _install_bnb_windows_rocm() -> bool:
force_pip = True,
)
if not _ok:
- print(
+ _safe_print(
_red(
" bnb pre-release install failed; falling back to PyPI "
f"{_BNB_ROCM_PYPI_FALLBACK}, which carries the ROCm 4-bit fix"
@@ -1679,14 +1679,14 @@ def _cap_cuda_family_for_pre_turing(family: str, exe: "str | None") -> str:
if not sms or all(sm >= floor for sm in sms):
return family # no GPU here sits under the family's floor
if not _span_covers(_CU126_SM_RANGE, sms):
- print(
+ _safe_print(
f" NVIDIA GPUs below sm_{floor} are present, but no PyTorch 2.11 CUDA "
f"family covers this mix -- keeping {family}, which cannot use "
+ ",".join(f"sm_{sm}" for sm in sorted(set(sms)) if sm < floor)
+ ". Set UNSLOTH_TORCH_INDEX_FAMILY=cu126 to choose the other way"
)
return family
- print(
+ _safe_print(
f" NVIDIA GPUs below sm_{floor} are present -- selecting cu126, because "
f"PyTorch 2.11's {family} wheels ship no kernels for them"
)
@@ -1986,7 +1986,7 @@ def _ensure_cuda_torch() -> None:
return
index_url = _detect_cuda_torch_index_url()
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
- print(
+ _safe_print(
f" torch cannot import but an explicit CUDA index is pinned -- reinstalling "
f"CUDA torch from {_strip_index_url_credentials(index_url)}"
)
@@ -2058,7 +2058,7 @@ def _ensure_cuda_torch() -> None:
if index_url is None:
index_url = _detect_cuda_torch_index_url()
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
- print(
+ _safe_print(
f" {_why} -- reinstalling CUDA torch from {_strip_index_url_credentials(index_url)}\n"
f" (set UNSLOTH_TORCH_BACKEND=rocm or cpu to keep a deliberate "
f"non-CUDA torch)"
@@ -2121,7 +2121,7 @@ def _ensure_xpu_torch() -> None:
# reinstalling never fixes a driver -- it would just re-download the trio twice per
# update, since this helper runs at two repair points.
if _xpu_wheel_supported_on_disk():
- print(
+ _safe_print(
_red(
" torch did not respond in time; the installed XPU build is supported, "
"so this is the Intel GPU compute driver -- update it and re-run"
@@ -2149,7 +2149,7 @@ def _ensure_xpu_torch() -> None:
else:
_why = "torch cannot import"
- print(
+ _safe_print(
f" {_why} but an explicit XPU index is pinned -- reinstalling XPU torch from "
f"{_strip_index_url_credentials(pin)}"
)
@@ -2302,9 +2302,9 @@ def _ensure_xpu_triton() -> None:
if not generic or "xpu" not in spec.lower():
return
- print(f" replacing triton {generic} with {spec} (Intel XPU)")
+ _safe_print(f" replacing triton {generic} with {spec} (Intel XPU)")
if not _ensure_venv_pip():
- print(
+ _safe_print(
_red(
f" no pip in the venv to fetch {spec}; generic triton {generic} left in "
"place -- it shadows torch XPU triton, so torch.compile will not use the XPU"
@@ -2348,7 +2348,7 @@ def _ensure_xpu_triton() -> None:
wheels = glob.glob(os.path.join(tmp, "*.whl"))
# The exit code alone is not enough: no wheel on disk means nothing to install from.
if dl is None or dl.returncode != 0 or not wheels:
- print(
+ _safe_print(
_red(
f" could not fetch {spec}; generic triton {generic} left in place -- "
"it shadows torch XPU triton, so torch.compile will not use the XPU"
@@ -2364,7 +2364,7 @@ def _ensure_xpu_triton() -> None:
# A read-only or locked venv leaves generic triton REGISTERED; installing over it
# would let a later upgrade or uninstall delete the shared files again. Change
# nothing.
- print(
+ _safe_print(
_red(
f" could not remove generic triton {generic}; leaving it in place -- it "
"shadows torch XPU triton, so torch.compile will not use the XPU"
@@ -2460,7 +2460,7 @@ def _ensure_cpu_torch() -> None:
# probe) and the base update won't reinstall an already-installed torch, so
# reinstall from the pin (self-resolving, no loop).
_torch_pkg, _vision_pkg, _audio_pkg = _CPU_TORCH_PKG_SPEC
- print(
+ _safe_print(
f" torch cannot import but an explicit CPU index is pinned -- reinstalling "
f"CPU torch from {_strip_index_url_credentials(pin)}"
)
@@ -2484,7 +2484,7 @@ def _ensure_cpu_torch() -> None:
if _lines[-1] != "gpu":
return # already a CPU build
- print(
+ _safe_print(
" torch is a GPU build but an explicit CPU index is pinned -- reinstalling "
f"CPU torch from {_strip_index_url_credentials(pin)}"
)
@@ -2595,7 +2595,7 @@ def _ensure_rocm_torch() -> None:
_want = (_GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "") or "").lower()
_have = _installed_rocm_wheel_family()
if _want and _have and _have != _want:
- print(
+ _safe_print(
f" installed ROCm torch is the {_have} build but {gfx_arch} needs "
f"{_want} -- reinstalling for this GPU"
)
@@ -2603,9 +2603,9 @@ def _ensure_rocm_torch() -> None:
if not _torch_already_rocm:
index_url = _win_rocm_pin or _windows_rocm_index_url(gfx_arch)
if index_url is None:
- print(f" No AMD Windows torch index for GPU arch {gfx_arch} -- skipping")
+ _safe_print(f" No AMD Windows torch index for GPU arch {gfx_arch} -- skipping")
return
- print(
+ _safe_print(
f" {gfx_arch or 'pinned ROCm index'} (Windows) -- installing torch from "
f"{_strip_index_url_credentials(index_url)}"
)
@@ -2627,7 +2627,7 @@ def _ensure_rocm_torch() -> None:
_audio_pkg,
constrain = False,
):
- print(
+ _safe_print(
f" Warning: AMD Windows ROCm torch install failed for {gfx_arch or 'the pinned index'}; "
"keeping the existing torch build. Re-run 'unsloth studio update' "
"later to retry ROCm."
@@ -2641,7 +2641,7 @@ def _ensure_rocm_torch() -> None:
# Always install AMD Windows bitsandbytes, even when torch was already a
# ROCm build, so `studio update` repairs a broken bnb.
if not _install_bnb_windows_rocm():
- print(
+ _safe_print(
" Warning: AMD Windows bitsandbytes install failed "
"(pre-release and PyPI); "
"ROCm torch is installed but bitsandbytes may need manual install"
@@ -2669,7 +2669,7 @@ def _ensure_rocm_torch() -> None:
ver = _detect_rocm_version()
if ver is None:
if _rocm_pin is None and not _inferred_linux_gfx:
- print(" ROCm detected but version unreadable -- skipping torch reinstall")
+ _safe_print(" ROCm detected but version unreadable -- skipping torch reinstall")
return
# Explicit pin or inferred gfx: the index drives the install.
ver = (0, 0)
@@ -2740,8 +2740,8 @@ def _ensure_rocm_torch() -> None:
_torch_pkg, _vision_pkg, _audio_pkg = _WINDOWS_ROCM_TORCH_PKG_SPECS.get(
_inferred_linux_gfx, ("torch", "torchvision", "torchaudio")
)
- print(
- f"\n {_inferred_linux_gfx} inferred (ROCm runtime not visible) -- "
+ _safe_print(
+ f" {_inferred_linux_gfx} inferred (ROCm runtime not visible) -- "
f"installing torch from {_strip_index_url_credentials(index_url)}\n"
f" AMD wheels bundle their own ROCm runtime; install the kernel stack "
f"for native GPU compute.\n"
@@ -2814,8 +2814,8 @@ def _ensure_rocm_torch() -> None:
"torchvision>=0.26.0,<0.27.0",
"torchaudio>=2.11.0,<2.12.0",
)
- print(
- f"\n {_selected_gfx} (AMD Strix) is the runtime target with ROCm "
+ _safe_print(
+ f" {_selected_gfx} (AMD Strix) is the runtime target with ROCm "
f"{ver[0]}.{ver[1]}.\n"
f" Routing torch install to AMD's arch-specific index\n"
f" ({_strix_override_url}) which serves torch 2.11.0+rocm7.13.0\n"
@@ -2824,8 +2824,8 @@ def _ensure_rocm_torch() -> None:
)
else:
_gfx_str = ", ".join(sorted(_detected_strix))
- print(
- f"\n Strix GPU ({_gfx_str}) present but HIP_VISIBLE_DEVICES "
+ _safe_print(
+ f" Strix GPU ({_gfx_str}) present but HIP_VISIBLE_DEVICES "
f"selects a non-Strix runtime target ({_runtime_gfx});\n"
f" skipping AMD per-gfx index override.\n"
)
@@ -2848,8 +2848,8 @@ def _ensure_rocm_torch() -> None:
and _strix_override_url is None
)
if _gfx906_override:
- print(
- f"\n gfx906 (MI50 / Radeon VII / Vega 20) is the runtime target with ROCm "
+ _safe_print(
+ f" gfx906 (MI50 / Radeon VII / Vega 20) is the runtime target with ROCm "
f"{ver[0]}.{ver[1]}.\n"
f" Routing torch install to the {_GFX906_LEGACY_TAG} index: the last wheel\n"
f" family that runs on gfx906 (newer rocm wheels ship without gfx906 BLAS\n"
@@ -2863,7 +2863,7 @@ def _ensure_rocm_torch() -> None:
if _strix_override_url is not None and _strix_override_pkgs is not None:
index_url = _strix_override_url
_torch_pkg, _vision_pkg, _audio_pkg = _strix_override_pkgs
- print(
+ _safe_print(
f" Strix arch-specific override -- installing torch from "
f"{_strip_index_url_credentials(index_url)}"
)
@@ -2886,7 +2886,7 @@ def _ensure_rocm_torch() -> None:
elif _gfx906_override and _GFX906_LEGACY_TAG not in _installed_torch_ver:
index_url = f"{_PYTORCH_WHL_BASE}/{_GFX906_LEGACY_TAG}"
_torch_pkg, _vision_pkg, _audio_pkg = _ROCM_TORCH_PKG_SPECS["_default"]
- print(
+ _safe_print(
f" gfx906 legacy override -- installing torch from "
f"{_strip_index_url_credentials(index_url)}"
)
@@ -2922,11 +2922,15 @@ def _ensure_rocm_torch() -> None:
None,
)
if tag is None:
- print(f" No PyTorch wheel for ROCm {ver[0]}.{ver[1]} -- skipping torch reinstall")
+ _safe_print(
+ f" No PyTorch wheel for ROCm {ver[0]}.{ver[1]} -- skipping torch reinstall"
+ )
else:
if _override_idx is None:
index_url = f"{_PYTORCH_WHL_BASE}/{tag}"
- print(f" ROCm torch -- installing from {_strip_index_url_credentials(index_url)}")
+ _safe_print(
+ f" ROCm torch -- installing from {_strip_index_url_credentials(index_url)}"
+ )
# Only the _grouped_mm-bug gfx arches need the 2.11 spec; other gfx indexes ship
# <2.11 and stay on the default range (matches install.ps1 / setup.ps1).
if tag in _ROCM_GFX_TORCH211_LEAVES:
@@ -2955,7 +2959,7 @@ def _ensure_rocm_torch() -> None:
# source-built bnb (the only 4-bit path on this arch) on every `studio update`.
# Skip the auto-install and leave whatever bnb is present.
if rocm_torch_ready and _runtime_is_gfx906:
- print(
+ _safe_print(
_dim(
" gfx906: skipping prebuilt bitsandbytes (no gfx906 kernels). "
"Build bitsandbytes from source for 4-bit QLoRA -- "
@@ -2967,7 +2971,7 @@ def _ensure_rocm_torch() -> None:
# 4-bit use). Drop it if this run pulled it in; a pre-existing source build
# (present before the base install) is left untouched.
if _GFX906_BNB_ABSENT_BEFORE_BASE and _bitsandbytes_installed():
- print(_dim(" gfx906: removing generic bitsandbytes pulled in as a dependency"))
+ _safe_print(_dim(" gfx906: removing generic bitsandbytes pulled in as a dependency"))
subprocess.run(
[sys.executable, "-m", "pip", "uninstall", "-y", "bitsandbytes"],
capture_output = True,
@@ -2993,7 +2997,7 @@ def _ensure_rocm_torch() -> None:
_fallback_note = (
", which carries the ROCm 4-bit fix" if _bnb_rocm_arch_has_binary() else ""
)
- print(
+ _safe_print(
_red(
" bnb pre-release install failed; falling back to PyPI "
f"{_BNB_ROCM_PYPI_FALLBACK}{_fallback_note}"
@@ -3009,7 +3013,7 @@ def _ensure_rocm_torch() -> None:
constrain = False,
)
if not _bnb_rocm_arch_has_binary():
- print(
+ _safe_print(
_red(
" aarch64: bitsandbytes ships no ROCm kernels on this arch; "
"4-bit QLoRA needs a source build -- "
@@ -3160,7 +3164,13 @@ _UNICODE_TO_ASCII: dict[str, str] = {
def _safe_print(*args: object, **kwargs: object) -> None:
- """Drop-in print() replacement that survives non-UTF-8 consoles and detached stdout."""
+ """Drop-in print() replacement that survives non-UTF-8 consoles and detached stdout.
+
+ Closes an open progress bar line first: _progress() leaves the cursor mid-line,
+ so centralising it here (nothing calls print() directly -- see
+ test_no_bare_print_calls) keeps every message off the bar.
+ """
+ _end_progress_line()
try:
print(*args, **kwargs)
except OSError:
@@ -3241,13 +3251,44 @@ def _title(msg: str) -> str:
_RULE = "\u2500" * 52
+def _end_progress_line() -> None:
+ """Close an in-place progress bar line so the next print starts on its own line."""
+ global _PROGRESS_LINE_ACTIVE
+ if not _PROGRESS_LINE_ACTIVE or VERBOSE:
+ return
+ try:
+ sys.stdout.write("\n")
+ sys.stdout.flush()
+ # Every _safe_print() lands here: a detached (None) or closed stdout must not
+ # take down a message bound for stderr.
+ except (AttributeError, OSError, ValueError):
+ pass
+ _PROGRESS_LINE_ACTIVE = False
+
+
+def _note(message: str, color_fn = None) -> None:
+ """Print a detail line under the current step, aligned to the value column."""
+ if color_fn is None:
+ color_fn = _dim
+ # Verbose prints no bar and no step line, so there is no value column to align to.
+ prefix = " " if VERBOSE else " " * (_INDENT + _COL)
+ wrap_width = max(24, shutil.get_terminal_size((100, 20)).columns - len(prefix))
+ lines = textwrap.wrap(
+ message,
+ width = wrap_width,
+ break_long_words = False,
+ break_on_hyphens = False,
+ ) or [""]
+ for line in lines:
+ _safe_print(f"{prefix}{color_fn(line)}")
+
+
def _step(
label: str,
value: str,
color_fn = None,
) -> None:
"""Print a single step line in the column format."""
- global _PROGRESS_LINE_ACTIVE
if color_fn is None:
color_fn = _green
padded = label[:_COL]
@@ -3263,13 +3304,6 @@ def _step(
break_long_words = False,
break_on_hyphens = False,
) or [""]
- if _PROGRESS_LINE_ACTIVE and not VERBOSE:
- try:
- sys.stdout.write("\n")
- sys.stdout.flush()
- except OSError:
- pass
- _PROGRESS_LINE_ACTIVE = False
_safe_print(f"{prefix}{color_fn(lines[0])}")
continuation_prefix = " " * plain_prefix_width
for line in lines[1:]:
@@ -3316,7 +3350,7 @@ def run(
if result.stdout:
# Redact before printing: the failing pip command may carry a pinned --index-url
# with userinfo/?token= creds, so raw pip error text would leak them.
- print(_redact_install_output(result.stdout))
+ _safe_print(_redact_install_output(result.stdout))
sys.exit(result.returncode)
return result
@@ -3353,7 +3387,7 @@ def _print_optional_install_failure(label: str, result: subprocess.CompletedProc
_step("warning", f"{label} failed (exit code {result.returncode})", _cyan)
if result.stdout:
# Redact any pinned --index-url credentials before printing captured output.
- print(_redact_install_output(result.stdout).strip())
+ _safe_print(_redact_install_output(result.stdout).strip())
def _flash_attn_install_disabled() -> bool:
@@ -3584,11 +3618,11 @@ def pip_install_try(
if result.returncode == 0:
# As pip_install below: `nobuild` only catches a build that reaches the log.
if VERBOSE and result.stdout:
- print(_redact_install_output(result.stdout))
+ _safe_print(_redact_install_output(result.stdout))
return True
if VERBOSE and result.stdout:
# pip/uv echo index URLs (credentials included) in failure output.
- print(_redact_install_output(result.stdout))
+ _safe_print(_redact_install_output(result.stdout))
return False
@@ -3631,7 +3665,7 @@ def pip_install(
if USE_UV:
uv_cmd = _build_uv_cmd(args) + constraint_args_uv + req_args_uv
if VERBOSE:
- print(f" {label}...")
+ _safe_print(f" {label}...")
result = subprocess.run(
uv_cmd,
stdout = subprocess.PIPE,
@@ -3647,11 +3681,11 @@ def pip_install(
# install, where sdist-only dependencies show up -- reported
# "built: none" and stayed green. Redacted: uv echoes credentialed URLs.
if VERBOSE and result.stdout:
- print(_redact_install_output(result.stdout))
+ _safe_print(_redact_install_output(result.stdout))
return
- print(_red(f" uv failed, falling back to pip..."))
+ _safe_print(_red(f" uv failed, falling back to pip..."))
if result.stdout:
- print(_redact_install_output(result.stdout))
+ _safe_print(_redact_install_output(result.stdout))
pip_cmd = _build_pip_cmd(args) + constraint_args_pip + req_args_pip
run(f"{label} (pip)" if USE_UV else label, pip_cmd)
@@ -3720,8 +3754,11 @@ def _has_working_git() -> bool:
def install_python_stack() -> int:
- global USE_UV, _STEP, _TOTAL
+ global USE_UV, _STEP, _TOTAL, _PROGRESS_LINE_ACTIVE
_STEP = 0
+ # An aborted earlier run leaves it set, and every _safe_print() consumes it --
+ # the first message would get a stray newline.
+ _PROGRESS_LINE_ACTIVE = False
# install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling base packages;
# `studio update` does NOT, so unsloth + unsloth-zoo are reinstalled to pick
@@ -3744,7 +3781,7 @@ def install_python_stack() -> int:
# the preflight that an interrupted run left the venv half-built. Stop if it
# survives rather than mutate the venv behind a marker that still verifies.
if not install_manifest.remove_manifest():
- print(
+ _safe_print(
f"error: could not remove the stale {install_manifest.MANIFEST_NAME} in "
f"{install_manifest.venv_root()}; refusing to install behind a marker "
"that would still report this venv as complete",
@@ -3976,13 +4013,10 @@ def install_python_stack() -> int:
_win_amd_gpu = True
break
if _win_amd_gpu and not _rocm_windows_torch_installed:
- _safe_print(
- _dim(" Note:"),
- "AMD GPU detected but ROCm PyTorch could not be auto-installed.",
- )
- _safe_print(
- " " * 8,
- "Manual install may be required. See: https://docs.unsloth.ai/get-started/install-and-update/amd",
+ _note(
+ "AMD GPU detected but ROCm PyTorch could not be auto-installed. "
+ "Manual install may be required. See: "
+ "https://docs.unsloth.ai/get-started/install-and-update/amd"
)
# 3. Extra dependencies
@@ -4013,12 +4047,12 @@ def install_python_stack() -> int:
# and crashes transformers.quantizers. Unsloth stubs it at runtime, so
# installing it only ships a package that crashes on import -- skip it.
_progress("dependency overrides (skipped, Windows ROCm)")
- _safe_print(" Windows ROCm -- skipping torchao (no working build; stubbed at runtime)")
+ _note("Windows ROCm -- skipping torchao (no working build; stubbed at runtime)")
else:
_progress("dependency overrides")
_torch_ver = _probe_installed_torch_version()
_torchao_spec = _select_torchao_spec(_torch_ver)
- _safe_print(f" torch {_torch_ver or 'unknown'} detected -- installing {_torchao_spec}")
+ _note(f"torch {_torch_ver or 'unknown'} detected -- installing {_torchao_spec}")
pip_install(
"Installing dependency overrides",
"--force-reinstall",
@@ -4032,7 +4066,7 @@ def install_python_stack() -> int:
if not IS_WINDOWS and not IS_MACOS:
if not _has_working_git():
_progress("triton kernels (skipped, no git)")
- _safe_print(" no working git -- skipping triton kernels (training speedup only)")
+ _note("no working git -- skipping triton kernels (training speedup only)")
else:
_progress("triton kernels")
pip_install(
@@ -4104,11 +4138,7 @@ def install_python_stack() -> int:
]
for _plugin_name, plugin_dir in local_dd_plugins:
if not plugin_dir.is_dir():
- _safe_print(
- _red(
- f"❌ Missing local plugin directory: {plugin_dir}",
- ),
- )
+ _note(f"❌ Missing local plugin directory: {plugin_dir}", _red)
return 1
_progress("local plugin")
for plugin_name, plugin_dir in local_dd_plugins:
@@ -4157,7 +4187,7 @@ def install_python_stack() -> int:
)
is None
):
- print(
+ _safe_print(
f"error: could not write {install_manifest.MANIFEST_NAME} to "
f"{install_manifest.venv_root()}",
file = sys.stderr,
diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.py
index 3a12e53f95e..9895e4ddefc 100644
--- a/tests/python/test_install_python_stack.py
+++ b/tests/python/test_install_python_stack.py
@@ -2,9 +2,13 @@
from __future__ import annotations
+import ast
+import contextlib
import glob
import importlib
+import io
import os
+import re
import sys
import tempfile
from pathlib import Path
@@ -282,3 +286,228 @@ class TestPinnedIndexClearsUvEnv:
configuration still applies to base packages."""
env = ips._install_env_for_cmd(["uv", "pip", "install", "unsloth"])
assert env is None
+
+
+class TestProgressLineNotes:
+ """_progress() leaves the cursor mid-line, so anything printed between two
+ progress steps must close that line first. Before centralising this, a real
+ install glued the torchao message onto the bar:
+ deps [=======-------------] 5/14 dependency overrides torch 2.11...
+ """
+
+ def _render(
+ self,
+ emit,
+ *,
+ columns = "100",
+ verbose = False,
+ color = False,
+ ) -> str:
+ buf = io.StringIO()
+ with (
+ mock.patch.dict(os.environ, {"COLUMNS": columns}),
+ mock.patch.object(ips, "VERBOSE", verbose),
+ # _HAS_COLOR is resolved once at import from the tty; pinning it keeps the
+ # assertions valid under FORCE_COLOR=1 or `pytest -s` in a terminal.
+ mock.patch.object(ips, "_HAS_COLOR", color),
+ mock.patch.object(ips, "_TOTAL", 14),
+ mock.patch.object(ips, "_STEP", 4),
+ mock.patch.object(ips, "_PROGRESS_LINE_ACTIVE", False),
+ contextlib.redirect_stdout(buf),
+ ):
+ emit()
+ return buf.getvalue()
+
+ def test_note_does_not_glue_onto_the_progress_bar(self):
+ msg = "torch 2.11.0+cu130 detected -- installing torchao==0.17.0"
+ out = self._render(lambda: (ips._progress("dependency overrides"), ips._note(msg)))
+ bar_lines = [ln for ln in out.split("\n") if "5/14" in ln]
+ assert len(bar_lines) == 1, f"expected one bar line, got {bar_lines!r}"
+ assert msg not in bar_lines[0], f"note glued onto the bar: {bar_lines[0]!r}"
+ assert any(ln.strip() == msg for ln in out.split("\n")), out
+
+ def test_note_aligns_under_the_step_value_column(self):
+ out = self._render(lambda: (ips._progress("dependency overrides"), ips._note("hello")))
+ note_line = next(ln for ln in out.split("\n") if ln.strip() == "hello")
+ assert len(note_line) - len(note_line.lstrip()) == ips._INDENT + ips._COL
+
+ def test_note_without_an_active_bar_prints_on_its_own(self):
+ out = self._render(lambda: ips._note("standalone"))
+ assert out == f"{' ' * (ips._INDENT + ips._COL)}standalone\n"
+
+ def test_step_still_closes_an_active_bar(self):
+ """_step() handed its inline line-break logic to _end_progress_line(); it
+ must keep breaking out of the bar."""
+ out = self._render(
+ lambda: (ips._progress("dependency overrides"), ips._step("deps", "installed"))
+ )
+ bar_lines = [ln for ln in out.split("\n") if "5/14" in ln]
+ assert len(bar_lines) == 1 and "installed" not in bar_lines[0], out
+
+ def test_progress_line_state_is_cleared(self):
+ """A stale _PROGRESS_LINE_ACTIVE blank-lines the next note instead of
+ closing a bar that is no longer open."""
+
+ def emit():
+ ips._progress("dependency overrides")
+ ips._note("first")
+ assert ips._PROGRESS_LINE_ACTIVE is False
+ ips._note("second")
+
+ out = self._render(emit)
+ assert "\n\n" not in out, out
+
+ def test_uv_fallback_warning_does_not_glue_onto_the_bar(self):
+ """A real producer, not _note() directly: pip_install() warns on the uv
+ fallback while the bar for its own step is still open. This path survived
+ the first pass of the fix, which only converted ' message' call sites."""
+ fake = mock.Mock(returncode = 1, stdout = "uv output")
+ with (
+ mock.patch.object(ips, "USE_UV", True),
+ mock.patch.object(ips, "subprocess") as sp,
+ mock.patch.object(ips, "run") as fallback,
+ ):
+ sp.run.return_value = fake
+ sp.PIPE, sp.STDOUT = -1, -2
+ out = self._render(
+ lambda: (ips._progress("studio deps"), ips.pip_install("Installing studio deps"))
+ )
+ assert fallback.called, "expected the pip fallback to run"
+ bar_lines = [ln for ln in out.split("\n") if "5/14" in ln]
+ assert len(bar_lines) == 1, f"expected one bar line, got {bar_lines!r}"
+ assert "uv failed" not in bar_lines[0], f"warning glued onto the bar: {bar_lines[0]!r}"
+
+ def test_no_bare_print_calls(self):
+ """The line-close lives in _safe_print(), so a direct print() anywhere in
+ the module silently reintroduces the glued-line bug."""
+ src = Path(ips.__file__).read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ allowed = [
+ (n.lineno, n.end_lineno)
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_safe_print"
+ ]
+ offenders = [
+ n.func.lineno
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Name)
+ and n.func.id == "print"
+ and not any(lo <= n.func.lineno <= hi for lo, hi in allowed)
+ ]
+ assert not offenders, (
+ f"install_python_stack.py:{offenders} call print() directly; "
+ "use _safe_print() or _note() so an open progress bar line is closed first"
+ )
+
+ def test_no_direct_stdout_writes(self):
+ """Copying _progress()'s sys.stdout.write idiom elsewhere would glue onto
+ the bar again while still passing test_no_bare_print_calls."""
+ tree = ast.parse(Path(ips.__file__).read_text(encoding = "utf-8"))
+ allowed = [
+ (n.lineno, n.end_lineno)
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name in {"_progress", "_end_progress_line"}
+ ]
+ offenders = [
+ n.lineno
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Attribute)
+ and n.func.attr in {"write", "flush"}
+ and isinstance(n.func.value, ast.Attribute)
+ and n.func.value.attr == "stdout"
+ and not any(lo <= n.lineno <= hi for lo, hi in allowed)
+ ]
+ assert not offenders, (
+ f"install_python_stack.py:{offenders} write to sys.stdout directly; "
+ "only _progress()/_end_progress_line() may, everything else uses _safe_print()"
+ )
+
+ def test_no_message_starts_with_a_newline(self):
+ """_safe_print() closes the bar itself now, so a message literal still
+ opening with \\n emits a second newline and a blank line."""
+ tree = ast.parse(Path(ips.__file__).read_text(encoding = "utf-8"))
+
+ def leads_with_newline(node) -> bool:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return node.value.startswith("\n")
+ if isinstance(node, ast.JoinedStr) and node.values:
+ return leads_with_newline(node.values[0])
+ return False
+
+ offenders = [
+ n.lineno
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Name)
+ and n.func.id in {"_safe_print", "_note"}
+ and n.args
+ and leads_with_newline(n.args[0])
+ ]
+ assert not offenders, (
+ f"install_python_stack.py:{offenders} start a message with a newline; "
+ "_safe_print() already closes the progress bar line, so this blank-lines the output"
+ )
+
+ def test_note_wraps_at_the_value_column_on_a_narrow_terminal(self):
+ """Wrapping is all that separates _note() from _safe_print(), and no other
+ test makes it wrap: every message fits one line at COLUMNS=100."""
+ msg = (
+ "AMD GPU detected but ROCm PyTorch could not be auto-installed. Manual install "
+ "may be required. See: https://docs.unsloth.ai/get-started/install-and-update/amd"
+ )
+ out = self._render(lambda: ips._note(msg), columns = "60")
+ lines = [ln for ln in out.split("\n") if ln.strip()]
+ assert len(lines) > 1, f"expected the message to wrap, got {out!r}"
+ for line in lines:
+ assert len(line) - len(line.lstrip()) == ips._INDENT + ips._COL, repr(line)
+ assert " ".join(ln.strip() for ln in lines) == msg
+ # break_long_words = False keeps the URL clickable rather than splitting it.
+ assert any("https://docs.unsloth.ai" in ln for ln in lines), out
+
+ def test_note_falls_back_to_the_flat_indent_in_verbose_mode(self):
+ """Verbose prints no bar and no step line, so the value column would indent
+ under nothing while neighbouring messages sit at column 3."""
+ out = self._render(lambda: ips._note("hello"), verbose = True)
+ assert out == " hello\n", repr(out)
+
+ def test_note_still_aligns_when_colour_is_on(self):
+ """The layout must survive a colour terminal, where every line carries ANSI
+ codes that occupy no columns."""
+ out = self._render(lambda: ips._note("hello"), color = True)
+ assert "\033[" in out, "expected ANSI codes with _HAS_COLOR on"
+ plain = re.sub(r"\033\[[0-9;]*m", "", out)
+ assert plain == f"{' ' * (ips._INDENT + ips._COL)}hello\n", repr(plain)
+
+ def test_safe_print_to_stderr_survives_a_closed_stdout(self):
+ """_safe_print() touches stdout on every call now, so stderr-bound manifest
+ errors must not die on an unrelated stdout failure."""
+ closed = io.StringIO()
+ closed.close()
+ err = io.StringIO()
+ with (
+ mock.patch.object(ips, "VERBOSE", False),
+ mock.patch.object(ips, "_PROGRESS_LINE_ACTIVE", True),
+ mock.patch.object(ips.sys, "stdout", closed),
+ ):
+ ips._safe_print("error: boom", file = err)
+ assert err.getvalue() == "error: boom\n"
+
+ def test_install_entry_clears_a_stale_progress_line(self):
+ """_PROGRESS_LINE_ACTIVE outlives an aborted run, and now every _safe_print()
+ reads it, so a stale flag newlines the next run."""
+ src = Path(ips.__file__).read_text(encoding = "utf-8")
+ fn = next(
+ n
+ for n in ast.walk(ast.parse(src))
+ if isinstance(n, ast.FunctionDef) and n.name == "install_python_stack"
+ )
+ assert any(
+ isinstance(n, ast.Global) and "_PROGRESS_LINE_ACTIVE" in n.names for n in ast.walk(fn)
+ ), "install_python_stack() must declare _PROGRESS_LINE_ACTIVE global"
+ assert any(
+ isinstance(n, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "_PROGRESS_LINE_ACTIVE" for t in n.targets)
+ for n in ast.walk(fn)
+ ), "install_python_stack() must reset _PROGRESS_LINE_ACTIVE"
diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.py
index c41ff9788d8..c72385ac66d 100644
--- a/tests/studio/test_xpu_triton_swap.py
+++ b/tests/studio/test_xpu_triton_swap.py
@@ -84,6 +84,9 @@ def _load(
body = src[start:end]
assert "_ensure_xpu_triton" in body, "extraction lost the swap"
assert "_ensure_venv_pip" in body, "extraction lost the pip bootstrap"
+ # The WARN assertions need the stub wired to the name the slice actually calls;
+ # a rename would leave them silently dead.
+ assert "_safe_print(" in body, "extraction lost the print helper the WARN stub hooks"
import glob as _glob
import importlib.util as _importlib_util
@@ -185,7 +188,11 @@ def _load(
"pip_install_try": fake_pip_install_try,
"pip_install": fake_pip_install,
"_red": lambda s: s,
- "print": lambda *a, **k: log.append("WARN") if a and "left in place" in str(a[0]) else None,
+ # _safe_print, not print: the slice calls it by name, so stubbing "print"
+ # would leave _safe_print undefined at exec time.
+ "_safe_print": (
+ lambda *a, **k: log.append("WARN") if a and "left in place" in str(a[0]) else None
+ ),
}
exec(compile(body, str(STACK), "exec"), ns)
mod.__dict__.update(ns)