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.

Studio: install the S3 SDK on demand (#14157)

Alberto Mancarella775b24688131
diff --git a/pyproject.toml b/pyproject.toml
index b5f90df1b70..4b6cae725cb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -179,7 +179,6 @@ studio = [
"cryptography>=42.0.0; sys_platform != 'win32' or platform_machine != 'ARM64'",
# Windows on ARM: 46.0.7 publishes no win_arm64 wheel and the sdist needs Rust.
"cryptography>=42.0.0,<=46.0.3; sys_platform == 'win32' and platform_machine == 'ARM64'",
- "boto3>=1.34.0",
"httpx>=0.27.0",
"fastmcp>=3.0.2",
"gguf==0.19.0 ; python_version >= '3.10'",
@@ -197,6 +196,9 @@ studio = [
"markdown-it-py>=3.0",
]
+# Optional AWS S3 dataset loading; kept out of the default Studio installation.
+s3 = ["boto3>=1.34.0"]
+
triton = [
# Not raised past 3.0.0 on purpose. torch pins triton exactly, and the oldest
# torch supported here, 2.6.0, requires `triton==3.2.0`, so any floor above
diff --git a/studio/backend/core/training/s3_dataset.py b/studio/backend/core/training/s3_dataset.py
index 247f084efca..cef4adfa823 100644
--- a/studio/backend/core/training/s3_dataset.py
+++ b/studio/backend/core/training/s3_dataset.py
@@ -6,8 +6,7 @@ S3 dataset loader.
Downloads dataset files (parquet / json / jsonl / csv) from an AWS S3 bucket
to a local temp directory so the existing local-file dataset path can consume
-them. boto3 is an optional dependency and is imported lazily — callers should
-gate on :func:`boto3_available` before invoking the loader.
+them. boto3 is an optional dependency installed on the first S3 load if missing.
Audio keys download too, keeping their prefix-relative layout, and audio values in
JSON/JSONL/CSV manifests are rewritten to the local paths (``datasets.Audio`` opens path
@@ -36,6 +35,7 @@ from importlib.util import find_spec
from typing import Callable, Optional
from utils.datasets.format_detection import _AUDIO_EXTENSIONS
from utils.paths.path_utils import drop_shadowed_appledouble_names
+from utils.s3_runtime import ensure_boto3
logger = logging.getLogger(__name__)
@@ -332,18 +332,17 @@ def prepare_s3_dataset_download(
Returns the local files plus the owned temporary directory, when one was
created. Call ``cleanup()`` after the dataset loader has materialized data.
- Raises ``RuntimeError`` if boto3 is missing, and ``ValueError`` if the
+ Raises ``RuntimeError`` if boto3 cannot be installed, and ``ValueError`` if the
bucket/prefix contains no supported dataset files.
"""
- if not boto3_available():
- raise RuntimeError("S3 dataset loading requires boto3. Install it with: pip install boto3")
-
bucket = s3_config.get("bucket")
if not bucket:
raise ValueError("s3_config.bucket is required")
prefix = s3_config.get("prefix")
_raise_if_cancelled(cancel_callback)
+ if not boto3_available():
+ ensure_boto3()
client = _build_s3_client(s3_config)
listed = _list_dataset_keys(client, bucket, prefix)
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index 0c270a0af29..da106b19738 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -688,7 +688,7 @@ class TrainingStartRequest(BaseModel):
s3_config: Optional[S3Config] = Field(
None,
- description = "S3 bucket configuration for loading datasets from AWS S3. Requires boto3 to be installed.",
+ description = 'S3 bucket configuration. Missing SDK installs on first use; preinstall offline support with: python -m pip install "unsloth[s3]"',
)
@field_validator("target_modules", mode = "before")
diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txt
index c0024de8ca9..6381a9f7c0c 100644
--- a/studio/backend/requirements/studio.txt
+++ b/studio/backend/requirements/studio.txt
@@ -46,7 +46,6 @@ cryptography>=42.0.0; sys_platform != "win32" or platform_machine != "ARM64"
# Windows on ARM: 46.0.7 has no win_arm64 wheel and its sdist needs Rust. Matches
# constraints.txt, which a plain pip install of the extra never reaches.
cryptography>=42.0.0,<=46.0.3; sys_platform == "win32" and platform_machine == "ARM64"
-boto3>=1.34.0 # optional: S3 dataset loading
httpx>=0.27.0
fastmcp>=3.0.2
# Local image generation (Images page): diffusers' GGUFQuantizationConfig needs
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 96ea2eaee45..fc84de953d2 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2025,14 +2025,15 @@ async def start_training(
detail = ("A transformers installation is in progress. Retry when it completes."),
)
- # S3 dataset loading needs the optional boto3 dependency.
+ # Install the optional SDK outside the event loop on the first S3 request.
if request.s3_config is not None and not request.resume_from_checkpoint:
from core.training.s3_dataset import boto3_available
+ from utils.s3_runtime import S3DependencyUnavailable, ensure_boto3
if not boto3_available():
- raise HTTPException(
- status_code = 501,
- detail = "S3 dataset loading requires boto3. Install it with: pip install boto3",
- )
+ try:
+ await asyncio.to_thread(ensure_boto3)
+ except S3DependencyUnavailable as exc:
+ raise HTTPException(status_code = 501, detail = str(exc)) from exc
if await asyncio.to_thread(backend.is_training_active):
existing_job_id: Optional[str] = getattr(backend, "current_job_id", "")
diff --git a/studio/backend/tests/test_s3_dataset.py b/studio/backend/tests/test_s3_dataset.py
index f47db565ff2..b2fcced01e5 100644
--- a/studio/backend/tests/test_s3_dataset.py
+++ b/studio/backend/tests/test_s3_dataset.py
@@ -148,6 +148,10 @@ def test_raises_when_no_supported_files(monkeypatch, tmp_path):
def test_raises_when_boto3_missing(monkeypatch, tmp_path):
+ from utils import s3_runtime
+
+ monkeypatch.setenv("UNSLOTH_S3_AUTO_INSTALL", "0")
+ monkeypatch.setattr(s3_runtime, "_import_sdk", lambda: None)
monkeypatch.setattr(s3_dataset, "boto3_available", lambda: False)
with pytest.raises(RuntimeError, match = "requires boto3"):
s3_dataset.download_s3_dataset(_cfg(), dest_dir = str(tmp_path))
diff --git a/studio/backend/tests/test_s3_optional.py b/studio/backend/tests/test_s3_optional.py
new file mode 100644
index 00000000000..65e0159dffa
--- /dev/null
+++ b/studio/backend/tests/test_s3_optional.py
@@ -0,0 +1,167 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""S3 is an opt-in dependency, including when the full API is imported."""
+
+import importlib.machinery
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import ModuleType
+from unittest.mock import Mock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+
+_AWS_MODULES = ("boto3", "botocore", "s3transfer", "jmespath")
+_INSTALL_COMMAND = 'python -m pip install "unsloth[s3]"'
+
+
+def without_aws(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_S3_AUTO_INSTALL", "0")
+ # None blocks imports even on a developer's machine with the SDK installed,
+ # and makes find_spec report the same absence as a default Studio install.
+ for name in _AWS_MODULES:
+ monkeypatch.setitem(sys.modules, name, None)
+
+
+def test_backend_and_training_routes_import_without_aws(tmp_path):
+ code = f"""
+import sys
+for name in {_AWS_MODULES!r}:
+ sys.modules[name] = None
+import main
+import routes.training
+assert '/api/train/start' in main.app.openapi()['paths']
+assert all(sys.modules[name] is None for name in {_AWS_MODULES!r})
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ cwd = Path(__file__).resolve().parents[1],
+ env = {
+ **os.environ,
+ "UNSLOTH_STUDIO_HOME": str(tmp_path),
+ "UNSLOTH_STUDIO_DISABLE_TORCH_WARM": "1",
+ },
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_local_dataset_loading_without_aws(without_aws, tmp_path):
+ from utils.datasets.cache_safe import load_dataset_cache_safe
+ from utils.datasets.raw_text import prepare_raw_text_dataset
+
+ source = tmp_path / "train.jsonl"
+ source.write_text('{"text": "hello"}\n{"text": "world"}\n', encoding = "utf-8")
+ dataset = load_dataset_cache_safe(
+ "json", data_files = str(source), split = "train", cache_dir = str(tmp_path / "cache")
+ )
+ prepared = prepare_raw_text_dataset(dataset, eos_token = "<eos>", append_eos = True)
+ assert list(prepared.dataset["text"]) == ["hello<eos>", "world<eos>"]
+ assert all(sys.modules[name] is None for name in _AWS_MODULES)
+
+
+def test_s3_request_without_aws_returns_actionable_501(without_aws, monkeypatch):
+ from routes import training
+ from core.training import token_preview
+
+ backend = Mock()
+ monkeypatch.setattr(training, "get_training_backend", lambda: backend)
+ monkeypatch.setattr(token_preview, "stop_token_preview_worker", lambda: None)
+ app = FastAPI()
+ app.include_router(training.router, prefix = "/api/train")
+ app.dependency_overrides[training.get_current_subject] = lambda: "test-user"
+ app.dependency_overrides[training.authenticated_via_api_key] = lambda: False
+ with TestClient(app) as client:
+ response = client.post(
+ "/api/train/start",
+ json = {
+ "model_name": "unsloth/test",
+ "training_type": "LoRA/QLoRA",
+ "format_type": "alpaca",
+ "s3_config": {"bucket": "test-bucket", "use_iam_role": True},
+ },
+ )
+ assert response.status_code == 501
+ assert _INSTALL_COMMAND in response.json()["detail"]
+ backend.start_training.assert_not_called()
+
+
+def test_s3_download_uses_optional_sdk(monkeypatch, tmp_path):
+ from core.training import s3_dataset
+
+ def download(bucket, key, filename, **kwargs):
+ assert bucket == "test-bucket"
+ assert key == "train.jsonl"
+ Path(filename).write_text('{"text": "hello"}\n', encoding = "utf-8")
+
+ client = Mock()
+ client.get_paginator.return_value.paginate.return_value = [
+ {"Contents": [{"Key": "train.jsonl"}]}
+ ]
+ client.download_file.side_effect = download
+ sdk = ModuleType("boto3")
+ sdk.__spec__ = importlib.machinery.ModuleSpec("boto3", loader = None)
+ sdk.client = Mock(return_value = client)
+ monkeypatch.setitem(sys.modules, "boto3", sdk)
+
+ files = s3_dataset.download_s3_dataset(
+ {
+ "bucket": "test-bucket",
+ "region": "us-west-2",
+ "access_key_id": "test-key",
+ "secret_access_key": "test-secret",
+ },
+ dest_dir = str(tmp_path),
+ )
+ assert len(files) == 1
+ assert Path(files[0]).read_text(encoding = "utf-8") == '{"text": "hello"}\n'
+ sdk.client.assert_called_once_with(
+ "s3",
+ region_name = "us-west-2",
+ aws_access_key_id = "test-key",
+ aws_secret_access_key = "test-secret",
+ )
+
+
[email protected]("s3_requested", [False, True])
+def test_training_installs_sdk_only_for_s3_then_continues(monkeypatch, s3_requested):
+ import asyncio
+ from routes import training
+ from core.training import s3_dataset, token_preview
+ from utils import s3_runtime
+
+ installed = []
+
+ def install():
+ # The installer must run off the async route's event loop.
+ with pytest.raises(RuntimeError, match = "no running event loop"):
+ asyncio.get_running_loop()
+ installed.append(True)
+
+ backend = Mock()
+ backend.is_training_active.return_value = True
+ backend.current_job_id = "existing-job"
+ monkeypatch.setattr(training, "get_training_backend", lambda: backend)
+ monkeypatch.setattr(token_preview, "stop_token_preview_worker", lambda: None)
+ monkeypatch.setattr(s3_dataset, "boto3_available", lambda: False)
+ monkeypatch.setattr(s3_runtime, "ensure_boto3", install)
+ app = FastAPI()
+ app.include_router(training.router, prefix = "/api/train")
+ app.dependency_overrides[training.get_current_subject] = lambda: "test-user"
+ app.dependency_overrides[training.authenticated_via_api_key] = lambda: False
+ payload = {"model_name": "unsloth/test", "training_type": "LoRA/QLoRA", "format_type": "alpaca"}
+ if s3_requested:
+ payload["s3_config"] = {"bucket": "test-bucket", "use_iam_role": True}
+ with TestClient(app) as client:
+ response = client.post("/api/train/start", json = payload)
+ assert response.status_code == 200
+ assert response.json()["message"].startswith("Training is already in progress")
+ assert installed == ([True] if s3_requested else [])
diff --git a/studio/backend/tests/test_s3_runtime.py b/studio/backend/tests/test_s3_runtime.py
new file mode 100644
index 00000000000..fb851c9af82
--- /dev/null
+++ b/studio/backend/tests/test_s3_runtime.py
@@ -0,0 +1,152 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""First-use S3 installation never contacts a package index in unit tests."""
+
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+from utils import s3_runtime as runtime
+
+
+def missing_sdk(monkeypatch, tmp_path):
+ state = {"sdk": None, "calls": []}
+ monkeypatch.setattr(runtime, "_import_sdk", lambda: state["sdk"])
+ monkeypatch.setattr(runtime.sys, "prefix", str(tmp_path))
+ monkeypatch.setattr(runtime, "hf_env_offline", lambda: False)
+ monkeypatch.setenv("UNSLOTH_S3_AUTO_INSTALL", "1")
+ monkeypatch.delenv("UV_OFFLINE", raising = False)
+ monkeypatch.delenv("UV_NO_INDEX", raising = False)
+ monkeypatch.delenv("PIP_NO_INDEX", raising = False)
+ monkeypatch.setattr(
+ runtime,
+ "distributions",
+ lambda: [SimpleNamespace(metadata = {"Name": "urllib3"}, version = "2.5.0")],
+ )
+
+ def install(command, **kwargs):
+ state["calls"].append((command, kwargs))
+ constraints = Path(command[command.index("--constraint") + 1]).read_text()
+ assert constraints == "urllib3==2.5.0\n"
+ state["sdk"] = SimpleNamespace(__version__ = "test")
+
+ monkeypatch.setattr(runtime.subprocess, "run", install)
+ return state
+
+
+def test_installed_sdk_is_reused_even_offline_and_disabled(missing_sdk, monkeypatch):
+ missing_sdk["sdk"] = object()
+ monkeypatch.setenv("UNSLOTH_S3_AUTO_INSTALL", "0")
+ monkeypatch.setattr(runtime, "hf_env_offline", lambda: True)
+ assert runtime.ensure_boto3() is missing_sdk["sdk"]
+ assert not missing_sdk["calls"]
+
+
[email protected]("installer", ["uv", "pip"])
+def test_install_targets_this_python_and_serializes_threads(missing_sdk, monkeypatch, installer):
+ monkeypatch.setattr(runtime, "_find_uv", lambda: "/tools/uv" if installer == "uv" else None)
+ with ThreadPoolExecutor(max_workers = 4) as pool:
+ results = list(pool.map(lambda _: runtime.ensure_boto3(), range(4)))
+ assert all(result is missing_sdk["sdk"] for result in results)
+ assert len(missing_sdk["calls"]) == 1
+ command, kwargs = missing_sdk["calls"][0]
+ assert command[-1] == "boto3>=1.34.0"
+ assert command[command.index("--only-binary") + 1] == ":all:"
+ if installer == "uv":
+ assert command[0] == "/tools/uv"
+ assert command[command.index("--python") + 1] == runtime.sys.executable
+ assert "--no-config" in command
+ else:
+ assert command[:4] == [runtime.sys.executable, "-m", "pip", "install"]
+ assert kwargs["check"] is True
+ assert 0 < kwargs["timeout"] <= 40
+
+
+def test_installer_does_not_receive_credentials_or_resolver_overrides(missing_sdk, monkeypatch):
+ for name in (
+ "AWS_SECRET_ACCESS_KEY",
+ "HF_TOKEN",
+ "UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET",
+ "UV_OVERRIDE",
+ "PIP_TARGET",
+ "PYTHONPATH",
+ ):
+ monkeypatch.setenv(name, "must-not-reach-child")
+ monkeypatch.setenv("HTTPS_PROXY", "https://proxy.example")
+ runtime.ensure_boto3()
+ env = missing_sdk["calls"][0][1]["env"]
+ assert "must-not-reach-child" not in env.values()
+ assert env["HTTPS_PROXY"] == "https://proxy.example"
+
+
+ "mode", ["disabled", "offline", "UV_OFFLINE", "UV_NO_INDEX", "PIP_NO_INDEX"]
+)
+def test_disabled_and_offline_install_never_runs(missing_sdk, monkeypatch, mode):
+ if mode == "disabled":
+ monkeypatch.setenv("UNSLOTH_S3_AUTO_INSTALL", "0")
+ elif mode == "offline":
+ monkeypatch.setattr(runtime, "hf_env_offline", lambda: True)
+ else:
+ monkeypatch.setenv(mode, "1")
+ with pytest.raises(runtime.S3DependencyUnavailable, match = r"unsloth\[s3\]"):
+ runtime.ensure_boto3()
+ assert not missing_sdk["calls"]
+
+
[email protected]("failure", ["resolver", "timeout", "missing-after-install"])
+def test_failed_install_preserves_guidance_without_exposing_output(
+ missing_sdk, monkeypatch, failure
+):
+ def fail(*args, **kwargs):
+ if failure == "resolver":
+ raise subprocess.CalledProcessError(1, "pip", stderr = "secret-proxy-password")
+ if failure == "timeout":
+ raise subprocess.TimeoutExpired("pip", 120)
+
+ monkeypatch.setattr(runtime.subprocess, "run", fail)
+ with pytest.raises(runtime.S3DependencyUnavailable) as caught:
+ runtime.ensure_boto3()
+ assert runtime.INSTALL_COMMAND in str(caught.value)
+ assert "secret-proxy-password" not in str(caught.value)
+
+
+def test_broken_installed_sdk_is_not_reinstalled(monkeypatch):
+ def broken(name):
+ raise ModuleNotFoundError("missing botocore", name = "botocore")
+
+ monkeypatch.setattr(runtime.importlib, "import_module", broken)
+ with pytest.raises(runtime.S3DependencyUnavailable, match = r"unsloth\[s3\]"):
+ runtime.ensure_boto3()
+
+
[email protected]("elapsed", [25, 41])
+def test_lock_wait_counts_against_install_timeout(missing_sdk, monkeypatch, elapsed):
+ clock = iter((100, 100 + elapsed))
+ monkeypatch.setattr(runtime, "time", SimpleNamespace(monotonic = lambda: next(clock)))
+ if elapsed > 40:
+ with pytest.raises(runtime.S3DependencyUnavailable):
+ runtime.ensure_boto3()
+ assert not missing_sdk["calls"]
+ else:
+ runtime.ensure_boto3()
+ assert missing_sdk["calls"][0][1]["timeout"] == 15
+
+
[email protected]("name", ["uv", "uv.exe"])
+def test_uv_is_found_off_path(monkeypatch, tmp_path, name):
+ from utils import mlx_repair
+
+ uv = tmp_path / ".local" / "bin" / name
+ uv.parent.mkdir(parents = True)
+ uv.write_text("")
+ uv.chmod(0o755)
+ monkeypatch.setattr(mlx_repair, "_UV_NAME", name)
+ monkeypatch.setattr(mlx_repair.shutil, "which", lambda name: None)
+ monkeypatch.setattr(mlx_repair.Path, "home", lambda: tmp_path)
+ assert runtime._find_uv() == str(uv)
diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.py
index 50582508378..195bb9ff673 100644
--- a/studio/backend/utils/mlx_repair.py
+++ b/studio/backend/utils/mlx_repair.py
@@ -262,14 +262,17 @@ def mlx_repair_started() -> bool:
return _attempted
+_UV_NAME = "uv.exe" if os.name == "nt" else "uv"
+
+
def _uv_executable() -> str | None:
"""Find uv even when macOS GUI launchers start with a minimal PATH."""
found = shutil.which("uv")
if found:
return found
for candidate in (
- Path.home() / ".local" / "bin" / "uv",
- Path.home() / ".cargo" / "bin" / "uv",
+ Path.home() / ".local" / "bin" / _UV_NAME,
+ Path.home() / ".cargo" / "bin" / _UV_NAME,
Path("/opt/homebrew/bin/uv"),
Path("/usr/local/bin/uv"),
):
diff --git a/studio/backend/utils/s3_runtime.py b/studio/backend/utils/s3_runtime.py
new file mode 100644
index 00000000000..c2c57078717
--- /dev/null
+++ b/studio/backend/utils/s3_runtime.py
@@ -0,0 +1,176 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Install the optional S3 SDK when an S3 dataset is first requested."""
+
+import importlib
+from importlib.metadata import distributions
+import logging
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+from filelock import FileLock
+
+from utils.subprocess_compat import windows_hidden_subprocess_kwargs
+from utils.utils import hf_env_offline
+
+INSTALL_COMMAND = 'python -m pip install "unsloth[s3]"'
+# Studio venvs are created by uv without pip, so also name the uv spelling.
+S3_INSTALL_MESSAGE = (
+ "S3 dataset loading requires boto3. Install it in the Studio environment with: "
+ f'{INSTALL_COMMAND} (or: uv pip install --python "{sys.executable}" "unsloth[s3]")'
+)
+logger = logging.getLogger(__name__)
+_INSTALL_ENV_KEYS = {
+ "PATH",
+ "HOME",
+ "USERPROFILE",
+ "SYSTEMROOT",
+ "SystemRoot",
+ "WINDIR",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "SSL_CERT_FILE",
+ "SSL_CERT_DIR",
+ "REQUESTS_CA_BUNDLE",
+ "CURL_CA_BUNDLE",
+ "HTTPS_PROXY",
+ "HTTP_PROXY",
+ "ALL_PROXY",
+ "NO_PROXY",
+ "https_proxy",
+ "http_proxy",
+ "all_proxy",
+ "no_proxy",
+ "PIP_CERT",
+ "PIP_CLIENT_CERT",
+ "PIP_PROXY",
+ "UV_NATIVE_TLS",
+ "UV_SYSTEM_CERTS",
+ "UV_CACHE_DIR",
+}
+
+
+class S3DependencyUnavailable(RuntimeError):
+ """The SDK could not be installed or imported; includes manual guidance."""
+
+
+def _find_uv():
+ # Desktop GUI launches can start with a minimal PATH, and the pip fallback needs a pip the venv lacks.
+ try:
+ from utils.mlx_repair import _uv_executable
+ return _uv_executable()
+ except Exception: # noqa: BLE001
+ return shutil.which("uv")
+
+
+def _import_sdk():
+ try:
+ return importlib.import_module("boto3")
+ except ModuleNotFoundError as exc:
+ if exc.name == "boto3":
+ return None
+ raise S3DependencyUnavailable(S3_INSTALL_MESSAGE) from exc
+ except ImportError as exc:
+ raise S3DependencyUnavailable(S3_INSTALL_MESSAGE) from exc
+
+
+def ensure_boto3():
+ """Reuse an installed SDK, or install it without upgrading shared packages.
+
+ Call from a worker thread when used by an async route. The installer runs in
+ a subprocess targeting this interpreter; importing the result stays in-process.
+ """
+ sdk = _import_sdk()
+ if sdk is not None:
+ return sdk
+ if os.environ.get("UNSLOTH_S3_AUTO_INSTALL", "1").strip().lower() in {
+ "0",
+ "false",
+ "no",
+ "off",
+ }:
+ raise S3DependencyUnavailable(
+ f"Automatic S3 installation is disabled. {S3_INSTALL_MESSAGE}"
+ )
+ if hf_env_offline() or any(
+ os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"}
+ for name in ("UV_OFFLINE", "UV_NO_INDEX", "PIP_NO_INDEX")
+ ):
+ raise S3DependencyUnavailable(
+ f"S3 SDK is not installed and offline mode is enabled. {S3_INSTALL_MESSAGE}"
+ )
+ try:
+ # Includes lock contention: the UI's training-start request times out at 60 s.
+ deadline = time.monotonic() + 40
+ with FileLock(str(Path(sys.prefix) / ".unsloth-s3-install.lock"), timeout = 40):
+ importlib.invalidate_caches()
+ sdk = _import_sdk()
+ if sdk is not None:
+ return sdk
+ logger.info("Installing optional S3 support on first use")
+ with tempfile.TemporaryDirectory(prefix = "unsloth-s3-") as staging:
+ constraints = Path(staging) / "constraints.txt"
+ constraints.write_text(
+ "".join(
+ f"{dist.metadata['Name']}=={dist.version}\n" for dist in distributions()
+ ),
+ encoding = "utf-8",
+ )
+ uv = _find_uv()
+ command = (
+ [uv, "pip", "install", "--python", sys.executable, "--no-config"]
+ if uv
+ else [
+ sys.executable,
+ "-m",
+ "pip",
+ "install",
+ "--disable-pip-version-check",
+ "--no-user",
+ ]
+ )
+ command += [
+ "--only-binary",
+ ":all:",
+ "--constraint",
+ str(constraints),
+ "--index-url",
+ "https://pypi.org/simple",
+ "boto3>=1.34.0",
+ ]
+ # Installer children need TLS/proxy settings, not AWS/HF credentials
+ # or package-source/target overrides from the running Studio process.
+ env = {key: value for key, value in os.environ.items() if key in _INSTALL_ENV_KEYS}
+ env["PIP_CONFIG_FILE"] = os.devnull
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError("S3 installation wait exceeded its time budget")
+ subprocess.run(
+ command,
+ check = True,
+ capture_output = True,
+ timeout = remaining,
+ env = env,
+ **windows_hidden_subprocess_kwargs(),
+ )
+ importlib.invalidate_caches()
+ sdk = _import_sdk()
+ if sdk is None:
+ raise S3DependencyUnavailable(S3_INSTALL_MESSAGE)
+ return sdk
+ except S3DependencyUnavailable:
+ raise
+ except Exception as exc:
+ # Installer output can contain proxy credentials; expose only our guidance.
+ raise S3DependencyUnavailable(
+ f"Automatic S3 installation failed. {S3_INSTALL_MESSAGE}"
+ ) from exc
diff --git a/tests/studio/install/test_studio_extra_matches_requirements.py b/tests/studio/install/test_studio_extra_matches_requirements.py
index e0d72546461..0e47238c773 100644
--- a/tests/studio/install/test_studio_extra_matches_requirements.py
+++ b/tests/studio/install/test_studio_extra_matches_requirements.py
@@ -53,6 +53,21 @@ def test_studio_extra_exists():
)
+def test_s3_sdk_is_only_in_the_s3_extra():
+ from packaging.requirements import Requirement
+
+ project = _load_pyproject()["project"]
+ extras = project["optional-dependencies"]
+ assert extras["s3"] == ["boto3>=1.34.0"]
+ aws_packages = {"boto3", "botocore", "s3transfer", "jmespath"}
+ default_requirements = (
+ project["dependencies"] + extras["studio"] + _requirement_lines(STUDIO_TXT)
+ )
+ assert not aws_packages.intersection(
+ Requirement(entry).name.lower() for entry in default_requirements
+ )
+
+
def test_huggingface_extra_contains_no_diffusers_vcs_reference():
from packaging.requirements import Requirement