modelscope-hub connects your code to the ModelScope ecosystem — models, datasets, Studio spaces, skills, and MCP servers — through a single HubApi class or the ms-hub CLI.
Unified repo interface — one set of methods for models, datasets, studios, skills, and MCP servers
OpenAPI-first — built on the ModelScope OpenAPI surface with transparent legacy fallback
Production-grade downloads — HTTP Range resume, parallel range download for large files, per-file retry with backoff, SHA256 integrity checks, file lock for multiprocess safety, offline mode, progress callbacks, and intra-cloud acceleration
Full lifecycle CLI — download, upload, deploy, manage secrets, inspect cache — all from the terminal
Deep ecosystem integration — seamless access to 100K+ models and datasets on ModelScope Hub; works with the modelscope training framework, Studio deployment platform, and MCP server infrastructure
News
v0.7.2 (2026-11-24)
Fix: download counting — a snapshot download (download_repo, snapshot_download, ms-hub download, report mode) sends one snapshot-identifier per task, shared by every file, retry, resumed transfer and range part, instead of a new one per file; a resumed report-mode task keeps its identifier. Standalone file downloads (download_file, model_file_download, dataset_file_download, CLI file arguments) no longer send one, so the Hub counts them per file. Cached dataset meta files no longer trigger a download request
v0.7.1 (2026-11-10)
Fix: the intra-cloud region probe is bounded per hop by MODELSCOPE_DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS (default 1), so a slow probe falls back to the default route instead of stalling the download
v0.7.0 (2026-11-09)
Feature: modelscope_hub.kernels loads optimized kernels from ModelScope (kernels extra); modelscope_hub.compat.hf_hub_patcher redirects huggingface_hub calls to ModelScope (hf extra); uploads route through the commit API instead of a git clone + push
Enhance: offline cache compatibility — resolve_cached_snapshot and local_files_only resolve standard and legacy cache layouts without network access or writes, legacy model-root links keep pre-snapshot paths valid, ms-hub cache clear validates scope and supports --dry-run, and MODELSCOPE_CACHE takes precedence over the MS_CACHE_HOME alias
v0.6.1 and older
v0.6.1 (2026-10-30)
Feature: ms-hub download --total-timeout (and HubApi(download_total_timeout=...)) sets a per-file time budget that overrides the environment variable; 0 means no limit
Behaviour: a transfer that keeps making progress is no longer capped by default — MODELSCOPE_DOWNLOAD_TOTAL_TIMEOUT now defaults to 0 (was 3600), while idle timeouts, the low-speed watchdog and bounded retries still apply; set a positive value to restore a cap
Fix: a stop caused by an expired budget keeps its partial data and is reported as pending, so a plain re-run resumes it instead of requiring --retry-failed; trickling response headers stay bounded by the idle timeout when no overall budget is set
Quality: budget and cancellation messages are English and name both the budget and the variable that relaxes it
v0.6.0 (2026-10-29)
Feature: model and dataset writes moved to OpenAPI — repository creation, category set/update, detail reads, model option lists and repository settings; get_model/get_dataset keep the historical Visibility enum, while gated_mode=True/False is the separate application switch
Breaking: approval_mode, the gated request parameter and --approval-mode are removed; passing them through **kwargs raises TypeError before any request
Enhance: creation keeps the v0.5.1 legacy request format when gated_mode is explicit, and category/zone and set-only fields are validated before sending
v0.5.1 (2026-10-26)
Feature: HubApi.download_repo_report and ms-hub download --continue-on-error continue past isolated file failures and return a COMPLETE/PARTIAL report; --retry-failed reruns them and exit code 3 means partial. download_repo and snapshot_download stay strict
Enhance: recovery hints live in one hidden JSON per task (no embedded database), state is advisory and re-validated against actual size/hash, failed pages are isolated, and listings stream with bounded queues
v0.5.0 (2026-10-24)
Feature: downloads verify size and SHA-256 before replacing files, with safe resume, bounded retries, idle and total timeouts, low-speed detection, cancellation and per-file locks; an incomplete snapshot raises FileDownloadError (CLI exit code 1) and keeps completed files
Enhance: every request sends the same modelscope_hub/<version> User-Agent, with custom information appended and CLI/compat markers propagated; errors name the next step
Behaviour: downloads and listings honour the new MODELSCOPE_DOWNLOAD_* and MODELSCOPE_REPO_TREE_PAGE_* variables listed in the environment-variable table
v0.4.6 (2026-10-09)
Fix: cross-region downloads cache a confirmed OSS-internal resolution per storage route (repository, revision and redirect endpoint) and probe routes in parallel, so a metadata route miss no longer suppresses the LFS probe or stalls the transfer
v0.4.5 (2026-09-21)
Feature: ms agent install -r owner/name installs an agent through a framework plugin published as a model repository, gated three times — explicit --plugin-repo/MODELSCOPE_AGENT_PLUGIN_REPO, a case-sensitive owner allow-list checked before any request, and a non-persisted trust prompt showing the manifest digest
Enhance: upload recovery retries commit-only failures without re-uploading blobs, splits policy rejections down to single files, aborts after three fully failed batches with a resumable tracker, and only warns about capacity limits
Fix: an HTTP 200 create-commit answer carrying Success:false is reported as an error instead of a silent success
v0.4.4 (2026-09-20)
Feature: commit batching — at most UPLOAD_COMMIT_BATCH_MAX_OPERATIONS (256) actions and an 8 MiB estimated request body per commit, clamped to the server's 2000-action ceiling, with LFS pointers excluded from the body budget; oversized inline files get their own batch, and path_in_repo is normalised consistently below the API layer
Fix: a repository tree page answering 403 mid-enumeration is retried instead of aborting a listing that spans hundreds of requests
v0.4.3 (2026-09-15)
Fix: an agent list answering 200 with OperationNotAllowed is reported as a permission error instead of an empty result; MCP list replies with legacy 200 + success:false envelopes are decoded as errors
v0.4.2 (2026-09-10)
Feature: delete_files on HubApi and the compat HubApi deletes explicit paths or glob patterns resolved against the remote file list, applied as commit delete actions
v0.4.1 (2026-09-09)
Feature: deletions go through the commit path like uploads (delete_files on the commit manager), because the direct repository DELETE endpoint rejects API-token authentication
v0.4.0 (2026-09-01)
Feature: complete OpenAPI coverage for Agent-IDP, MCP, and Studios — Agent Ed25519 identities, OIDC discovery/JWKS and signed JWT issuance (HubApi, ms-hub agent-idp); Studio lists, variables and configuration options; hosted MCP discovery; protected visibility and runtime metadata; read-only tokens can log in and rejected writes name the required tier. Agent private JWKs are only written to an explicitly requested owner-only file.
Fix: Studio compat calls no longer leak connection options or API tokens, or drop cover images; errors distinguish permission, quota and conflicts; anonymous Studio info and log pagination work
Enhance: MCP verb negotiation and Studio-owner listings adapt to endpoint behaviour
Quality: the vendored OpenAPI spec and operation registry flag unimplemented published Agent-IDP, MCP, and Studios endpoints
v0.3.1 (2026-09-01)
Refactor: upload environment variables now state their units and semantics; deprecated names remain supported with warnings
Fix: logout works; download locks avoid same-basename contention; whoami and legacy responses normalise pre-production field names
v0.3.0 (2026-08-19)
Feature: this package owns all four console scripts (modelscope, ms, modelscope-hub, ms-hub), adds HubApi.get_current_username(), and supports both agent visibility wire formats
Fix: large repo/files listings are re-enumerated when the server silently truncates results
v0.2.0 (2026-08-01)
Breaking: HubApi.login() now raises NetworkError / ServerError / RequestTimeoutError for non-authentication failures instead of always raising AuthenticationError — widen except AuthenticationError to HubError if you catch any login failure
Fix: network, timeout and 5xx errors during login are no longer misreported as an invalid token; a failed login no longer deletes stored credentials; bare and upper-case endpoints are accepted (e.g. --endpoint modelscope.ai)
Enhancement: a rejected login probes the peer ModelScope site and suggests --endpoint when the token is valid there; --verbose prints the full error cause chain
v0.1.9 (2026-07-31)
Fix: two stale unit tests that failed in downstream distro sandboxes (#46, NixOS): align the mcp deploy call-shape assertion and the parse_timestamp timezone-normalization contract
Feature: ms-hub mcp deploy prints the operational URL after deployment; new --auth-check and repeatable --env KEY=VALUE options; --transport-type now validates against sse/streamable_http
CI: new citest workflow — mock-mode test suite (no credentials/network, mirrors distro build sandboxes) on Python 3.10/3.12/3.14 plus ruff/mypy hard gates; releases now require a green test gate before publishing; added a pre-commit config
Quality: ruff & mypy debt cleared to zero; lint/type-check targets aligned to the supported Python floor (3.10)
v0.1.8 (2026-07-21)
Feature: ms-hub agent raw file transfer (download/upload/list) for remote agent repos; visibility support for agent hub; cache checksum verification (ms-hub cache verify)
Fix: forward progress_callbacks through HubApi.download_repo so custom download-progress callbacks work end-to-end; harden legacy (pre-1.38) cache auto-detection (reuse existing {cache}/models/... and default {cache}/hub/models/... layouts); normal (non-LFS) file upload
Packaging: rename console scripts to modelscope-hub / ms-hub to avoid a file conflict with the modelscope package (e.g. FreeBSD pkg)
v0.1.7 (2026-07-07)
Feature: intra-/inter-region cloud download acceleration, with a source marker in the progress bar
Fix: align snapshot_download cache path with the CLI; add legacy cache fallback
Refactor: inter-region config via env var only (removed the --inter-regions CLI arg); cache the region probe
v0.1.6 (2026-07-03)
Refactor: replace the extra-field whitelist with a reserved-field blocklist for more permissive param passthrough
v0.1.5 (2026-06-30)
Fix: adaptive commit batch size for uploads
v0.1.4 (2026-06-26)
Feature: gated_mode parameter for create_repo; ms-hub create --gated/--no-gated flags
Refactor: unify visibility / gated_mode semantics in the SDK layer
Fix: create_repo extra-kwargs whitelist + type validation; correct visibility mapping (private bool is authoritative)
v0.1.3 (2026-06-23)
Feature: add AlreadyExistsError (E3026) and fix the exist_ok mechanism; align list_repos/RepoInfo with the OpenAPI response format
Fix: clear-cache supports all cache layouts (standard/flat/legacy); add last_modified mapping and to_dict() for RepoInfo/PagedResult
v0.1.2 (2026-06-23)
Fix: unify list_datasets/get_dataset return format and align parameters
Requires Python 3.10+. Lightweight — only requests, tqdm, filelock, urllib3.
Command names
This package installs every ModelScope console script, and all four are the same
program — pick whichever reads best in your shell:
Command
Use it for
modelscope
the primary, brand-level command
ms
short form of modelscope
modelscope-hub
explicit hub-only invocation
ms-hub
short form of modelscope-hub
Owning all four in one distribution is deliberate: when the umbrella
modelscope SDK also declared
modelscope / ms, installing or upgrading either package could overwrite or
delete the other's scripts and leave you with no CLI at all. OS packagers (such
as FreeBSD pkg) likewise refuse to let two ports own the same path. The SDK now
contributes its extra commands as plugins instead.
So modelscope and ms work on a hub-only install too. Commands that belong to
the full SDK (pipeline, server, studio, modelcard, …) appear once you
also pip install modelscope; until then --help says so. The two *-hub
aliases always report just this package, which is handy for scripts that must
pin the lightweight client:
Downloads validate available size and SHA-256 metadata before replacing files, with safe resume, bounded retries, timeouts, and cancellation. Incomplete snapshots raise FileDownloadError (CLI exit code 1), preserving completed files for subsequent retries.
Download counting: each download_repo / snapshot_download call is one snapshot download. Every file request it makes, including retries, resumed transfers and range parts, carries the same snapshot-identifier. The dataset service deduplicates this identifier for two hours; standalone download_file calls send no identifier and use fractional per-file counting. Cached files issue no download requests.
The dataset count is recorded at the first eligible file request, not when the whole download succeeds; filtered snapshots can count as one download, and cancellation does not roll it back. The server's asynchronous updates and two-hour deduplication TTL do not provide exactly-once counting for arbitrary task durations. Model and archive counting use separate server logic.
Load kernels (modelscope_hub.kernels)
modelscope_hub.kernels is a drop-in wrapper around the kernels library that downloads optimized compute kernels from ModelScope instead of the Hugging Face Hub. A kernel repository is an ordinary ModelScope model repository mirroring the HF kernel layout (build/<variant>/... plus v1-style version branches or tags):
pip install "modelscope-hub[kernels]"
from modelscope_hub.kernels import get_kernel
# Download optimized kernels from the ModelScope hub
activation = get_kernel("kernels-community/activation", version=1)
Also available: has_kernel() (environment compatibility check), get_kernel_variants() (build-variant decisions), get_local_kernel() (load from a local path, dependencies from ModelScope), install_kernel() (download to the local cache without importing — CI pre-installation / offline preparation), install_kernel_all_variants() (download every build variant plus the dependency tree), lock_kernels() (resolve the dependency tree against ModelScope and write a kernels.lock file — the in-process equivalent of kernels lock), get_locked_kernel() (load a kernel pinned by a lockfile, downloading missing pieces), and load_kernel() (import an already-installed locked kernel; never downloads). The same lockfile can be created from the command line with ms-hub kernels lock [project_dir], which reads [tool.kernels.dependencies] from pyproject.toml. Under patch_kernels_hub() every other networked kernels entry point (the layer/kernelize APIs, benchmarks, etc.) is redirected the same way, because the whole library routes through one Hub API factory. The upstream kernels lock console script runs in its own process and therefore cannot pick up the in-process patch; use lock_kernels() or ms-hub kernels lock instead.
Notes:
The kernel loading, variant resolution, and dependency logic of kernels are reused unchanged — only its Hub API factory is swapped for a ModelScope-backed shim while a modelscope_hub.kernels call is in flight, so a plain import kernels elsewhere keeps using the Hugging Face Hub. patch_kernels_hub() / unpatch_kernels_hub() / patch_scope() switch this explicitly if you need it globally; the modelscope package's patch_hub() builds on the same implementation.
version=N resolves against the repository's v<N> branches/tags. A mirror that only carries master exposes it as kernel version v1 automatically.
Kernel lockfiles record hub-specific commit hashes: a lockfile created against the Hugging Face Hub cannot resolve on ModelScope (the two hubs have different git histories). Create the lockfile in the ModelScope environment (lock_kernels(), install_kernel_all_variants, or ms-hub kernels lock) so it records ModelScope commits; a commit-hash revision that cannot be found raises with a note explaining this.
ModelScope has no trusted-publisher flag, so untrusted publishers are rejected by default: only kernels-community is trusted out of the box. Extend the allowlist with MS_KERNELS_TRUSTED_PUBLISHERS (comma-separated), or allow specific repositories / all repositories through the trust parameters of get_kernel (its docstring mirrors the kernel library's API).
The mirror must contain kernels built for your exact Torch version and platform (kernels selects build/torchXY-...-<cpu>-<os>/); a repository whose builds predate kernels 0.17 metadata cannot be loaded until it is rebuilt with a current kernel-builder.
Continuous dataset downloads
For migration jobs, download_repo_report continues past isolated file failures and returns an explicit COMPLETE or PARTIAL report. The original download_repo and snapshot_download remain strict by default.
from modelscope_hub import HubApi, DownloadRetryPolicy
api = HubApi(endpoint="https://www.modelscope.ai")
report = api.download_repo_report(
"owner/dataset", "dataset", revision="master", local_dir="./data",
tracker_path="./.ms_download_state.json", max_workers=8,
retry_policy=DownloadRetryPolicy(),
)
for entry in report.iter_files("VERIFIED"):
consume_verified_file(entry.path)
print(report.status, report.succeeded, report.failed, report.deferred, report.report_path)
report.close() # Release temporary per-file results after consumption.
Recovery defaults: at most 2 extra retries per file, shared by range parts and integrity recovery; failed-request inactivity and waits have a 60-second cumulative budget. Idle/header waits are limited to 15 seconds, low-speed checks use a 10-second window, and cooldowns longer than 5 seconds defer the file instead of tying up a worker. Size/hash mismatches get at most one full re-download. Healthy transfer time is not capped by default: a transfer that keeps making progress runs to completion, and MODELSCOPE_DOWNLOAD_TOTAL_TIMEOUT only applies when set to a positive value.
Each task uses one hidden JSON file outside downloaded contents (cache_dir/.download_state/.ms_download_<key>.json by default), with no embedded database dependency. It combines sparse failures, recovery budgets, failed pages, and the latest call's summary under report; report.report_path equals report.tracker_path. Reruns and batches replace the same file, without extra report JSON or JSONL files. Successful files have no persistent per-file records; a healthy run writes only its scope header and final summary, not an update per file. Its scope is endpoint/repository/revision/output, independent of batch filters. Standard reusable lock files remain separate from JSON metadata.
The same JSON keeps the task's snapshot-identifier: reruns of an unfinished task (PARTIAL or CANCELLED) reuse it, so the dataset service can deduplicate resumed requests within its two-hour window; the run after a COMPLETE one starts a new task. Keeping it adds no writes beyond the scope header, exceptional records and the final summary.
State is advisory, never the sole evidence of success. Every rerun validates actual files against current size/hash metadata, even if hints say FAILED or DEFERRED; a repaired valid file clears its stale hint without network IO. Otherwise failures remain isolated until metadata changes or retry_failed=True. Missing or corrupt hints allow bounded fresh recovery; load/write problems are logged and exposed in report.state_warnings, not treated as data corruption or success. A crash during recovery preserves its budget if hints were saved; healthy in-flight files need no markers and resume from actual partial files. Old database-format trackers are not read or migrated: select a new JSON path; existing correct data is reused through validation.
Dataset pages are streamed with bounded queues. Failed pages are recorded and isolated across calls; later pages/roots can continue. Two consecutive failed pages stop that root, and listing_complete=False prevents false success. The next run can use retry_failed=True or an authoritative file_list iterable to recover incomplete enumeration. Model listings that hit an unrecoverable server cap also return a partial report.
Counts and report.iter_files() cover this call's selection. Per-file results stream from an anonymous temporary spool owned by the live report, so earlier report objects remain independent of later batches without permanent manifests or an in-memory list of every file. Call report.close() after consumption; garbage collection also releases its spool. results_path is empty. The single JSON retains only the latest summary, not historical reports or a verified-file manifest: reconstructing a report from it cannot provide per-file results; rerun actual-file validation instead. Aggregate batch counts for the whole migration. Only VERIFIED entries may be uploaded; changed files must be checked again before use, and partial reports must not authorize deleting source data. A pinned revision or authoritative manifest is recommended. Reuse the same tracker and output across ten-file batches; a tracker cannot be shared by simultaneous writers.
Credential loss or a full/read-only disk pauses further work and sets global_error; Ctrl+C writes a CANCELLED report and remains interruptible. DNS and blocked filesystem calls remain OS-constrained. Caller-provided iterables must also be responsive to cancellation.
ms-hub download owner/dataset --repo-type dataset --local-dir ./data --continue-on-error
# Explicit repair run after the source is fixed
ms-hub download owner/dataset --repo-type dataset --local-dir ./data --continue-on-error --retry-failed
# Cap each file at one hour, e.g. for a scheduled job with a fixed window
ms-hub download owner/dataset --repo-type dataset --local-dir ./data --total-timeout 3600
A file stopped by --total-timeout keeps its partial data and is reported as pending rather than failed, so a plain re-run resumes it; --retry-failed stays reserved for genuinely suspect files.
CLI exit codes: 0 complete, 3 partial after remaining known files have been processed, 1 global failure, 130 interrupted. Schedulers must treat 3 as partial completion, not an instruction to retry the whole task indefinitely. The SDK's modelscope_hub.compat.snapshot_download(..., continue_on_error=True, tracker_path=...) preserves a string return path and logs the report location; use HubApi.download_repo_report to read results directly. Older modelscope.hub.snapshot_download wrappers may not accept the new options: import the compat function from modelscope_hub directly until the wrapper is updated.
The SDK keeps its historical Visibility integer enum: PRIVATE=1,
INTERNAL=3, PUBLIC=5. Application gating is a separate boolean switch,
gated_mode=True / False, and is not deprecated. It is effective for private
repositories; with explicit public/internal visibility it is warned about and
ignored. Either explicit boolean with no visibility still implies private.
Use the same high-level spelling as v0.5.1. A gated repository requires an
approved application to download; the boolean switch does not select an
approval policy:
api.create_repo(
"my-org/my-data", "dataset", visibility="private",
gated_mode=True,
)
# Turn the application switch off; the repository becomes ordinary private.
api.update_repo_settings("my-org/my-data", "dataset", gated_mode=False)
Ordinary creation prefers OpenAPI. Explicit gated_mode=True/False creation
retains the legacy Visibility plus ProtectedMode=1/2 request format to keep
v0.5.1 behaviour. Settings adapt the boolean to the OpenAPI access mode internally;
True enables gating with the server's auto approval default, False leaves an
ordinary private repository, and None leaves the control unchanged.
High-level visibility accepts the historical enum/labels, not "gated".
approval_mode and gated request parameters have been removed, including the
--approval-mode CLI flag; passing them through **kwargs raises TypeError
before any request. This does not remove the existing RepoInfo.gated boolean
response field or the native gated_mode string in new detail responses.
get_repo() preserves Visibility for models/datasets, while raw get_model() /
get_dataset() retain native OpenAPI fields. Native approval-policy strings
belong only to the low-level api.openapi payloads, not to the high-level
gated_mode boolean.
visibility="internal" (visible within an organisation) has no equivalent in
the OpenAPI surface, so those requests continue to use the legacy endpoint.
Model and dataset zones
Models belong to the base, aigc, or science zone; datasets to base or
science. A new repository is always base. Upload the files first, then set
the zone — the AIGC endpoint checks that each weight path already exists:
api.create_repo("my-org/my-lora", "model", visibility="private")
api.upload_folder("my-org/my-lora", "model", "./my-lora-files")
options = api.list_aigc_model_options() # enum ids, no credentials needed
api.set_model_category(
"my-org/my-lora",
model_category="aigc",
aigc_type="LoRA",
base_model_architecture_type=options["base_architectures"][0]["id"],
base_model_architecture_subtype=options["base_architectures"][0]["subtypes"][0]["id"],
version_name="v1.0",
weight_files=[{"path_in_repo": "model.safetensors"}],
sample_images=[{"url": "https://example.com/sample.png", "prompt": "a cat"}],
)
# Detail reads can lag behind writes; wait briefly before resolving a new version name.
import time
for _ in range(10):
detail = api.get_model("my-org/my-lora")
if any(v.get("version_name") == "v1.0" for v in detail.get("versions", [])):
break
time.sleep(1)
else:
raise TimeoutError("The new version is not visible yet; retry the detail read later.")
# Edit a version's metadata in place, addressed by version name or numeric id.
api.update_model_category("my-org/my-lora", version_name="v1.0", trigger_words=["anime"])
# Read the zone fields back; which keys are present depends on the category.
detail = api.get_model("my-org/my-lora")
print(detail["model_category"], [v["version_id"] for v in detail.get("versions", [])])
Enum values (aigc_type, architectures, subject areas, task, license) come
from the options endpoints; pass each option's id, not its label. An
existing version's weights are immutable — changing them means creating a new
version with set_model_category.
Deploy a Studio
ms-hub deploy my-org/chat-demo --repo-type studio
ms-hub logs my-org/chat-demo --log-type run
ms-hub stop my-org/chat-demo --repo-type studio
The CLI is available as both ms-hub and modelscope-hub.
Global options (placed before or after the subcommand):
Option
Description
--token TOKEN
API token (overrides env and persisted token)
--endpoint URL
API endpoint (default: https://modelscope.cn)
-v, --verbose
Enable DEBUG logging (global only)
-V, --version
Print version and exit (global only)
--token and --endpoint can be placed either before or after the subcommand:
ms-hub --token xxx download ... and ms-hub download ... --token xxx are equivalent.
Browse and download; list your Studios, secrets and variables
write
Everything above, plus create/upload/deploy and change settings
admin
Everything above, plus administrative operations
What this means in practice:
A read-only token can log in.ms-hub login succeeds and prints a warning
that git and session credentials were not issued, so pushes and uploads will
need a write token. Downloads and browsing work normally.
A rejected write is explicit. Attempting a write with a read-only token
fails with [E3002] Permission denied and a suggestion naming the level the
operation requires, rather than leaving you to guess.
Quota exhaustion is not a permission problem. The service reports both as
HTTP 403; the SDK separates them into PermissionDeniedError and
QuotaExceededError (the latter is never retried, since retrying an exhausted
quota only delays the error).
Public reads never fail because of a token. For public endpoints the SDK
retries once without credentials, so a read-scoped or stale token cannot hide
data any anonymous caller can see.
The SDK cannot tell you which level your token has: the API does not report
it. Check the token settings page if you are unsure.
ms-hub whoami
Show the user associated with the current token.
ms-hub whoami
ms-hub whoami --token $MY_TOKEN # check a specific token without logging in
ms-hub download
Download a single file or a full repository snapshot.
ms-hub download Qwen/Qwen3-0.6B # full snapshot
ms-hub download Qwen/Qwen3-0.6B config.json # single file
ms-hub download Qwen/Qwen3-0.6B --include "*.safetensors" # filter by glob
ms-hub download Qwen/Qwen3-0.6B --local-dir ./out --max-workers 8 # direct download
ms-hub download my-org/my-data --repo-type dataset --revision v2 # dataset at tag
Argument / Option
Required
Description
repo_id
yes
Repository identifier (owner/name)
files...
no
Specific file paths; omit for full snapshot
--repo-type {model,dataset}
no
Default: model
--revision REV
no
Branch, tag, or commit hash (default: master)
--local-dir DIR
no
Download directly here (bypasses cache layout)
--cache-dir DIR
no
Override default cache directory
--include GLOB...
no
Only download matching files; repeatable
--exclude GLOB...
no
Skip matching files; repeatable
--max-workers N
no
Parallel download threads (default: 4)
--force
no
Re-download even if cached
Advanced examples
# Download multiple specific files at once
ms-hub download Qwen/Qwen3-0.6B config.json tokenizer.json generation_config.json
# Download only safetensors, skip GGUF and bin weights
ms-hub download Qwen/Qwen3-0.6B --include "*.safetensors" --exclude "*.bin" "*.gguf"
# Download a dataset at a specific tag into a local directory
ms-hub download my-org/my-data --repo-type dataset --revision v2 --local-dir ./data
# Use a custom cache directory and 8 parallel threads
ms-hub download Qwen/Qwen3-0.6B --cache-dir /data/hub-cache --max-workers 8
# Force re-download even if already cached
ms-hub download Qwen/Qwen3-0.6B config.json --force
# Download all skills from a collection (legacy flag)
ms-hub download --collection my-org/skill-collection
# Enable parallel range download for large files (env var)
MODELSCOPE_DOWNLOAD_PARALLELS=4 ms-hub download Qwen/Qwen3-0.6B
# Use the modelscope.ai endpoint (global option, before subcommand)
ms-hub --endpoint https://modelscope.ai download Qwen/Qwen3-0.6B
# Upload a single file with a custom commit message
ms-hub upload my-org/my-model ./weights.safetensors --commit-message "add fp16 weights"
# Upload a folder into a subdirectory of the repo
ms-hub upload my-org/my-model ./output models/ --repo-type model
# Upload only Python files from the current directory
ms-hub upload my-org/my-model . --include "*.py" --commit-message "update code"
# Upload only safetensors, skip checkpoints
ms-hub upload my-org/my-model ./output --include "*.safetensors" --exclude "*.ckpt" "*.bin"
# Upload to a dataset repo on a specific branch
ms-hub upload my-org/my-data ./data --repo-type dataset --revision dev
# Upload with extended commit description
ms-hub upload my-org/my-model ./weights.safetensors \
--commit-message "v2 weights" \
--commit-description "Retrained with extended dataset, 3 epochs, lr=2e-5"
# Resumable upload: interrupted uploads resume automatically via cache
ms-hub upload my-org/my-model ./large-folder
# If interrupted, just re-run the same command — already uploaded files are skipped
# Disable upload cache (no resume, fresh upload every time)
ms-hub upload my-org/my-model ./output --no-cache
# Disable progress bars (useful for CI/CD pipelines)
ms-hub upload my-org/my-model ./output --disable-tqdm
ms-hub create / ms-hub info / ms-hub list / ms-hub delete
Repository management.
ms-hub create my-org/my-model --repo-type model --visibility private
ms-hub create my-org/demo --repo-type studio --sdk-type gradio
ms-hub info my-org/my-model --repo-type model
ms-hub list --repo-type model --owner my-org --page-size 20
ms-hub list --repo-type studio --owner my-org
ms-hub delete my-org/my-model --repo-type model --yes
Deletion permission:delete_repo / ms-hub delete needs repository deletion permission; ordinary write permission alone is not sufficient. An admin-level token has been verified to work. Tokens without the required permission are refused (10010101003 for models, 10020301011 for datasets) and directed to the web console. Retrying a permission rejection with the same token will not help.
delete_files uses the legacy commit/session path. File-deletion permission is distinct from repository-deletion permission; a write token may delete files even when it cannot delete the repository.
ms-hub create options
Argument / Option
Required
Description
repo_id
yes
Repository identifier
--repo-type
yes
model, dataset, studio, or skill
--visibility
no
public, private or internal. For Studios also protected (app public, code repository hidden)
Note:ms-hub logs only supports Studio spaces. MCP server logs are not available via this command.
ms-hub settings supports Studio and Skill repos; for MCP servers use ms-hub mcp deploy with configuration payload.
ms-hub secret / ms-hub studio variable
Manage a Studio's environment variables. Two commands, because the disclosure
differs: a secret's value is never returned by the API, a variable's value
is publicly visible.
# Secrets — values are write-only
ms-hub secret add my-org/demo API_KEY sk-xxx
ms-hub secret list my-org/demo
ms-hub secret update my-org/demo API_KEY sk-new
ms-hub secret delete my-org/demo API_KEY --yes
# Plaintext variables — values are readable by anyone
ms-hub studio variable add my-org/demo MODEL_NAME Qwen2.5-7B
ms-hub studio variable list my-org/demo
ms-hub studio variable update my-org/demo MODEL_NAME Qwen2.5-14B
ms-hub studio variable delete my-org/demo MODEL_NAME --yes
Subcommands
Subcommand
Arguments
Description
add
repo_id key value
Add a new entry
list
repo_id
List entries (secret shows keys only; variable shows keys and values)
update
repo_id key value
Update a value
delete
repo_id key [--yes]
Delete an entry
ms-hub secret accepts --repo-type (default: studio, currently the only supported type).
Put anything sensitive in a secret. A plaintext variable's value is public.
ms-hub studio
Browse Studio spaces and the runtime resources they can be configured with.
# Browse
ms-hub studio list --search chat --sort likes --page-size 20
ms-hub studio list --owner my-org --status all
ms-hub studio list --mcp-support --hardware-type xgpu
# Discover valid values for --hardware / --base-image / --sdk-version
ms-hub studio hardware --sdk-type gradio
ms-hub studio hardware --studio my-org/demo
ms-hub studio base-images
ms-hub studio sdk-versions --sdk-type gradio
# Runtime management (also available as the top-level deploy/stop/logs/settings)
ms-hub studio deploy my-org/demo
ms-hub studio logs my-org/demo --type build
ms-hub studio settings my-org/demo --visibility protected
--visibility accepts three values: public (code and app public), protected
(app public, code repository hidden) and private. --private / --public
remain as shorthands.
Paid hardware tiers are selected as --hardware paid/<instance_type>; run
ms-hub studio hardware to see the available identifiers.
--status defaults to all whenever --owner is given, so listing your own
spaces includes stopped ones. Without --owner the server's own default applies
(running spaces only).
ms-hub mcp
Manage MCP (Model Context Protocol) servers.
ms-hub mcp list --search weather --page-size 10
ms-hub mcp list --hosted # only your own hosted servers, with live URLs
ms-hub mcp info my-org/weather-mcp
ms-hub mcp deploy my-org/weather-mcp
ms-hub mcp undeploy my-org/weather-mcp
--hosted lists the servers you currently have hosted along with their
operational_urls. It takes no search or paging options, because the underlying
endpoint accepts none.
Discovery is capped at page * page_size <= 100 by the service.
Remote agent repositories: raw file transfer (download, upload, list) and plugin-driven install.
ms-hub agent download -r user/my-agent --local-dir ./my-agent # download raw files
ms-hub agent upload -r user/my-agent --local-dir ./my-agent # upload raw
ms-hub agent install -r user/my-agent # install into the framework
download / upload / list transfer files as-is, with no framework awareness.
install is different: it fetches an official plugin and hands the agent id to it, leaving every framework decision to the plugin. See ms-hub agent install for the details and the security model.
Framework-aware operations (cross-framework convert, watch/bidirectional sync, status, backups, restore, stop) live in modelscope-agent — use ms-agent agent ... instead. For example, to download and convert in one step: ms-agent agent download -f qoder -r user/my-agent --target-framework qwenpaw.
Subcommands
ms-hub agent download
Download all files of a remote agent repository to a local directory (raw, no conversion).
Source path (file or directory) to upload (default: CWD)
--revision REV
no
Repository revision (default: master)
--dry-run
no
List files that would be uploaded without uploading
ms-hub agent install
Download an agent and hand it to its framework plugin. A plugin with an install entry point places the agent into the framework's workspace; one that only transports bytes writes the repository's files into a destination directory and leaves placement to whatever runs next. The command reports which happened (Installed … vs Fetched …).
ms-hub agent install -r user/my-agent
Option
Required
Description
-r, --repo REPO
yes
Agent repository to install (owner/name)
--plugin-revision REV
no
Plugin revision (default: master; pin a tag for reproducible installs)
-n, --name NAME
no
Sub-agent name, passed through to the plugin
--framework FW
no
Override the plugin's framework detection
--local-dir DIR
no
Where the agent repository is downloaded, not where it is installed. Omitted, downloads go to $MODELSCOPE_CACHE/agent/agent-staging/<owner>--<name>-<timestamp>/ and are cleaned up on success
--dry-run
no
Ask the plugin to report instead of change anything. The plugin is still downloaded, imported and run — only its writes are suppressed
-y, --yes / --force / -q, --quiet
no
Passed through to the plugin
Exit codes: 0 success, 2 a gate refused or the command line is wrong, otherwise the plugin's own code — the install layer uses 3 (already exists), 4 (refused to overwrite), 5 (install or self-check failed), 6 (framework mismatch).
Supported scope
This package supports no frameworks; what can be installed is a property of the plugin build it fetches, so the authoritative list is printed every run:
planned names operations the plugin declares but has not implemented; calling one returns ok=False naming the planned release.
Security model
Where the plugin may come from is fixed at compile time, not at the command line:
Owner allow-list — modelscope_hub.constants.AGENT_PLUGIN_TRUSTED_OWNERS, currently modelscope and AI-ModelScope. Checked before anything is downloaded, with no environment override and no per-invocation confirmation: an allow-listed plugin is fetched and run. Widening the list is a reviewed code change.
Manifest integrity — plugin.json's content_sha256 is verified against the files on disk before import. That proves the bytes are the ones the manifest described; it is not authenticity, since the manifest is unsigned and ships beside the code it describes. Origin rests on the allow-list alone.
Which build is about to run is logged before the import. The plugin receives your --endpoint and your API token, since it needs credentials to fetch the agent.
Plugins from other owners are not supported. The package format is documented for maintainers in the modelscope_hub.agent._plugin module docstring.
Agent-IDP manages an Agent's identity and signing key, not its repository files. Use ms-hub agent for raw Agent repository transfer; use ms-hub agent-idp to register an Ed25519 public key, inspect OIDC metadata, and issue a short-lived JWT.
# Private JWK storage is always explicit; the command prints only its public JWK.
ms-hub agent-idp keygen --private-key-out ./agent.jwk
ms-hub agent-idp create --agent-name my-agent --private-key-file ./agent.jwk
ms-hub agent-idp issue-token --agent-id agent_id:modelscope:agent_xxx --audience my-hub --private-key-file ./agent.jwk
# These discovery endpoints are public and do not require login.
ms-hub agent-idp configuration
ms-hub agent-idp jwks
Protect the private JWK file: it is created with mode 0600 on POSIX, never copied into the SDK configuration or cache, and must not be committed. External key stores can pass a public JWK with --public-jwk-file for registration or rotation.
from modelscope_hub import HubApi
# Connect to modelscope.cn (default)
api = HubApi(token="...")
# Or connect to modelscope.ai
api = HubApi(token="...", endpoint="https://modelscope.ai")
Anonymous OIDC discovery and JWT verification keys
Cache
scan_cache(cache_dir)
Inspect local cache
clear_cache(cache_dir, ...)
Free disk space
Deletion restrictions:
delete_repo needs repository deletion permission. Insufficient permission is rejected (10010101003 / 10020301011); use an authorised token or the web console. An admin-level token has been verified to work. The SDK uses the legacy endpoint; the current OpenAPI contract has no repository-deletion route.
delete_files uses the legacy commit/session path and checks file-deletion permission separately. It does not inherit the OpenAPI file-deletion endpoint's 100-path limit. Editing a tag revision may be rejected by repository policy.
Token permission levels: every write method needs a token issued with
write permission or higher. A rejected write raises PermissionDeniedError
whose suggestion names the required level; an exhausted quota raises
QuotaExceededError instead. See Token permission levels.
Ecosystem Integration
modelscope-hub is the hub connectivity layer for the ModelScope ecosystem:
Browse & discover — search 100K+ models and datasets via list_repos / ms-hub repo list
Download & cache — pull model weights, tokenizer configs, or entire datasets into a managed cache or a local directory; supports offline mode via local_files_only
Train & fine-tune — use with the modelscope framework: train locally, then push results back
Deploy — launch a Studio space or MCP server directly from the CLI or SDK
Automate — integrate into CI/CD pipelines with environment-variable auth and --yes flags for non-interactive operation
Configuration
Run ms-hub list --envs to see all configurable environment variables with their current values.
Token is persisted locally after ms-hub login and auto-loaded in subsequent sessions.
Environment variables
Core:
Variable
Default
Description
MODELSCOPE_API_TOKEN
—
API authentication token
MODELSCOPE_ENDPOINT
https://modelscope.cn
API endpoint URL
MODELSCOPE_CACHE
~/.cache/modelscope
Local cache directory; takes precedence over the legacy MS_CACHE_HOME alias
MODELSCOPE_HOME
~/.modelscope
SDK config directory
MODELSCOPE_PREFER_AI_SITE
false
Prefer modelscope.ai over modelscope.cn
Network:
Variable
Default
Description
MODELSCOPE_API_TIMEOUT
60
HTTP request timeout (seconds)
MODELSCOPE_API_CONNECT_TIMEOUT
10
HTTP connect timeout (seconds)
MODELSCOPE_API_MAX_RETRIES
5
Regular API retries; downloads and file listings use separate retry policies
MODELSCOPE_OPTIONS_CACHE_TTL
300
Seconds to cache the model/dataset enum option endpoints; 0 disables caching
MODELSCOPE_REPO_TREE_PAGE_TIMEOUT_SECONDS
15
Per-page listing timeout (seconds)
MODELSCOPE_REPO_TREE_PAGE_MAX_ATTEMPTS
4
Maximum attempts per listing page, including the initial request
MODELSCOPE_REPO_TREE_PAGE_RETRY_MAX_DELAY_SECONDS
8
Maximum listing retry delay (seconds)
MODELSCOPE_REPO_TREE_LIST_TIMEOUT_SECONDS
3600
Total repository listing time budget (seconds)
Download:
Variable
Default
Description
MODELSCOPE_DOWNLOAD_PARALLEL_WORKERS
1
Parallel range-download streams
MODELSCOPE_DOWNLOAD_PARALLEL_THRESHOLD_MB
500
Parallel download threshold (MB)
MODELSCOPE_DOWNLOAD_CHUNK_SIZE_MB
1
Streaming chunk size (MB)
MODELSCOPE_DOWNLOAD_PART_SIZE_MB
160
Parallel range chunk size (MB)
MODELSCOPE_DOWNLOAD_MAX_RETRIES
5
Single-layer transport retries; 0 disables them; integrity retries are separately bounded
MODELSCOPE_DOWNLOAD_TIMEOUT
60
Idle read timeout for streams and range parts, not the whole file (seconds)
MODELSCOPE_DOWNLOAD_TOTAL_TIMEOUT
0
Per-file time budget, including locks, probes, transfers, retries, and validation (seconds); 0 imposes no overall limit
MODELSCOPE_DOWNLOAD_MIN_BYTES_PER_SECOND
1024
Minimum rate per connection (B/s); 0 disables low-speed detection
MODELSCOPE_DOWNLOAD_LOW_SPEED_WINDOW_SECONDS
60
Minimum-rate observation window (seconds)
MODELSCOPE_DOWNLOAD_RETRY_MAX_DELAY_SECONDS
60
Maximum download Retry-After or backoff delay (seconds)
MODELSCOPE_DOWNLOAD_FILE_LOCK_TIMEOUT_SECONDS
600
Maximum wait for another process's file lock (seconds)
MODELSCOPE_DOWNLOAD_FILE_LOCK
true
File lock for multiprocess download safety
MODELSCOPE_DOWNLOAD_INTRA_CLOUD
true
Alibaba cloud intra-cloud acceleration
MODELSCOPE_DOWNLOAD_INTRA_CLOUD_REGION
(auto)
Override intra-cloud region ID
Upload:
Variable
Default
Description
MODELSCOPE_UPLOAD_MAX_CONCURRENT_WORKERS
min(8, cpu+4)
Default parallel worker threads
MODELSCOPE_UPLOAD_CACHE_ENABLED
true
Enable resumable upload cache; only committed files are skipped on a later run
MODELSCOPE_UPLOAD_IGNORE_FILE_PATTERN
—
File pattern excluded by legacy push_to_hub uploads
MODELSCOPE_UPLOAD_MAX_FILE_SIZE_MB
102400
Advisory single-file warning threshold (MB); uploads continue above it
MODELSCOPE_UPLOAD_MAX_FILE_COUNT
100000
Advisory total file-count warning threshold; uploads continue above it
Advisory total inline-file size warning threshold (MB)
MODELSCOPE_UPLOAD_LFS_FORCE_THRESHOLD
1MiB
Route larger non-metadata files through LFS; accepts byte-unit suffixes
MODELSCOPE_UPLOAD_COMMIT_BATCH_MAX_OPERATIONS
256
Target actions per commit, clamped to the server hard ceiling
MODELSCOPE_UPLOAD_COMMIT_MAX_INLINE_BYTES
8MiB
Estimated commit request-body budget used as the secondary batch constraint
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)
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.
Logging:
Variable
Default
Description
MODELSCOPE_LOG_LEVEL
INFO
SDK log level (DEBUG/INFO/WARNING/ERROR)
MODELSCOPE_NO_DEPRECATION_WARNINGS
—
Suppress deprecation warnings
Kernels:
Variable
Default
Description
MS_KERNELS_TRUSTED_PUBLISHERS
—
Comma-separated kernel publishers trusted in addition to the built-in allowlist (see Load kernels)
Old variable names (e.g. API_TIMEOUT, DOWNLOAD_RETRY_TIMES, UPLOAD_USE_CACHE) are
deprecated and remain temporarily supported. They emit a FutureWarning and will be removed
in a future version. Run ms-hub list --envs to see which deprecated names are active in your
environment.
Backward Compatibility
modelscope-hub provides a compatibility layer for code written against the old modelscope.hub API surface. The old SDK can delegate directly to modelscope_hub.compat:
from modelscope_hub.compat import snapshot_download, model_file_download
from modelscope_hub.compat import LegacyHubApi as HubApi
All legacy parameter names (allow_file_pattern, ignore_file_pattern, cookies, etc.) are accepted and mapped to the new implementation.
Behaviour changes when model/dataset writes moved to OpenAPI
Model and dataset creation and settings now use the /openapi/v1 endpoints.
Inputs those endpoints cannot express keep using the legacy ones, so existing
calls continue to work; three observable differences remain:
Change
Detail
Gated repositories in metadata
The historical Visibility enum is preserved. New OpenAPI "gated" responses map to Visibility.PRIVATE with gated=True, rather than leaking a raw string as in 0.5.1 against that response. Older payloads without visibility could instead be misclassified as PUBLIC from private: false; both parsing cases are handled.
Default license
When license is omitted the Hub applies its own default (apache-2.0) instead of the SDK sending Apache-2.0. Only affects calls that take the OpenAPI route.
LegacyHubApi.create_dataset(description=...)
The argument was previously accepted and then dropped; it is now sent.
Unchanged on purpose:
gated_mode=True / gated_mode=False keep the exact legacy request
(Visibility=PRIVATE plus ProtectedMode=1/2), including warn-and-ignore for
explicit public/internal visibility and implicit private for either boolean
when visibility is omitted. ms-hub create --gated/--no-gated stays unchanged.
High-level approval_mode, gated, visibility="gated" and string-valued
gated_mode are not supported. The removed request aliases must not leak into
legacy extra fields. Native OpenAPI payload/response fields remain unchanged.
delete_files() still commits deletions directly, so it keeps glob support
and has no 100-path ceiling.
visibility="internal", licenses outside the OpenAPI enum, a task on a
dataset, and extra request fields all still reach the legacy endpoint.
The AIGC creation path in modelscope_hub.compat
(create_model(aigc_model=...), create_model_tag(aigc_model=...)) is
untouched.
Development
git clone https://github.com/modelscope/modelscope_hub.git
cd modelscope_hub
make install # pip install -e ".[dev]"
make test # unit tests (no network)
make lint # ruff check
make typecheck # mypy
@Misc{modelscope-hub,
title = {modelscope-hub: The official Python client to connect with ModelScope Hub.},
author = {The ModelScope Team},
howpublished = {\url{https://github.com/modelscope/modelscope_hub}},
year = {2026}
}
Alternatives
Use instead of modelscope-hub: tools that do the same job, closest first.
Use together with modelscope-hub: extensions, drivers, servers and companion tools.
transformersPythie’s Index: 90Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.122.3M downloads/mo