Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Changing any of the following files or symbols constitutes a change to the uploa
- `src/modelscope_hub/errors.py`: `raise_for_status`, `_COMMIT_RETRYABLE_BUSINESS_CODES`, and HTTP/business-code mappings
- `src/modelscope_hub/_legacy_api.py`: `create_commit`, including the HTTP 200 / `Success:false` check
- `src/modelscope_hub/constants.py`: upload-related constants such as `UPLOAD_*` and `COMMIT_MAX_ACTIONS_PER_REQUEST`
- Resumable multipart (opt-in, `MODELSCOPE_UPLOAD_MULTIPART_MODE`): `src/modelscope_hub/_multipart_*.py` (config, control, protocol, source, state, upload), `src/modelscope_hub/_aigc_weights.py` (LoRA weight pre-upload), and `src/modelscope_hub/utils/_sha256_state.py` (SHA256 prefix engine). Their invariants: status-first and initialize only on `UPLOAD_NOT_FOUND`; send only pending or dirty parts; `complete` once; a source that changes mid-run fails with `E2020` and sends no part; a `completed` response whose identity differs from the declared sha256/size is never success; the href origin must be the endpoint origin or an exact `MODELSCOPE_UPLOAD_MULTIPART_TRUSTED_ORIGINS` entry; the AIGC compat path (`compat/hub_api.py::_preupload_aigc_weights`) verifies the local file against `weight_sha256` / `weight_size` before any request and keeps the legacy single-stream pre-upload when the mode is `off`.

---

Expand Down Expand Up @@ -92,6 +93,7 @@ The following behavior must also be preserved:
| D3 | 5 GB / 2 thousand files | Commit-batch count and tail behavior (including whether rebalancing applies), blob-dominated cost |
| D4 | 200 GB / 10 files | All LFS, **one commit**, blob-transfer dominated, no capacity warning |
| DX | 1,000 files × 1 GB | All LFS, the 8 MiB budget does not apply, commit batches (`256×3+232=4`), approximately 1,000 PUTs |
| D-Multipart | 1 file × 1 GiB, `MODELSCOPE_UPLOAD_MULTIPART_MODE=required` | One LFS blob, one commit; the server plan (8 MiB parts on pre) yields 128 part PUTs, at least 2 status requests and exactly 1 complete; no ordinary blob PUT; blob-transfer dominated, no capacity warning |

For every scenario, derive at least: the LFS/normal routing result, the `_calculate_adaptive_batch_size` target, `_plan_commit_batches` count plus operations and estimated body size per batch, blob PUT count, presign request count, advisory warnings triggered, and resume behavior.

Expand Down Expand Up @@ -125,7 +127,7 @@ For each error below, describe its classification, whether it is automatically r

### 5.4 Required Automated Validation (Run in Parallel with the Simulation)

- `PYTHONPATH=src pytest -q tests/test_upload_batching.py tests/test_commit_action_limit.py tests/test_errors_openapi_codes.py tests/test_upload_config.py tests/test_upload_lfs_gate.py tests/test_upload_blob_dedup.py`
- `PYTHONPATH=src pytest -q tests/test_upload_batching.py tests/test_commit_action_limit.py tests/test_errors_openapi_codes.py tests/test_upload_config.py tests/test_upload_lfs_gate.py tests/test_upload_blob_dedup.py tests/test_multipart_hash_recovery.py tests/test_sha256_prefix.py tests/test_aigc_weights_multipart.py`
- If error mappings changed, additionally run `tests/test_login_failure_paths.py`.
- The full non-remote suite, ruff, and mypy must pass.

Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,27 @@ Token is persisted locally after `ms-hub login` and auto-loaded in subsequent se
| `MODELSCOPE_UPLOAD_COMMIT_MAX_ATTEMPTS` | `5` | Maximum attempts for one transient commit failure |
| `MODELSCOPE_UPLOAD_BLOB_CONNECT_TIMEOUT_SECONDS` | `30` | Blob upload connect timeout (seconds) |
| `MODELSCOPE_UPLOAD_BLOB_READ_TIMEOUT_SECONDS` | `3600` | Blob upload read timeout (seconds) |
| `MODELSCOPE_UPLOAD_MULTIPART_MODE` | `off` | Resumable multipart mode: `off`, `auto`, or `required` |
| `MODELSCOPE_UPLOAD_MULTIPART_THRESHOLD` | `64MiB` | Minimum eligible LFS source size for multipart upload |
| `MODELSCOPE_UPLOAD_MULTIPART_PART_SIZE` | `0` | Requested part size; `0` uses the server plan |
| `MODELSCOPE_UPLOAD_MULTIPART_TRUSTED_ORIGINS` | — | Comma-separated additional exact HTTPS Mirror origins |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_CONCURRENT_REQUESTS` | `8` | Total multipart and ordinary blob request slots per enabled call |
| `MODELSCOPE_UPLOAD_MULTIPART_PART_WORKERS` | `4` | Maximum concurrent part requests per blob |
| `MODELSCOPE_UPLOAD_MULTIPART_HASH_WORKERS` | `2` | Maximum concurrent multipart source scanners |
| `MODELSCOPE_UPLOAD_MULTIPART_IO_CHUNK_SIZE` | `1MiB` | Multipart source reader and scanner buffer size |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_RESPONSE_BYTES` | `4MiB` | Maximum buffered multipart JSON response size |
| `MODELSCOPE_UPLOAD_MULTIPART_LOCK_TIMEOUT_SECONDS` | `600` | Maximum local multipart state-lock wait (seconds) |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_RECOVERY_ROUNDS` | `3` | Maximum repair rounds per blob |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_RECOVERY_ACTIONS` | `8` | Maximum recovery actions per blob |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_REINITIALIZATIONS` | `1` | Maximum new sessions after the initial init |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_TOKEN_REFRESHES` | `2` | Maximum authenticated token refreshes per blob |
| `MODELSCOPE_UPLOAD_MULTIPART_MAX_RETRY_AFTER_SECONDS` | `60` | Longest multipart Retry-After delay honored (seconds) |
| `MODELSCOPE_UPLOAD_MULTIPART_CONTROL_READ_TIMEOUT_SECONDS` | `300` | Read timeout for multipart init/status/complete requests (seconds); the server allows 240 s |
| `MODELSCOPE_UPLOAD_MULTIPART_COMPLETE_SETTLE_SECONDS` | `15` | Wait between status polls after an uncertain complete outcome (seconds) |
| `MODELSCOPE_UPLOAD_MULTIPART_PURE_PYTHON_MAX_BYTES` | `256MiB` | Largest source `auto` mode uploads with the pure Python hash engine; larger sources use the ordinary blob PUT (`required` only warns) |
| `MODELSCOPE_SHA256_LIBCRYPTO_PATH` | — | Absolute path of a libcrypto shared library for the native SHA256 prefix engine; when unset, common system libraries are probed |

Resumable multipart is pre-release and disabled by default. It applies to eligible model/dataset LFS sources (`MODELSCOPE_UPLOAD_MULTIPART_THRESHOLD` or larger) and to LoRA weight pre-uploads from the compat `create_model` / `create_model_tag` AIGC path, and preserves the existing commit pipeline. Every session runs status-first, initializes only on `UPLOAD_NOT_FOUND`, sends only pending or dirty parts, and completes once; a rerun resumes from the local state hint and never re-sends confirmed parts. The whole-file and part digests use Python's `hashlib`; the protocol-required SHA256 prefix state uses a native libcrypto engine (located automatically or through `MODELSCOPE_SHA256_LIBCRYPTO_PATH`, accepted only after a self-test) and falls back to a pure Python engine that is thousands of times slower. No additional Python dependencies or persistent hash caches are used. `auto` falls back to the ordinary blob PUT when the Mirror rejects multipart before any part exists or when the pure Python engine would hash a source above `MODELSCOPE_UPLOAD_MULTIPART_PURE_PYTHON_MAX_BYTES`; `required` raises instead of falling back. Service interoperability, full regression, and throughput/RSS validation remain release gates.

Capacity thresholds are advisory and emit warnings without blocking upload. Structural errors (invalid paths, missing inputs, changed files) still fail immediately, while the server's per-commit action ceiling is always enforced by splitting. A manual rerun retries every file not marked committed, including files whose previous run ended with a non-retryable error.

Expand Down
3 changes: 3 additions & 0 deletions src/modelscope_hub/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from __future__ import annotations

from ._aigc_weights import WeightIdentity, preupload_aigc_weights
from ._cache_manager import resolve_cached_snapshot
from ._download import ProgressCallback, TqdmCallback
from .agent_idp import (
Expand Down Expand Up @@ -88,6 +89,8 @@
"set_default_config",
"get_cache_root",
"resolve_cached_snapshot",
"preupload_aigc_weights",
"WeightIdentity",
# Enums
"AigcModelType",
"DatasetCategory",
Expand Down
105 changes: 105 additions & 0 deletions src/modelscope_hub/_aigc_weights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""Resumable multipart pre-upload for LoRA weights (``PUT /api/v1/models/aigc/weights``)."""

from __future__ import annotations

import hashlib
import os
import re
import stat
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING

from ._multipart_config import MultipartSettings, MultipartTarget
from ._multipart_control import UploadExecution
from ._multipart_upload import BlobTransferResult, MultipartUploader
from .config import get_default_config
from .constants import UPLOAD_CACHE_ENABLED
from .errors import InvalidParameter

if TYPE_CHECKING:
from ._legacy_api import LegacyClient


@dataclass(frozen=True)
class WeightIdentity:
"""Server-confirmed weight identity; ``reused`` means no part was sent."""

sha256: str
size: int
reused: bool
part_requests: int


def _whole_file_sha256(path: str | Path, size: int) -> str:
# First pass: every action carries the whole-file identity, so it is fixed
# locally before the first request.
hasher = hashlib.sha256()
read = 0
with open(path, "rb") as stream:
while chunk := stream.read(1024 * 1024):
hasher.update(chunk)
read += len(chunk)
if read != size:
raise InvalidParameter("Weight file size changed while it was being read.")
return hasher.hexdigest()


def preupload_aigc_weights(
path: str | Path,
*,
sha256: str,
size: int,
client: LegacyClient,
home: Path | None = None,
execution: UploadExecution | None = None,
) -> WeightIdentity:
"""Register one LoRA weight file with the resumable multipart protocol.

Returns only after the server reports ``completed`` with a matching
identity; the caller may then run the existing model/tag creation with
unchanged weight metadata. Any other outcome raises.
"""
settings = execution.settings if execution is not None else MultipartSettings.load(client.endpoint)
if settings.mode == "off":
raise InvalidParameter("Multipart weight upload is disabled (MODELSCOPE_UPLOAD_MULTIPART_MODE=off).")
if not isinstance(sha256, str) or not re.fullmatch(r"[0-9a-fA-F]{64}", sha256):
raise InvalidParameter("sha256 must be a 64-digit hex digest of the whole weight file.")
sha256 = sha256.lower()
if type(size) is not int or size <= 0:
raise InvalidParameter("size must be the positive byte length of the weight file.")
if not isinstance(path, (str, Path)):
raise InvalidParameter("Weight path must be a local file path.")
try:
info = os.stat(path)
except OSError as error:
raise InvalidParameter(f"Weight file is not accessible: {path}") from error
if not stat.S_ISREG(info.st_mode):
raise InvalidParameter("Weight path must be a regular file.")
if info.st_size == 0:
raise InvalidParameter("Weight file is empty.")
if info.st_size != size:
raise InvalidParameter("Weight file size does not match the declared size.")
if _whole_file_sha256(path, size) != sha256:
raise InvalidParameter("Weight file SHA256 does not match the declared digest.")
state_dir: Path = home if home is not None else get_default_config().config_dir
target = MultipartTarget.aigc_weights(client.endpoint, sha256, size)

def upload(active: UploadExecution) -> BlobTransferResult:
return MultipartUploader(
active,
home=state_dir,
repo_id="",
repo_type="aigc_weights",
sha256=sha256,
size=size,
data=path,
kind="aigc_weights",
).run(target.url, entry="status_tokenless")

if execution is not None:
result = upload(execution)
else:
with UploadExecution(settings, client, None, UPLOAD_CACHE_ENABLED) as created:
result = upload(created)
return WeightIdentity(sha256, size, result.reused, result.part_requests)
94 changes: 93 additions & 1 deletion src/modelscope_hub/_legacy_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
)
from .errors import (
APIError,
AuthenticationError,
InvalidParameter,
NetworkError,
PermissionDeniedError,
Expand Down Expand Up @@ -1065,6 +1066,8 @@ def validate_blobs(
repo_id: str,
repo_type: str,
objects: list[dict[str, Any]],
*,
strict: bool = False,
) -> dict[str, str | None]:
"""Check which blobs need uploading via the LFS batch API.

Expand All @@ -1079,18 +1082,107 @@ def validate_blobs(
f"repos/{segment}/{repo_id}/info/lfs/objects/batch",
json_body=payload,
)
data = self._json_data(resp)
if strict:
from ._multipart_protocol import MultipartError

try:
body = resp.json()
except ValueError:
raise MultipartError("LFS batch did not return valid JSON.") from None
if not isinstance(body, dict) or body.get("Success") is not True or body.get("Code") not in (200, "200"):
raise MultipartError("LFS batch did not confirm a successful response.")
data = body.get("Data")
if not isinstance(data, dict) or not isinstance(data.get("objects"), list):
raise MultipartError("LFS batch did not return an objects array.")
else:
data = self._json_data(resp)

result: dict[str, str | None] = {}
resp_objects = data.get("objects", []) if isinstance(data, dict) else []
expected = {item["oid"] for item in objects} if strict else set()
expected_sizes = {item["oid"]: item["size"] for item in objects} if strict else {}
multipart = {item["oid"] for item in objects if item.get("upload_type") == "http"} if strict else set()
for obj in resp_objects:
if strict and (
not isinstance(obj, dict)
or not isinstance(obj.get("oid"), str)
or obj.get("oid") not in expected
or obj.get("error")
):
raise MultipartError("LFS batch returned an invalid or failed object.")
oid = obj.get("oid", "")
if strict and obj.get("size") != expected_sizes[oid]:
raise MultipartError("LFS batch changed an object's size.")
actions = obj.get("actions", {})
if strict and (oid in result or not isinstance(actions, dict)):
raise MultipartError("LFS batch returned duplicate or invalid actions.")
upload_action = actions.get("upload", {})
if strict and (
not isinstance(upload_action, dict)
or (oid in multipart and (upload_action.get("header") or upload_action.get("headers")))
):
raise MultipartError("Multipart upload-action headers require a verified service contract.")
href = upload_action.get("href")
if strict and "upload" in actions and (not isinstance(href, str) or not href):
raise MultipartError("LFS batch upload action is missing its URL.")
result[oid] = href # None means already exists
if strict:
# LFS batch semantics: an object the server already holds is omitted from
# the response (pre.modelscope.cn does this for plain and upload_type=http
# requests alike); some deployments echo it without actions instead. Both
# mean "already exists", so the caller reuses the blob with no multipart
# request. Only a present-but-malformed entry is a contract violation.
for oid in expected - set(result):
result[oid] = None
return result

def _multipart_session(self) -> requests.Session:
session = requests.Session()
session.headers["User-Agent"] = self._user_agent
retry = Retry(total=0, connect=0, read=0, status=0, redirect=0, other=0)
adapter = HTTPAdapter(max_retries=retry, pool_connections=1, pool_maxsize=1)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session

def _multipart_request(
self,
session: requests.Session,
url: str,
*,
headers: dict[str, str],
data: Any,
timeout: tuple[int, int],
max_response_bytes: int,
) -> requests.Response:
from ._multipart_protocol import MultipartError

if not self._token:
raise AuthenticationError("Multipart upload requires a valid login identity.")
merged = self._headers(headers)
merged["Cookie"] = f"m_session_id={self._token}"
if "Content-Type" not in headers:
merged.pop("Content-Type", None)
try:
response = session.put(url, data=data, headers=merged, timeout=timeout, allow_redirects=False, stream=True)
try:
content = bytearray()
for chunk in response.iter_content(chunk_size=65536):
if len(content) + len(chunk) > max_response_bytes:
raise MultipartError("Multipart response exceeds its configured size limit.")
content.extend(chunk)
response._content = bytes(content)
response._content_consumed = True
return response
finally:
response.close()
except requests.Timeout:
raise RequestTimeoutError("Multipart request timed out; its outcome may be unknown.") from None
except requests.ConnectionError:
raise NetworkError("Multipart connection failed; its outcome may be unknown.") from None
except requests.RequestException:
raise NetworkError("Multipart transport failed; its outcome may be unknown.") from None

def upload_blob(
self,
upload_url: str,
Expand Down
Loading
Loading