mirror of
https://github.com/unslothai/unsloth.git
synced 2026-08-23 15:53:46 +00:00
* fix(studio): harden training setup and model loading Scan every model load root before approving remote code, and pin third-party codec sources to verified revisions. Align dataset option validation across the UI and backend, preserve manual drafts, and include edits in training start identity. Require job-scoped stop requests and retain bounded early-cancel tombstones without unsafe eviction. * fix(studio): harden training lifecycle and audio loading Preserve early start cancellations with bounded tombstones and explicit capacity handling for concurrent requests. Pin and verify third-party audio sources and codec artifacts with safe archive extraction and offline cache migration. Keep automatic evaluation data separate from every split included in a combined training instruction. Keep training summaries and GPU progress state aligned with the active configuration through public feature exports. Make route and lifecycle tests deterministic by isolating Hub reachability and executor behavior. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix(studio): correct completion masking and offline training Apply Alpaca response markers safely when completion-only training is enabled. Skip optional runtime dependency installs while Studio is offline. Limit causal-conv1d hooks to recognized model families without dropping supported architectures. Disable known-broken TileLang dispatch when offline repair is unavailable. Use cached GGUF and model-size metadata without offline Hub retries. * fix(studio): resolve causal conv kernels from model configs Detect causal-conv1d requirements from resolved model architectures before loading model code. Keep name matching as a fallback while excluding unrelated renamed checkpoints. * fix(studio): preserve registered training cancellation Allow registered start cancellations to reclaim the oldest expiring tombstone when unknown cancellation capacity is full. Preserve the hard capacity limit and 429 response for unregistered request IDs. * Fix reset job scoping, DAC fast path, scan target and subset splits for PR #8103 - /api/train/reset: an unscoped reset could force-terminate a run mid-cancel. The guard now refuses to touch a live run it cannot prove it owns. The field stays optional so pre-rework clients, which POST /reset with no body, keep working. - ensure_dac_speech_weights: install the download into the pinned destination, so later loads hit the fast path instead of re-downloading and re-hashing 295 MB under the install lock. - _requires_security_review_for_model: apply the same load_scan_target alias normalization the sibling remote-code check gained, else the Spark-TTS alias 404s and fails open to "no review needed". - _purge_package_bytecode: best effort. It runs without the install lock over a cache shared by the inference and training workers; 7 of 8 concurrent imports died on it. Also moved inside the try so a failure cannot strand the cache dir on sys.path, and snapshot sys.modules before the origin audit. - commitSubset: clear the backing splits too, else the render-phase draft sync reads the previous subset's split back into the boxes it just reset. - Fix two tests that fail on the branch: the DAC assertion pinned the old return value, and the causal-conv1d assertion matched call formatting. * Make the SSM runtime tests Windows aware ensure_ssm_runtime deliberately skips causal-conv1d on win32 (no prebuilt wheel), so the two install-order assertions only hold off Windows. Caught on a real windows-latest runner. * Update two frontend source contracts the branch moved - captureTrainingStartInputs now delegates to createTrainingStartInputIdentity, so the normalize/flags assertions belong against training-start-inputs.ts. - resetTraining takes a RequiredTrainingJobScope and always sends the body, which is stronger than the hasScope branch the contract pinned. Both fail on the branch today; caught by tests/studio, which the studio backend job does not cover. * Fix unscoped reset compat, pyc purge fail-open and DAC fallback for PR #8103 Corrects four things in my earlier commits on this branch. Unscoped /api/train/reset returned "superseded" (HTTP 200) for a live run. The pre-rework cancel dialog chains stopTrainingRun then a bodyless reset, so an older client read that 200 as success and cleared its UI while training kept running. Return "active" (409) instead: same answer a live run already gives, and one those clients already handle. It still never force-terminates, so a bodyless reset landing between current_job_id being set and _cancel_requested being cleared cannot kill the run that just started. The bytecode purge was made best-effort, but it is the only thing stopping a stale or planted .pyc shadowing a verified .py: the manifest skips __pycache__ and the origin audit reads __file__, which still names the .py. Tolerate only FileNotFoundError, the real concurrent-purge race, and let PermissionError fail the load again. The DAC fast path copies 295 MB inside the hub cache with only Timeout caught, so a full disk turned a hash-verified download into a hard failure. Fall back to the verified hub path on OSError. commitSubset cleared both splits, but setDatasetSubset already does that; the extra setDatasetSplit(null) only cost a runDatasetCheck against an assumed "train" split. * Restore the eval split reset and the cancelled-run dismiss for PR #8103 Two corrections to 4e5389c21. commitSubset: I removed setDatasetEvalSplit(null) because setDatasetSubset already nulls datasetEvalSplit. It does, but it never resets evalSteps, and setDatasetEvalSplit is not a plain setter: it zeroes evalSteps and runs streamingCompatiblePatch. Without it, changing the subset left evaluation armed with no split, which routes/training.py rejects with 422 once streaming is on, and which silently auto-detects an eval split otherwise. Restored. setDatasetSplit(null) stays out, since its only unique effect was a runDatasetCheck against an assumed "train". Unscoped reset: returning "active" for every live run was too broad. The pre-rework cancel dialog only dismisses after stopTrainingRun succeeded, so _cancel_requested is already set and clearing the UI is right; 409 there just wedged the overlay behind a "Training still active" toast. Now 409 only when no stop was requested, which is the stale-tab case the change was for. Still no force_terminate on an unscoped reset. Also covers the __pycache__ branch of the purge, which is the route a planted .pyc actually takes; the existing test only reached the top-level .pyc loop. * Keep live start cancellations and fall back on a full disk for PR #8103 Two fixes plus the regression tests the earlier lifecycle fixes shipped without. Cancelling the active start at tombstone capacity reclaimed a slot by deleting the soonest-expiring entry. Expired ones are already pruned a few lines above, so that entry was always live, and dropping it let a delayed /start spawn the job it had cancelled. Reserve capacity instead: only the owner of the active start reaches that branch and there is at most one, so the table lands at cap + 1 rather than forgetting a cancellation. Unregistered ids still hit the hard cap. ensure_dac_speech_weights migrated a pre-existing legacy file with an unguarded copy, so a hub cache that cannot absorb a second 295 MB copy failed weights that had already passed size and sha256. Same fallback the download branch below it already uses. Tests: renamed and local SSM checkpoints resolving from config rather than name, the owner of an active start staying cancellable at capacity, live cancellations surviving that cancel, and the full-disk legacy DAC fallback. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Opt the pinned source checkouts into Git long paths for PR #8103 Cross-OS CI caught 14 failures on windows-latest, all of them the pinned checkout dying with "error: unable to write file ...: Filename too long". Git for Windows still enforces MAX_PATH unless told otherwise, and the cache nests a 40-char revision, a staging dir and .git/objects under the studio home. A venv-inferred home already measures about 253 of the 260 characters, so a slightly longer user or install path fails on a normal Windows machine, not just under the deeper pytest tmp dir. Passed per invocation with -c so no user or system Git config is touched, and it is a no-op off Windows. * Bound pending cancels, reach legacy DAC weights, and delete read-only checkouts for PR #8103 Three fixes, two of them on my own previous commit. Moving the owner cancel from evict-oldest to a one-slot overshoot also changed what the hardcoded reclaim_capacity=True on the pending non-owner branch did: it used to evict, so the table stayed at the cap, and it started overshooting instead. Start plus cancel could then be repeated to grow it without bound (1224 entries against a cap of 1024). That branch now takes the plain reservation, so the extra slot belongs to the owner of the active run alone. The DAC legacy fallback sat behind destination.parent.mkdir() and the install lock, both of which need a writable cache, so a read-only or full hub cache raised before weights we can already verify were ever looked at. Fall back at both points, and only to an artifact that passes the same size and sha256 check. Cross-OS CI then caught replacing a pinned checkout failing on windows-latest with WinError 5: Git marks .git/objects read-only and Windows will not delete a read-only file, so any repair or revision change died there. Clear the attribute and retry, only when the path is genuinely not writable, so an open handle still surfaces. * Delete the cached checkout the Windows-safe way in the migration test for PR #8103 --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <moonshotaisubstack@gmail.com>
368 lines
15 KiB
Python
368 lines
15 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
|
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
|
|
|
"""Consent gate for loads that would execute model repo code.
|
|
|
|
The LOAD-path counterpart to the capability probes (which read raw config and
|
|
never need remote code). A deliberate load calls ``evaluate_remote_code_consent``
|
|
right before passing ``trust_remote_code=True``, and decides by the severity of a
|
|
static scan of the repo's ``auto_map`` ``.py``:
|
|
|
|
* No ``auto_map`` in any config (model/tokenizer/processor) -> nothing runs; allow.
|
|
* CRITICAL (reverse shell, IMDS, credential theft, droppers) -> hard block, never
|
|
approvable, even first-party (defends a compromised trusted repo).
|
|
* HIGH/MEDIUM (subprocess/exec/eval/network/b64decode, or a large embedded blob) ->
|
|
block but user-approvable: the dialog pins approval to the scanned ``fingerprint``.
|
|
Applies to EVERY repo; first-party is not a blanket bypass.
|
|
* ``auto_map`` present but unscannable (gated/offline/listing failure) -> fail
|
|
closed: hard block, since we cannot verify or fingerprint unseen code.
|
|
|
|
Hardening + consent, not a sandbox: static patterns are evadable, so subprocess /
|
|
venv isolation remains the containment layer.
|
|
"""
|
|
|
|
from dataclasses import dataclass, field
|
|
from typing import Optional
|
|
|
|
from loggers import get_logger
|
|
|
|
from utils.security.remote_code_scan import (
|
|
CRITICAL,
|
|
HIGH,
|
|
MEDIUM,
|
|
RemoteCodeUnscannable,
|
|
remote_code_config_paths,
|
|
remote_code_fingerprint,
|
|
repo_remote_code_files,
|
|
scan_remote_code_files,
|
|
)
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
@dataclass
|
|
class RemoteCodeDecision:
|
|
"""Outcome of the consent gate for one (model, trust_remote_code) load."""
|
|
|
|
model_name: str
|
|
has_remote_code: bool
|
|
blocked: bool
|
|
fingerprint: Optional[str]
|
|
max_severity: Optional[str]
|
|
findings_summary: str
|
|
reason: str
|
|
findings: list = field(default_factory = list) # structured [{severity,file,check,evidence}]
|
|
approvable: bool = True # False only for CRITICAL (user cannot override)
|
|
|
|
def response_payload(self) -> dict:
|
|
"""Machine-readable detail for the frontend. ``error_kind`` splits a
|
|
user-approvable prompt (``remote_code_consent_required``) from a CRITICAL hard
|
|
block (``remote_code_blocked``).
|
|
"""
|
|
return {
|
|
"error_kind": (
|
|
"remote_code_consent_required" if self.approvable else "remote_code_blocked"
|
|
),
|
|
"model_name": self.model_name,
|
|
"has_remote_code": self.has_remote_code,
|
|
"approvable": self.approvable,
|
|
"fingerprint": self.fingerprint,
|
|
"max_severity": self.max_severity,
|
|
"findings": self.findings,
|
|
"findings_summary": self.findings_summary,
|
|
"reason": self.reason,
|
|
}
|
|
|
|
|
|
def _config_has_auto_map(
|
|
model_name: str,
|
|
hf_token: Optional[str] = None,
|
|
*,
|
|
load_subdirs = (),
|
|
) -> Optional[bool]:
|
|
"""Whether any config (model/tokenizer/processor) declares an ``auto_map`` the load
|
|
would execute. Reads raw JSON with ``hf_token``; returns None when a config is
|
|
unreadable (transient/auth) so the caller treats it as "unknown" and scans, False
|
|
when the repo genuinely ships none.
|
|
|
|
GGUF-inertness is the LOADER's property, decided upstream by the caller's ``is_gguf``
|
|
check, not here. Every path that reaches this helper (export, training, non-GGUF
|
|
inference) loads via ``from_pretrained``, which imports ``auto_map`` even for a
|
|
``.gguf``-only repo, so a GGUF-classified repo id MUST still be scanned. Only a direct
|
|
``.gguf`` FILE reference is inert (a genuine single-file llama.cpp load).
|
|
"""
|
|
# A direct .gguf FILE loads via llama.cpp (auto_map inert); a bare repo id ending in .gguf can
|
|
# still ship safetensors + auto_map, so it falls through to the scan.
|
|
if _is_direct_gguf_file_ref(model_name):
|
|
return False
|
|
configs = _load_remote_code_configs(model_name, hf_token, load_subdirs = load_subdirs)
|
|
if configs is None:
|
|
return None
|
|
if not any(bool((cfg or {}).get("auto_map")) for cfg in configs):
|
|
return False
|
|
return True
|
|
|
|
|
|
def _is_direct_gguf_file_ref(model_name: str) -> bool:
|
|
"""Whether ``model_name`` names a specific ``.gguf`` FILE (llama.cpp), not a repo:
|
|
a local ``.gguf`` path or a remote ``org/repo/.../file.gguf`` (>= 2 slashes). A bare
|
|
``org/name.gguf`` is a repo id that can still ship safetensors + auto_map, so it
|
|
falls through to the scan.
|
|
"""
|
|
name = model_name or ""
|
|
if not name.lower().endswith(".gguf"):
|
|
return False
|
|
try:
|
|
from utils.paths import is_local_path
|
|
if is_local_path(name):
|
|
return True
|
|
except Exception:
|
|
pass
|
|
# Remote: a file reference is repo_id ("org/name") + filename => >= 2 slashes.
|
|
return name.count("/") >= 2
|
|
|
|
|
|
def _load_remote_code_configs(
|
|
model_name: str,
|
|
hf_token: Optional[str] = None,
|
|
*,
|
|
load_subdirs = (),
|
|
) -> Optional[list]:
|
|
"""Read every config that can declare ``auto_map`` (model/tokenizer/processor) as
|
|
raw dicts. Returns the configs present (``[]`` when all 404, a definitive "no
|
|
auto_map"), or None when one is unreadable (transient/auth) so the caller scans.
|
|
The 404-vs-error split matters: real absence is "allow"; unreadable is "unknown".
|
|
"""
|
|
import json
|
|
from pathlib import Path
|
|
|
|
try:
|
|
from utils.paths import is_local_path, normalize_path
|
|
|
|
if is_local_path(model_name):
|
|
root = Path(normalize_path(model_name)).expanduser()
|
|
configs = []
|
|
for name in remote_code_config_paths(load_subdirs):
|
|
p = root.joinpath(*Path(name).parts)
|
|
if p.is_file():
|
|
configs.append(json.loads(p.read_text(encoding = "utf-8-sig")))
|
|
return configs
|
|
|
|
from huggingface_hub import hf_hub_download
|
|
from huggingface_hub.utils import EntryNotFoundError
|
|
from utils.hf_cache_settings import active_hf_hub_cache
|
|
|
|
configs = []
|
|
for name in remote_code_config_paths(load_subdirs):
|
|
try:
|
|
p = hf_hub_download(
|
|
repo_id = model_name,
|
|
filename = name,
|
|
token = hf_token,
|
|
cache_dir = active_hf_hub_cache(),
|
|
)
|
|
except EntryNotFoundError:
|
|
continue # genuine 404 -> truly absent
|
|
except Exception:
|
|
# Transient/auth failure is not "absent" -> fail closed to "unknown" so the caller scans.
|
|
return None
|
|
configs.append(json.loads(Path(p).read_text(encoding = "utf-8-sig")))
|
|
# Every config was read or a genuine 404 -> an empty list is a definitive "no auto_map".
|
|
return configs
|
|
except Exception as exc:
|
|
logger.debug("auto_map check could not read config for %s: %s", model_name, exc)
|
|
return None
|
|
|
|
|
|
def evaluate_remote_code_consent(
|
|
model_name: str,
|
|
hf_token: Optional[str] = None,
|
|
*,
|
|
trust_remote_code: bool,
|
|
approved_fingerprint: Optional[str] = None,
|
|
trusted_org: Optional[bool] = None,
|
|
subject: Optional[str] = None,
|
|
) -> RemoteCodeDecision:
|
|
"""Single-repo consent; thin wrapper over the for_targets form. ``trusted_org`` is
|
|
accepted for backward compatibility but no longer changes the decision.
|
|
"""
|
|
return evaluate_remote_code_consent_for_targets(
|
|
[model_name],
|
|
hf_token,
|
|
trust_remote_code = trust_remote_code,
|
|
approved_fingerprint = approved_fingerprint,
|
|
subject = subject,
|
|
)
|
|
|
|
|
|
def _fingerprint_target_key(target: str) -> str:
|
|
"""Canonical namespace key for a target in the combined fingerprint."""
|
|
try:
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from utils.paths import is_local_path, normalize_path
|
|
|
|
if is_local_path(target):
|
|
path = Path(normalize_path(target)).expanduser().resolve(strict = False)
|
|
return os.path.normcase(str(path))
|
|
except Exception:
|
|
return target
|
|
return target.lower()
|
|
|
|
|
|
def evaluate_remote_code_consent_for_targets(
|
|
targets,
|
|
hf_token: Optional[str] = None,
|
|
*,
|
|
trust_remote_code: bool,
|
|
approved_fingerprint: Optional[str] = None,
|
|
subject: Optional[str] = None,
|
|
load_subdirs_by_target = None,
|
|
) -> RemoteCodeDecision:
|
|
"""Decide whether a ``trust_remote_code=True`` load may proceed, over every repo whose
|
|
code the load would execute. A LoRA load runs adapter AND base code, so all targets
|
|
are scanned as ONE unit and pinned by ONE fingerprint over the union of their ``.py``
|
|
-- one approval covers every repo, and a base-only fingerprint can't leave an
|
|
adapter's own ``auto_map`` unreviewed. On ``blocked``, the caller surfaces
|
|
``response_payload()`` and retries with ``approved_fingerprint`` if the user accepts.
|
|
|
|
When ``subject`` is given, a prior approval by that user can skip the DIALOG (never the
|
|
scan): the stored fingerprint seeds the authoritative content check below, so an
|
|
unchanged repo auto-approves while any change re-prompts. A genuine approval is
|
|
recorded for next time.
|
|
"""
|
|
targets = [t for t in dict.fromkeys(targets) if t]
|
|
primary = targets[0] if targets else ""
|
|
|
|
if not trust_remote_code:
|
|
return RemoteCodeDecision(
|
|
primary, False, False, None, None, "", "trust_remote_code disabled"
|
|
)
|
|
|
|
# Persistent per-user approval: seed the stored fingerprint so the authoritative scan below
|
|
# auto-approves an unchanged repo (skips only the prompt, never the scan). Gated so it cannot
|
|
# weaken the scan: the approval must match the current ruleset, and a resolvable commit SHA must
|
|
# match the approved revision. The fingerprint and the CRITICAL block still apply.
|
|
caller_approved_fingerprint = approved_fingerprint
|
|
if subject:
|
|
from utils.security import remote_code_approvals
|
|
|
|
_ak = remote_code_approvals.approval_target_key(targets)
|
|
_stored = remote_code_approvals.lookup(subject, _ak)
|
|
if _stored is not None and _stored.scanner_version == remote_code_approvals.SCANNER_VERSION:
|
|
_sha = remote_code_approvals.resolve_combined_sha(targets, hf_token)
|
|
if _sha is None or _sha == _stored.commit_sha:
|
|
approved_fingerprint = approved_fingerprint or _stored.fingerprint
|
|
|
|
# Gather executable .py from every target that ships auto_map. A definitively auto_map-free
|
|
# target contributes nothing; an unreadable config is scanned anyway. If ANY target's code is
|
|
# present but unscannable, fail the whole load closed.
|
|
combined: dict = {}
|
|
has_remote_code = False
|
|
load_subdirs_by_target = load_subdirs_by_target or {}
|
|
for target in targets:
|
|
load_subdirs = tuple(load_subdirs_by_target.get(target, ()))
|
|
scan_kwargs = {"load_subdirs": load_subdirs} if load_subdirs else {}
|
|
if _config_has_auto_map(target, hf_token, **scan_kwargs) is False:
|
|
continue
|
|
has_remote_code = True
|
|
try:
|
|
files = repo_remote_code_files(target, hf_token = hf_token, **scan_kwargs)
|
|
except RemoteCodeUnscannable:
|
|
logger.warning(
|
|
"Blocking trust_remote_code load of '%s': remote code present (auto_map) "
|
|
"but could not be downloaded and scanned.",
|
|
target,
|
|
)
|
|
return RemoteCodeDecision(
|
|
target,
|
|
True,
|
|
True,
|
|
None,
|
|
None,
|
|
"Remote code is present (auto_map) but could not be downloaded and "
|
|
"scanned. Retry when the repo is reachable and the correct Hugging Face "
|
|
"token is set.",
|
|
"blocked: remote code could not be scanned",
|
|
approvable = False,
|
|
)
|
|
# Namespace filenames by (casing-normalized) target so two repos' same-named files stay distinct.
|
|
target_key = _fingerprint_target_key(target)
|
|
for filename, body in files.items():
|
|
combined[f"{target_key}\0{filename}"] = body
|
|
|
|
if not has_remote_code:
|
|
return RemoteCodeDecision(
|
|
primary, False, False, None, None, "", "no auto_map; trust_remote_code is a no-op"
|
|
)
|
|
|
|
if not combined:
|
|
# auto_map declared but no executable .py (e.g. GGUF repo) -> nothing to scan -> allow.
|
|
return RemoteCodeDecision(
|
|
primary,
|
|
False,
|
|
False,
|
|
None,
|
|
None,
|
|
"",
|
|
"auto_map declared but no executable code present; trust_remote_code is a no-op",
|
|
)
|
|
|
|
result = scan_remote_code_files(combined)
|
|
fingerprint = remote_code_fingerprint(combined)
|
|
sev = result.max_severity
|
|
|
|
# CRITICAL is never approvable; a fingerprint pins approval for lower severities only.
|
|
approvable = sev != CRITICAL
|
|
approved = (
|
|
approvable and approved_fingerprint is not None and approved_fingerprint == fingerprint
|
|
)
|
|
|
|
if sev == CRITICAL:
|
|
blocked, reason = True, "blocked: scan found CRITICAL patterns"
|
|
elif approved:
|
|
blocked, reason = False, "approved by fingerprint"
|
|
elif sev == HIGH:
|
|
# HIGH is user-approvable but must pin the fingerprint via the dialog, for every repo including
|
|
# first-party (a compromised trusted repo still needs review).
|
|
blocked, reason = True, "blocked: scan found HIGH patterns; approval required"
|
|
elif sev == MEDIUM:
|
|
# MEDIUM (e.g. a big embedded base64 blob) also pins approval like HIGH, so a direct API caller
|
|
# can't run flagged code by just setting trust_remote_code=True.
|
|
blocked, reason = True, "blocked: scan found MEDIUM patterns; approval required"
|
|
else:
|
|
blocked, reason = False, "allowed: no high-risk patterns"
|
|
|
|
if blocked:
|
|
logger.warning(
|
|
"Blocking trust_remote_code load of '%s': scan severity %s (fingerprint %s)",
|
|
primary,
|
|
sev,
|
|
fingerprint[:12],
|
|
)
|
|
|
|
# Persist a genuine user approval (a matching fingerprint from the caller, not a cache seed)
|
|
# under the current scanner version, so the repo is not re-prompted until code or ruleset changes.
|
|
if approved and subject and caller_approved_fingerprint == fingerprint:
|
|
from utils.security import remote_code_approvals
|
|
remote_code_approvals.record(
|
|
subject,
|
|
remote_code_approvals.approval_target_key(targets),
|
|
commit_sha = remote_code_approvals.resolve_combined_sha(targets, hf_token),
|
|
fingerprint = fingerprint,
|
|
max_severity = sev,
|
|
scanner_version = remote_code_approvals.SCANNER_VERSION,
|
|
)
|
|
|
|
return RemoteCodeDecision(
|
|
primary,
|
|
True,
|
|
blocked,
|
|
fingerprint,
|
|
sev,
|
|
result.summary(),
|
|
reason,
|
|
findings = result.findings_payload(),
|
|
approvable = approvable,
|
|
)
|