mirror of
https://github.com/lemonade-sdk/lemonade.git
synced 2026-11-23 17:49:38 -10:00
feat: add modelscope besides huggingface (#2647)
* feat: add modelscope besides huggingface * fix: harden ModelScope errors and registry provenance
This commit is contained in:
1 parent
08d646f2a0
commit
1b3aa1a38d
33 files changed
+1773
-608
No files matched your search
@@ -627,6 +627,7 @@ set(SOURCES_CORE
|
||||
src/cpp/server/config_file.cpp
|
||||
src/cpp/server/directory_watcher.cpp
|
||||
src/cpp/server/model_manager.cpp
|
||||
src/cpp/server/model_registry.cpp
|
||||
src/cpp/server/hf_variants.cpp
|
||||
src/cpp/server/wrapped_server.cpp
|
||||
src/cpp/server/streaming_proxy.cpp
|
||||
@@ -2176,6 +2177,20 @@ if(EXISTS "${_MODEL_MANAGER_COLLECTION_VALIDATION_TEST_SRC}")
|
||||
add_test(NAME ModelManagerCollectionValidationTest COMMAND test_model_manager_collection_validation)
|
||||
endif()
|
||||
|
||||
# Remote model registry source parsing, cache namespaces, snapshot fingerprints,
|
||||
# and persistence of ModelScope provenance in ModelInfo.
|
||||
set(_MODEL_REGISTRY_TEST_SRC
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/test/cpp/test_model_registry.cpp"
|
||||
)
|
||||
if(BUILD_TESTING AND EXISTS "${_MODEL_REGISTRY_TEST_SRC}")
|
||||
add_executable(test_model_registry test/cpp/test_model_registry.cpp)
|
||||
target_link_libraries(test_model_registry PRIVATE lemonade-server-core)
|
||||
add_dependencies(test_model_registry copy_resources)
|
||||
|
||||
include(CTest)
|
||||
add_test(NAME ModelRegistryTest COMMAND test_model_registry)
|
||||
endif()
|
||||
|
||||
# Router-backed ClassifierServices wiring (issue #2384): binds the pure engine's
|
||||
# embed/run_classifier/chat lambdas to Router-style JSON calls.
|
||||
set(_ROUTING_CLASSIFIER_SERVICES_TEST_SRC
|
||||
|
||||
@@ -113,7 +113,7 @@ For hybrid setups, Lemonade can also route to any OpenAI-compatible cloud provid
|
||||
|
||||
Lemonade supports a wide variety of LLMs (**GGUF**, **FLM**, and **ONNX**), whisper, stable diffusion, etc. models across CPU, GPU, and NPU.
|
||||
|
||||
Use `lemonade pull` or the built-in **Model Manager** to download models. You can also import custom GGUF/ONNX models from Hugging Face.
|
||||
Use `lemonade pull` or the built-in **Model Manager** to download models. Custom GGUF/ONNX models can be pulled from Hugging Face or ModelScope, with their source retained for future updates.
|
||||
|
||||
**[Browse all built-in models →](https://lemonade-server.ai/models.html)**
|
||||
|
||||
@@ -475,7 +475,7 @@ Free code signing provided by [SignPath.io](https://signpath.io), certificate by
|
||||
- **Committers and reviewers**: [Maintainers](#maintainers) of this repo
|
||||
- **Approvers**: [Owners](https://github.com/orgs/lemonade-sdk/people?query=role%3Aowner)
|
||||
|
||||
**Privacy policy**: This program will not transfer any information to other networked systems unless specifically requested by the user or the person installing or operating it. When the user requests it, Lemonade downloads AI models from [Hugging Face Hub](https://huggingface.co/) (see their [privacy policy](https://huggingface.co/privacy)).
|
||||
**Privacy policy**: This program will not transfer any information to other networked systems unless specifically requested by the user or the person installing or operating it. When the user requests a model download or registry lookup, Lemonade may contact [Hugging Face Hub](https://huggingface.co/) (see their [privacy policy](https://huggingface.co/privacy)) or [ModelScope](https://modelscope.cn/), according to the model source selected by the user or packager.
|
||||
|
||||
## License and Attribution
|
||||
|
||||
@@ -488,6 +488,7 @@ This project is:
|
||||
- [kokoros](https://github.com/lucasjinreal/Kokoros)
|
||||
- [OnnxRuntime GenAI](https://github.com/microsoft/onnxruntime-genai)
|
||||
- [Hugging Face Hub](https://github.com/huggingface/huggingface_hub)
|
||||
- [ModelScope](https://github.com/modelscope/modelscope)
|
||||
- [OpenAI API](https://github.com/openai/openai-python)
|
||||
- [IRON/MLIR-AIE](https://github.com/Xilinx/mlir-aie)
|
||||
- and more...
|
||||
|
||||
@@ -189,10 +189,18 @@ function buildModelTableRows(name, details) {
|
||||
const checkpoint = parseCheckpoint(name, details);
|
||||
|
||||
if (checkpoint.repo) {
|
||||
const registrySource = details.registry_source
|
||||
|| (details.source === 'modelscope' || details.source === 'huggingface'
|
||||
? details.source
|
||||
: 'huggingface');
|
||||
const checkpointUrl = registrySource === 'modelscope'
|
||||
? `https://modelscope.cn/models/${escapeHtml(checkpoint.repo)}/summary`
|
||||
: `https://huggingface.co/${escapeHtml(checkpoint.repo)}`;
|
||||
rows.push({
|
||||
key: 'Checkpoint',
|
||||
value: `<a href="https://huggingface.co/${escapeHtml(checkpoint.repo)}" target="_blank" rel="noopener">${escapeHtml(checkpoint.repo)}</a>`
|
||||
value: `<a href="${checkpointUrl}" target="_blank" rel="noopener">${escapeHtml(checkpoint.repo)}</a>`
|
||||
});
|
||||
rows.push({ key: 'Model Source', value: registrySource === 'modelscope' ? 'ModelScope' : 'Hugging Face' });
|
||||
if (checkpoint.variant) {
|
||||
rows.push({ key: 'GGUF Variant', value: escapeHtml(checkpoint.variant) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Remote Model Registries
|
||||
|
||||
Lemonade supports Hugging Face and ModelScope as remote model registries. This document records the implementation contract so later providers can be added without reintroducing provider-specific assumptions.
|
||||
|
||||
## Source identity
|
||||
|
||||
Remote provenance is stored separately from local origin:
|
||||
|
||||
- `ModelInfo::source` describes a local origin such as `local_upload`, `local_path`, or `extra_models_dir`.
|
||||
- `ModelInfo::registry_source` identifies the remote registry: `huggingface` or `modelscope`.
|
||||
- The public registration field is `source`. For a remote model it is canonicalized and persisted as the registry name. `registry_source` is also accepted in exported/internal records.
|
||||
|
||||
Hugging Face is the default for backward compatibility. A model and all of its checkpoints have one registry source. Collection components inherit the collection source unless an inline component definition explicitly declares another source.
|
||||
|
||||
## Registry interface
|
||||
|
||||
`ModelRegistry` normalizes provider behavior into:
|
||||
|
||||
- repository file-tree discovery;
|
||||
- a stable local snapshot identifier;
|
||||
- provider-specific file download URLs;
|
||||
- provider-specific authentication headers.
|
||||
|
||||
Variant discovery and the main download engine consume this normalized representation. `download_from_manifest()` remains provider-independent.
|
||||
|
||||
## Cache contract
|
||||
|
||||
Both providers use the configured `models_dir` and the same runtime structure:
|
||||
|
||||
```text
|
||||
<repo-cache>/
|
||||
refs/main
|
||||
snapshots/<snapshot-id>/...
|
||||
.lemonade_registry.json
|
||||
```
|
||||
|
||||
Repository directory names are provider-qualified:
|
||||
|
||||
- Hugging Face: `models--org--repo`
|
||||
- ModelScope: `modelscope--models--org--repo`
|
||||
|
||||
This prevents collisions while allowing existing snapshot resolution, deletion, and cache cleanup code to stay shared.
|
||||
|
||||
Hugging Face uses the immutable commit SHA returned by the Hub. ModelScope normally downloads a mutable branch/tag such as `master`; Lemonade therefore derives `snapshot-id` from the normalized file tree. The fingerprint changes when paths, sizes, or available hashes change, allowing update checks to work without pretending that the branch name is immutable. A branch can still move while a download is in progress because ModelScope does not provide the same commit-pinned download contract as Hugging Face.
|
||||
|
||||
## Authentication and endpoints
|
||||
|
||||
- Hugging Face: `HF_TOKEN`, optional `HF_ENDPOINT`
|
||||
- ModelScope: `MODELSCOPE_API_TOKEN` (or compatibility alias `MODELSCOPE_ACCESS_TOKEN`), optional `MODELSCOPE_ENDPOINT`
|
||||
|
||||
ModelScope requests send both Bearer authorization and the `m_session_id` cookie used by its legacy model endpoints.
|
||||
|
||||
## v1 product scope
|
||||
|
||||
The CLI and API support repository IDs, variants, and ModelScope model URLs. The desktop manual-registration form exposes a source selector and source-aware model links. The desktop marketplace search remains Hugging Face-only in v1; server-side multi-registry search can be introduced later without changing persisted model records or cache semantics.
|
||||
@@ -22,7 +22,7 @@ Contents:
|
||||
|
||||
### Sharing Models With Other Apps
|
||||
|
||||
The default value for `models_dir` is `"auto"`, which means "respect my user's `HF_HOME` and `HF_HUB_CACHE` environment variables, in accordance with the Hugging Face Hub standard." If those environment variables are not set, it defaults to `~/.cache/huggingface/hub`.
|
||||
The default value for `models_dir` is `"auto"`, which means "respect my user's `HF_HOME` and `HF_HUB_CACHE` environment variables, in accordance with the Hugging Face Hub standard." If those environment variables are not set, it defaults to `~/.cache/huggingface/hub`. This directory is Lemonade's shared model-hub cache for both Hugging Face and ModelScope.
|
||||
|
||||
The benefit of `models_dir="auto"` is that models are placed in a common location on your user's drive, which means they can be shared across applications. However, the downside is that other applications could manage models that your app relies on.
|
||||
|
||||
@@ -66,21 +66,33 @@ You can test whether models end up at the desired location with a pull command:
|
||||
ls models
|
||||
```
|
||||
|
||||
Which should return:
|
||||
Which should return a Hugging Face cache directory:
|
||||
|
||||
```
|
||||
models--unsloth--Qwen3-0.6B-GGUF
|
||||
```
|
||||
|
||||
> Note: if you need to use a GGUF LLM that is not available on huggingface.co, you can use GGUF files acquired through other means using the `extra_models_dir` configuration discussed in [Importing Models to `lemond`](#importing-models-to-lemond).
|
||||
A ModelScope pull uses the same `models_dir` but a separate namespace:
|
||||
|
||||
```bash
|
||||
./lemonade pull --source modelscope Qwen/Qwen3-0.6B-GGUF
|
||||
```
|
||||
|
||||
```
|
||||
modelscope--models--Qwen--Qwen3-0.6B-GGUF
|
||||
```
|
||||
|
||||
Both layouts contain `snapshots/` and `refs/main`, so runtime resolution, deletion, and bundling use one cache model without allowing identically named repositories on the two hubs to collide.
|
||||
|
||||
> Note: if a GGUF is on neither supported registry, use `extra_models_dir` as described in [Importing Models to `lemond`](#importing-models-to-lemond).
|
||||
|
||||
### Importing Models to `lemond`
|
||||
|
||||
You may want to share models within your app if `lemond` is not your only inference provider for GGUF LLMs.
|
||||
|
||||
There is also a scenario where `lemond`'s Hugging Face Hub-based `pull` methodology is not able to obtain the models you need, for example:
|
||||
- Hugging Face Hub is blocked in your users' locality.
|
||||
- Your GGUF files are not on Hugging Face Hub.
|
||||
There are also scenarios where registry pulls cannot obtain the models you need, for example:
|
||||
- Neither Hugging Face nor ModelScope is reachable in your deployment.
|
||||
- Your GGUF files are not published on either registry.
|
||||
|
||||
To address all of these scenarios, `lemond` can recursively search a directory for GGUF files using the `extra_models_dir` configuration.
|
||||
|
||||
@@ -180,6 +192,7 @@ For example, if you wanted to add [OmniCoder-9B](https://huggingface.co/Tesslate
|
||||
|
||||
```
|
||||
"OmniCoder-9B-GGUF": {
|
||||
"source": "huggingface",
|
||||
"checkpoint": "Tesslate/OmniCoder-9B-GGUF:omnicoder-9b-q4_k_m.gguf",
|
||||
"recipe": "llamacpp",
|
||||
"suggested": true,
|
||||
@@ -192,6 +205,8 @@ For example, if you wanted to add [OmniCoder-9B](https://huggingface.co/Tesslate
|
||||
|
||||
You can learn more in the [Custom Models](../guide/configuration/custom-models.md) guide, including how to enable your users to register their own custom models at runtime.
|
||||
|
||||
Set `"source": "modelscope"` for curated entries hosted on ModelScope. Lemonade preserves that field in its model metadata and uses it for every subsequent download and update check. The default is `huggingface`, so existing registry files require no migration.
|
||||
|
||||
### Per-Model Load Options
|
||||
|
||||
You may want to customize how specific models will load on your user's system. You can do this with the `recipe_options.json` file. Learn more in the [Custom Models](../guide/configuration/custom-models.md) guide.
|
||||
|
||||
+3
-2
@@ -46,7 +46,7 @@ The `lemonade` CLI is the primary tool for interacting with Lemonade Server from
|
||||
| Command | Description |
|
||||
|---------------------|-------------------------------------|
|
||||
| `list` | List all available models. |
|
||||
| `pull MODEL_OR_CHECKPOINT` | Download a registered model, pull a Hugging Face checkpoint, or manually register a `user.*` model with `--checkpoint`/`--recipe`. See command options [below](#options-for-pull). |
|
||||
| `pull MODEL_OR_CHECKPOINT` | Download a registered model, pull a Hugging Face or ModelScope checkpoint, or manually register a `user.*` model with `--checkpoint`/`--recipe`. See command options [below](#options-for-pull). |
|
||||
| `import JSON_FILE` | Import a model from a JSON configuration file. See command options [below](#options-for-import). |
|
||||
| `delete MODEL_NAME` | Delete a model and its files from local storage. |
|
||||
| `load MODEL_NAME` | Load a model for inference. See command options [below](#options-for-load). |
|
||||
@@ -190,7 +190,8 @@ lemonade pull user.MyModel --checkpoint main org/model:Q4_0 --recipe llamacpp
|
||||
|
||||
| Option | Description | Required |
|
||||
|--------|-------------|----------|
|
||||
| `MODEL_OR_CHECKPOINT` | Registered model name, or `owner/repo[:variant]` Hugging Face checkpoint | Yes |
|
||||
| `MODEL_OR_CHECKPOINT` | Registered model name, or `owner/repo[:variant]` Hugging Face/ModelScope checkpoint | Yes |
|
||||
| `--source` | Remote registry for checkpoint pulls: `huggingface` (default) or `modelscope`; direct hub URLs are auto-detected | No |
|
||||
| `--checkpoint TYPE CHECKPOINT` | Manual registration: add a checkpoint entry. Repeat for multi-component models such as `main` + `mmproj` or `main` + `vae`. | No |
|
||||
| `--recipe RECIPE` | Manual registration: recipe to associate with the new `user.*` model (`llamacpp`, `flm`, `ryzenai-llm`, `vllm`, `whispercpp`, `sd-cpp`, `kokoro`, `collection.omni`) | No |
|
||||
| `--label LABEL` | Manual registration: add a label to the new model. Repeatable. Valid: `coding`, `embeddings`, `hot`, `mtp`, `reasoning`, `reranking`, `tool-calling`, `vision` | No |
|
||||
|
||||
@@ -4,44 +4,59 @@ This guide explains every supported way to add a custom model to Lemonade Server
|
||||
|
||||
## Choose a Workflow
|
||||
|
||||
### Pull a Hugging Face model
|
||||
### Pull from Hugging Face or ModelScope
|
||||
|
||||
For most Hugging Face GGUFs, use the repo id directly:
|
||||
Hugging Face remains the default registry, so existing commands keep working unchanged:
|
||||
|
||||
```bash
|
||||
lemonade pull org/repo
|
||||
```
|
||||
|
||||
Lemonade fetches the repo, lists the available quantizations and sharded folder variants, auto-detects `mmproj-*.gguf` files for vision models, infers labels (`vision`/`embeddings`/`reranking`) from the repo id, and presents an interactive variant menu.
|
||||
|
||||
To skip the menu, append a variant:
|
||||
|
||||
```bash
|
||||
lemonade pull org/repo:Q4_K_M
|
||||
```
|
||||
|
||||
Choose ModelScope explicitly when the model is hosted or mirrored there:
|
||||
|
||||
```bash
|
||||
lemonade pull --source modelscope org/repo
|
||||
lemonade pull --source modelscope org/repo:Q4_K_M
|
||||
```
|
||||
|
||||
Full model URLs are accepted and select the registry automatically:
|
||||
|
||||
```bash
|
||||
lemonade pull https://huggingface.co/unsloth/Qwen3-8B-GGUF
|
||||
lemonade pull https://modelscope.cn/models/Qwen/Qwen3-8B-GGUF
|
||||
```
|
||||
|
||||
For supported repository layouts, Lemonade lists GGUF quantizations and sharded variants, auto-detects `mmproj-*.gguf` files, infers common labels, and presents the same interactive variant menu for either registry.
|
||||
|
||||
Examples:
|
||||
|
||||
```bash
|
||||
# Interactive GGUF variant menu
|
||||
lemonade pull unsloth/Qwen3-8B-GGUF
|
||||
|
||||
# Specific GGUF variant
|
||||
# Hugging Face (default)
|
||||
lemonade pull unsloth/Qwen3-8B-GGUF:Q4_K_M
|
||||
|
||||
# Vision model with mmproj auto-detection
|
||||
lemonade pull ggml-org/gemma-3-4b-it-GGUF:Q4_K_M
|
||||
|
||||
# Sharded variant
|
||||
lemonade pull unsloth/Qwen3-30B-A3B-GGUF:Q4_K_M
|
||||
# ModelScope
|
||||
lemonade pull --source modelscope Qwen/Qwen3-8B-GGUF:Q4_K_M
|
||||
```
|
||||
|
||||
The selected source is persisted with the model registration. Variant discovery, downloads, display links, cache lookup, deletion, and future update checks therefore continue to use the same registry. All checkpoints belonging to one model use one registry source.
|
||||
|
||||
Private repositories can be authenticated with `HF_TOKEN` for Hugging Face or `MODELSCOPE_API_TOKEN` for ModelScope. `MODELSCOPE_ACCESS_TOKEN` is also accepted as a compatibility alias. Custom endpoints can be supplied with `HF_ENDPOINT` or `MODELSCOPE_ENDPOINT`.
|
||||
|
||||
#### Cache and revision behavior
|
||||
|
||||
Both registries share Lemonade's configured `models_dir`. Hugging Face keeps its established `models--org--repo` directory names. ModelScope uses the collision-free `modelscope--models--org--repo` namespace. Under either directory Lemonade uses the same `snapshots/<id>` and `refs/main` structure consumed by runtime resolution and cache cleanup.
|
||||
|
||||
Hugging Face snapshots use the immutable commit returned by the Hub. ModelScope downloads use its branch/tag revision (normally `master`); Lemonade derives a stable local snapshot fingerprint from the normalized remote file tree so a changed ModelScope repository is detected even when the branch name stays the same.
|
||||
|
||||
The desktop app's manual model form exposes the same source selector. The browse/search catalog remains Hugging Face-backed in this first version; ModelScope models can be added by repository ID through the manual form, CLI, or API.
|
||||
|
||||
### Register with explicit CLI flags
|
||||
|
||||
Use a `user.*` name plus `--checkpoint` and `--recipe` when you need full control: multiple checkpoints, a non-default recipe, or custom labels.
|
||||
|
||||
```bash
|
||||
lemonade pull user.NAME --checkpoint TYPE CHECKPOINT --recipe RECIPE [--label LABEL ...]
|
||||
lemonade pull user.NAME --source SOURCE --checkpoint TYPE CHECKPOINT --recipe RECIPE [--label LABEL ...]
|
||||
```
|
||||
|
||||
Examples:
|
||||
@@ -70,6 +85,7 @@ Supported registration flags:
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--source SOURCE` | Remote registry for every checkpoint in this model: `huggingface` (default) or `modelscope`. |
|
||||
| `--checkpoint TYPE CHECKPOINT` | Add a checkpoint entry. Repeat for multi-file models such as `main` + `mmproj` or `main` + `vae`. |
|
||||
| `--recipe RECIPE` | Recipe to associate with the new `user.*` model. Common values: <!-- BEGIN GENERATED: recipe-values -->`llamacpp`, `whispercpp`, `moonshine`, `kokoro`, `sd-cpp`, `flm`, `ryzenai-llm`, `vllm`, `thinksound`, `acestep`, `trellis`, `openmoss`, `collection.omni`<!-- END GENERATED: recipe-values -->. |
|
||||
| `--label LABEL` | Add a label to the new model. Repeatable. Valid labels include `coding`, `embeddings`, `hot`, `mtp`, `reasoning`, `reranking`, `tool-calling`, `vision`. |
|
||||
@@ -116,7 +132,7 @@ If a component model is deleted later, the Omni Model entry remains registered b
|
||||
|
||||
The editor also exposes a **System Prompt** field, pre-filled with the shipped default so you can see the text you'd be replacing. Edit it to override the default for this collection only; the override stays a *template* — both the `{tool_list}` and `{tool_guidance}` placeholders are **required** in any custom prompt and the editor blocks save/export when either is missing, because the server expands them at runtime based on which components are present. A collection whose textarea matches the default — or that has been reset via **Reset to default** — stores no override and keeps tracking whatever the global default is at runtime.
|
||||
|
||||
### Share a collection: export, import, and Hugging Face
|
||||
### Share a collection: export, import, and model registries
|
||||
|
||||
`lemonade export <collection>` (and the desktop app's Export button) writes a *collection file*: the
|
||||
collection's [`/v1/models/{model_id}`](../../api/openai.md#get-v1modelsmodel_id) object normalized into
|
||||
@@ -132,10 +148,12 @@ The same file works, verbatim, in three places:
|
||||
- `lemonade import <CollectionName>.json` on the CLI (or **File > New Omni Model > From JSON** in the
|
||||
desktop app).
|
||||
- `POST /v1/pull` with the file contents as the request body.
|
||||
- Uploaded to a Hugging Face model repo **named after the collection**, so that the repo contains
|
||||
`<RepoName>.json`. `lemonade pull <org>/<repo>` looks for the manifest named after the repo,
|
||||
then registers and downloads everything in it. The built-in `LMX-Omni-*` collections are
|
||||
distributed this way.
|
||||
- Uploaded to a Hugging Face or ModelScope model repo **named after the collection**, so that the
|
||||
repo contains `<RepoName>.json`. Pull it with the corresponding source, for example
|
||||
`lemonade pull <org>/<repo>` or `lemonade pull --source modelscope <org>/<repo>`. Lemonade
|
||||
downloads the manifest, preserves its registry provenance, then registers and downloads every
|
||||
component. Inline component definitions inherit the collection source unless they explicitly
|
||||
declare their own source.
|
||||
|
||||
On import, component names that are already registered keep their local definition (differences from
|
||||
the embedded definition are logged as warnings); unknown components are registered as `user.*` models
|
||||
@@ -177,7 +195,7 @@ Example collection file:
|
||||
|
||||
### Register via API
|
||||
|
||||
The `/v1/pull` endpoint accepts the same model registration fields as the CLI. Use this when integrating Lemonade into another app or script:
|
||||
The `/v1/pull` endpoint accepts the same model registration fields as the CLI. Set `source` to `huggingface` (the default) or `modelscope`; the server canonicalizes and persists it for later update checks. Use this when integrating Lemonade into another app or script:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:13305/v1/pull \
|
||||
@@ -185,6 +203,7 @@ curl -X POST http://localhost:13305/v1/pull \
|
||||
-d '{
|
||||
"model_name": "user.MyModel",
|
||||
"recipe": "llamacpp",
|
||||
"source": "modelscope",
|
||||
"checkpoint": "org/repo:Q4_0"
|
||||
}'
|
||||
```
|
||||
@@ -297,6 +316,7 @@ This file contains a JSON object where each key is a model name and each value d
|
||||
```json
|
||||
{
|
||||
"MyCustomModel": {
|
||||
"source": "modelscope",
|
||||
"checkpoint": "org/repo-name:filename.gguf",
|
||||
"recipe": "llamacpp",
|
||||
"size": 3.5
|
||||
@@ -308,12 +328,13 @@ This file contains a JSON object where each key is a model name and each value d
|
||||
|
||||
| Field | Required | Type | Description |
|
||||
|-------|----------|------|-------------|
|
||||
| `checkpoint` | Yes* | String | HuggingFace checkpoint in `org/repo` or `org/repo:variant` format. Use `org/repo:filename.gguf` for GGUF models. |
|
||||
| `source` | No | String | Remote registry: `huggingface` (default) or `modelscope`. Persisted and used for variants, downloads, cache paths, links, and update checks. |
|
||||
| `checkpoint` | Yes* | String | Registry checkpoint in `org/repo` or `org/repo:variant` format. Use `org/repo:filename.gguf` for GGUF models. |
|
||||
| `checkpoints` | Yes* | Object | Alternative to `checkpoint` for models with multiple files. See [Multi-file models](#multi-file-models). |
|
||||
| `recipe` | Yes | String | Backend engine to use. One of: `llamacpp`, `whispercpp`, `moonshine`, `sd-cpp`, `kokoro`, `ryzenai-llm`, `flm`, `collection.omni`. |
|
||||
| `components` | Yes** | Array | Components for a collection. Required when `recipe: "collection.omni"`. See [Collections](#collections). |
|
||||
| `size` | No | Number | Model size in GB. Informational only — displayed in the UI and used for RAM filtering. |
|
||||
| `mmproj` | No | String | Filename of the multimodal projector file for llamacpp vision models (must be in the same HuggingFace repo as the checkpoint). This is a **top-level field**, not inside `checkpoints`. |
|
||||
| `mmproj` | No | String | Filename of the multimodal projector file for llamacpp vision models (must be in the same registry repo as the checkpoint). This is a **top-level field**, not inside `checkpoints`. |
|
||||
| `image_defaults` | No | Object | Default image generation parameters for `sd-cpp` models. See [Image defaults](#image-defaults). |
|
||||
|
||||
\* Either `checkpoint` or `checkpoints` is required, but not both.
|
||||
@@ -428,6 +449,7 @@ This file configures per-model runtime settings. Each key is a **canonical model
|
||||
```json
|
||||
{
|
||||
"Qwen2.5-Coder-1.5B-Instruct": {
|
||||
"source": "huggingface",
|
||||
"checkpoint": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF:qwen2.5-coder-1.5b-instruct-q4_k_m.gguf",
|
||||
"recipe": "llamacpp",
|
||||
"size": 1.0
|
||||
|
||||
@@ -2,10 +2,13 @@ import React, { useState, useEffect } from 'react';
|
||||
import { useSystem } from './hooks/useSystem';
|
||||
import { COLLECTION_OMNI_MODEL_RECIPE, RECIPE_DISPLAY_NAMES } from './utils/recipeNames';
|
||||
|
||||
export type ModelRegistrySource = 'huggingface' | 'modelscope';
|
||||
|
||||
export interface AddModelInitialValues {
|
||||
name: string;
|
||||
checkpoint: string;
|
||||
recipe: string;
|
||||
source?: ModelRegistrySource;
|
||||
checkpoints?: Record<string, string>;
|
||||
mmprojOptions?: string[];
|
||||
labels?: string[];
|
||||
@@ -18,6 +21,7 @@ export interface ModelInstallData {
|
||||
name: string;
|
||||
checkpoint: string;
|
||||
recipe: string;
|
||||
source: ModelRegistrySource;
|
||||
checkpoints?: Record<string, string>;
|
||||
mmproj?: string;
|
||||
labels?: string[];
|
||||
@@ -84,10 +88,25 @@ const RECIPE_EXAMPLES: Record<string, RecipeExample> = {
|
||||
|
||||
const getRecipeExample = (recipe: string): RecipeExample => RECIPE_EXAMPLES[recipe] ?? RECIPE_EXAMPLES.llamacpp;
|
||||
|
||||
const createEmptyForm = (initial?: AddModelInitialValues) => ({
|
||||
type AddModelFormState = {
|
||||
name: string;
|
||||
checkpoint: string;
|
||||
recipe: string;
|
||||
source: ModelRegistrySource;
|
||||
textEncoderCheckpoint: string;
|
||||
vaeCheckpoint: string;
|
||||
mmproj: string;
|
||||
reasoning: boolean;
|
||||
vision: boolean;
|
||||
embedding: boolean;
|
||||
reranking: boolean;
|
||||
};
|
||||
|
||||
const createEmptyForm = (initial?: AddModelInitialValues): AddModelFormState => ({
|
||||
name: initial?.name ?? '',
|
||||
checkpoint: initial?.checkpoint ?? initial?.checkpoints?.main ?? '',
|
||||
recipe: initial?.recipe ?? 'llamacpp',
|
||||
source: initial?.source ?? 'huggingface',
|
||||
textEncoderCheckpoint: initial?.checkpoints?.text_encoder ?? '',
|
||||
vaeCheckpoint: initial?.checkpoints?.vae ?? '',
|
||||
mmproj: '',
|
||||
@@ -131,7 +150,9 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
setError(null);
|
||||
}, [initialValues]);
|
||||
|
||||
const handleChange = (field: string, value: string | boolean) => {
|
||||
const handleChange = <K extends keyof AddModelFormState>(
|
||||
field: K, value: AddModelFormState[K]
|
||||
) => {
|
||||
setForm(prev => ({ ...prev, [field]: value }));
|
||||
setError(null);
|
||||
};
|
||||
@@ -140,6 +161,7 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
const name = form.name.trim();
|
||||
const checkpoint = form.checkpoint.trim();
|
||||
const recipe = form.recipe.trim();
|
||||
const source = form.source;
|
||||
const textEncoderCheckpoint = form.textEncoderCheckpoint.trim();
|
||||
const vaeCheckpoint = form.vaeCheckpoint.trim();
|
||||
const hasSdComponents = Boolean(textEncoderCheckpoint || vaeCheckpoint);
|
||||
@@ -157,7 +179,7 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
return;
|
||||
}
|
||||
if (recipe === 'sd-cpp' && !hasRepoRelativeFilePath(checkpoint)) {
|
||||
setError('StableDiffusion.cpp checkpoints must include the full file path relative to the Hugging Face repo, for example repo/model:path/to/model.safetensors or repo/model:path/to/model.gguf.');
|
||||
setError('StableDiffusion.cpp checkpoints must include the full file path relative to the selected registry repo, for example repo/model:path/to/model.safetensors or repo/model:path/to/model.gguf.');
|
||||
return;
|
||||
}
|
||||
if (recipe !== 'sd-cpp' && isGgufCheckpoint(checkpoint) && !checkpoint.includes(':')) {
|
||||
@@ -165,7 +187,7 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
return;
|
||||
}
|
||||
if (recipe === 'vllm' && isGgufCheckpoint(checkpoint)) {
|
||||
setError('vLLM checkpoints should use a Hugging Face model repo, not a GGUF file or GGUF repo.');
|
||||
setError('vLLM checkpoints should use a model repository, not a GGUF file or GGUF repo.');
|
||||
return;
|
||||
}
|
||||
if (recipe === 'sd-cpp' && hasSdComponents && (!textEncoderCheckpoint || !vaeCheckpoint)) {
|
||||
@@ -182,6 +204,7 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
onInstall({
|
||||
name,
|
||||
checkpoint,
|
||||
source,
|
||||
checkpoints: recipe === 'sd-cpp' && hasSdComponents
|
||||
? { main: checkpoint, text_encoder: textEncoderCheckpoint, vae: vaeCheckpoint }
|
||||
: undefined,
|
||||
@@ -262,14 +285,31 @@ const AddModelPanel: React.FC<AddModelPanelProps> = ({ onClose, onInstall, initi
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-section">
|
||||
<label className="form-label" title="Remote registry used for downloads, variants, caching, and update checks">
|
||||
Model source
|
||||
</label>
|
||||
<select
|
||||
className="form-input form-select"
|
||||
value={form.source}
|
||||
onChange={(e) => handleChange('source', e.target.value as ModelRegistrySource)}
|
||||
>
|
||||
<option value="huggingface">Hugging Face</option>
|
||||
<option value="modelscope">ModelScope</option>
|
||||
</select>
|
||||
<span className="settings-description">
|
||||
Lemonade stores this source with the model so future updates use the same registry.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="form-section">
|
||||
<label
|
||||
className="form-label"
|
||||
title={isSdCpp
|
||||
? 'Hugging Face repo and exact model file path relative to the repo'
|
||||
? 'Repository and exact model file path relative to the selected registry'
|
||||
: form.recipe === 'vllm'
|
||||
? 'Hugging Face model repository for vLLM; do not use GGUF checkpoints'
|
||||
: 'Hugging Face model path, for example repo/model or repo/model:variant'}
|
||||
? 'Model repository for vLLM; do not use GGUF checkpoints'
|
||||
: 'Registry model path, for example repo/model or repo/model:variant'}
|
||||
>
|
||||
{isSdCpp ? 'Main checkpoint' : 'Checkpoint'}
|
||||
</label>
|
||||
|
||||
@@ -227,6 +227,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({ isVisible, width }) => {
|
||||
checkpoint: data.checkpoint,
|
||||
checkpoints: data.checkpoints,
|
||||
recipe: data.recipe,
|
||||
source: data.source,
|
||||
mmproj: data.mmproj,
|
||||
labels: data.labels,
|
||||
reasoning: data.reasoning,
|
||||
|
||||
@@ -1098,7 +1098,10 @@ const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
const matchesCheckpoint = (info: ModelInfo | undefined): boolean => {
|
||||
if (!info || !checkpoint) return false;
|
||||
return info.checkpoint === checkpoint || info.checkpoints?.main === checkpoint;
|
||||
const registrySource = info.registry_source
|
||||
?? (info.source === 'modelscope' || info.source === 'huggingface' ? info.source : 'huggingface');
|
||||
return registrySource === 'huggingface'
|
||||
&& (info.checkpoint === checkpoint || info.checkpoints?.main === checkpoint);
|
||||
};
|
||||
|
||||
const suggestedName = backend.suggestedName || modelId.split('/').pop() || modelId;
|
||||
@@ -1145,6 +1148,7 @@ const [searchQuery, setSearchQuery] = useState('');
|
||||
handleDownloadModel(modelName, {
|
||||
checkpoint,
|
||||
recipe: backend.recipe,
|
||||
source: 'huggingface',
|
||||
mmproj,
|
||||
labels: Array.from(labels),
|
||||
vision: labels.has('vision'),
|
||||
@@ -2075,6 +2079,7 @@ const [searchQuery, setSearchQuery] = useState('');
|
||||
name: resolveHfModelName(hfModel.id, backend, checkpoint),
|
||||
checkpoint,
|
||||
recipe: backend.recipe,
|
||||
source: 'huggingface',
|
||||
mmprojOptions: backend.mmprojFiles,
|
||||
labels,
|
||||
vision: labels.includes('vision') || (backend.mmprojFiles?.length ?? 0) > 0,
|
||||
|
||||
@@ -140,7 +140,15 @@ const ModelOptionsModal: React.FC<SettingsModalProps> = ({ isOpen, onCancel, onS
|
||||
setModelInfo({ ...data });
|
||||
|
||||
const checkpoint = typeof data.checkpoint === 'string' ? data.checkpoint : '';
|
||||
setModelUrl(checkpoint ? `https://huggingface.co/${checkpoint.replace(/:.+$/, '')}` : '');
|
||||
const repoId = checkpoint.replace(/:.+$/, '');
|
||||
const registrySource = data.registry_source
|
||||
?? (data.source === 'modelscope' || data.source === 'huggingface'
|
||||
? data.source
|
||||
: 'huggingface');
|
||||
const registryUrl = registrySource === 'modelscope'
|
||||
? `https://modelscope.cn/models/${repoId}/summary`
|
||||
: `https://huggingface.co/${repoId}`;
|
||||
setModelUrl(checkpoint ? registryUrl : '');
|
||||
|
||||
const recipe = data.recipe as string;
|
||||
const recipeOptions = data.recipe_options ?? {};
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface ModelRegistrationData {
|
||||
checkpoints?: Record<string, string>;
|
||||
components?: string[];
|
||||
recipe: string;
|
||||
source?: 'huggingface' | 'modelscope';
|
||||
mmproj?: string;
|
||||
labels?: string[];
|
||||
reasoning?: boolean;
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface ModelInfo {
|
||||
cost_output_per_million?: number;
|
||||
mmproj?: string;
|
||||
source?: string;
|
||||
registry_source?: 'huggingface' | 'modelscope';
|
||||
model_name?: string;
|
||||
reasoning?: boolean;
|
||||
vision?: boolean;
|
||||
@@ -124,6 +125,11 @@ const normalizeModelInfo = (info: unknown): ModelInfo | null => {
|
||||
normalized.source = source;
|
||||
}
|
||||
|
||||
const registrySource = info['registry_source'];
|
||||
if (registrySource === 'huggingface' || registrySource === 'modelscope') {
|
||||
normalized.registry_source = registrySource;
|
||||
}
|
||||
|
||||
const modelName = info['model_name'];
|
||||
if (typeof modelName === 'string' && modelName) {
|
||||
normalized.model_name = modelName;
|
||||
@@ -216,6 +222,10 @@ const fetchBuiltInModelsFromAPI = async (): Promise<ModelsData> => {
|
||||
modelInfo.source = model.source;
|
||||
}
|
||||
|
||||
if (model.registry_source === 'huggingface' || model.registry_source === 'modelscope') {
|
||||
modelInfo.registry_source = model.registry_source;
|
||||
}
|
||||
|
||||
if (typeof model.model_name === 'string' && model.model_name) {
|
||||
modelInfo.model_name = model.model_name;
|
||||
}
|
||||
@@ -310,6 +320,8 @@ const EXPORT_KNOWN_KEYS = new Set([
|
||||
'recipe',
|
||||
'recipe_options',
|
||||
'routing',
|
||||
'source',
|
||||
'registry_source',
|
||||
'size',
|
||||
'system_prompt',
|
||||
]);
|
||||
@@ -324,6 +336,33 @@ const toExportEntry = (raw: Record<string, unknown>): Record<string, unknown> =>
|
||||
if (isRecord(entry.checkpoints) && 'checkpoint' in entry) {
|
||||
delete entry.checkpoint;
|
||||
}
|
||||
|
||||
// Preserve only portable remote provenance. Local origins refer to paths on
|
||||
// the exporting machine and must not be replayed on import.
|
||||
const publicSource = typeof raw.source === 'string' ? raw.source.toLowerCase() : '';
|
||||
const explicitRegistry = typeof raw.registry_source === 'string'
|
||||
? raw.registry_source.toLowerCase()
|
||||
: '';
|
||||
const isRemoteSource = (value: string): value is 'huggingface' | 'modelscope' =>
|
||||
value === 'huggingface' || value === 'modelscope';
|
||||
|
||||
if (publicSource && !isRemoteSource(publicSource)) {
|
||||
delete entry.source;
|
||||
delete entry.registry_source;
|
||||
} else {
|
||||
const registrySource = isRemoteSource(publicSource)
|
||||
? publicSource
|
||||
: isRemoteSource(explicitRegistry)
|
||||
? explicitRegistry
|
||||
: '';
|
||||
if (registrySource) {
|
||||
entry.source = registrySource;
|
||||
entry.registry_source = registrySource;
|
||||
} else {
|
||||
delete entry.source;
|
||||
delete entry.registry_source;
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
};
|
||||
|
||||
|
||||
@@ -93,6 +93,10 @@ set(COMMON_SOURCES
|
||||
../server/utils/path_utils.cpp
|
||||
../server/utils/json_utils.cpp
|
||||
../server/utils/http_client.cpp
|
||||
# recipe_import.cpp persists and validates remote registry provenance.
|
||||
# Compile the provider implementation into the standalone CLI as well; the
|
||||
# CLI does not link lemonade-server-core, where this source is otherwise built.
|
||||
../server/model_registry.cpp
|
||||
agent_launcher.cpp
|
||||
agent_config_file.cpp
|
||||
opencode_profile.cpp
|
||||
|
||||
+75
-16
@@ -139,17 +139,51 @@ std::string normalize_user_model_name(std::string name) {
|
||||
return prefix + name;
|
||||
}
|
||||
|
||||
std::string strip_huggingface_url_prefix(const std::string& arg) {
|
||||
static const std::string prefix = "https://huggingface.co/";
|
||||
if (arg.rfind(prefix, 0) == 0) {
|
||||
return arg.substr(prefix.size());
|
||||
std::string normalize_source(std::string source) {
|
||||
source = to_lower(std::move(source));
|
||||
if (source.empty() || source == "hf" || source == "huggingface") return "huggingface";
|
||||
if (source == "ms" || source == "modelscope") return "modelscope";
|
||||
return source;
|
||||
}
|
||||
|
||||
std::string strip_query_fragment(std::string value) {
|
||||
const size_t pos = value.find_first_of("?#");
|
||||
if (pos != std::string::npos) value.resize(pos);
|
||||
while (!value.empty() && value.back() == '/') value.pop_back();
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string first_repo_segments(const std::string& path) {
|
||||
const size_t slash = path.find('/');
|
||||
if (slash == std::string::npos) return path;
|
||||
const size_t second = path.find('/', slash + 1);
|
||||
return second == std::string::npos ? path : path.substr(0, second);
|
||||
}
|
||||
|
||||
std::string normalize_registry_url(const std::string& arg,
|
||||
std::string& source) {
|
||||
static const std::vector<std::pair<std::string, std::string>> prefixes = {
|
||||
{"https://huggingface.co/", "huggingface"},
|
||||
{"http://huggingface.co/", "huggingface"},
|
||||
{"https://modelscope.cn/models/", "modelscope"},
|
||||
{"https://www.modelscope.cn/models/", "modelscope"},
|
||||
{"http://modelscope.cn/models/", "modelscope"},
|
||||
{"http://www.modelscope.cn/models/", "modelscope"},
|
||||
{"https://modelscope.ai/models/", "modelscope"},
|
||||
{"https://www.modelscope.ai/models/", "modelscope"},
|
||||
};
|
||||
for (const auto& [prefix, detected] : prefixes) {
|
||||
if (arg.rfind(prefix, 0) != 0) continue;
|
||||
source = detected;
|
||||
std::string path = strip_query_fragment(arg.substr(prefix.size()));
|
||||
return first_repo_segments(path);
|
||||
}
|
||||
return arg;
|
||||
return strip_query_fragment(arg);
|
||||
}
|
||||
|
||||
void split_checkpoint_variant(const std::string& arg,
|
||||
std::string& checkpoint, std::string& variant) {
|
||||
// HF repo ids never contain ':', so split on the last ':'.
|
||||
// Supported registry repo ids never contain ':', so split on the last ':'.
|
||||
size_t pos = arg.rfind(':');
|
||||
if (pos == std::string::npos) {
|
||||
checkpoint = arg;
|
||||
@@ -172,34 +206,49 @@ std::string format_variant_label(const json& v) {
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string normalize_huggingface_checkpoint_arg(const std::string& arg) {
|
||||
return strip_huggingface_url_prefix(arg);
|
||||
std::string normalize_registry_checkpoint_arg(const std::string& arg,
|
||||
const std::string& source_hint,
|
||||
std::string* detected_source) {
|
||||
std::string source = normalize_source(source_hint);
|
||||
std::string checkpoint = normalize_registry_url(arg, source);
|
||||
if (detected_source) *detected_source = source;
|
||||
return checkpoint;
|
||||
}
|
||||
|
||||
int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
const std::string& model_arg,
|
||||
bool assume_yes) {
|
||||
std::string normalize_huggingface_checkpoint_arg(const std::string& arg) {
|
||||
return normalize_registry_checkpoint_arg(arg, "huggingface", nullptr);
|
||||
}
|
||||
|
||||
int registry_pull_flow(lemonade::LemonadeClient& client,
|
||||
const std::string& model_arg,
|
||||
bool assume_yes,
|
||||
const std::string& registry_source) {
|
||||
std::string source;
|
||||
std::string checkpoint;
|
||||
std::string variant;
|
||||
std::string normalized_model_arg = normalize_huggingface_checkpoint_arg(model_arg);
|
||||
std::string normalized_model_arg = normalize_registry_checkpoint_arg(
|
||||
model_arg, registry_source, &source);
|
||||
split_checkpoint_variant(normalized_model_arg, checkpoint, variant);
|
||||
|
||||
if (checkpoint.find('/') == std::string::npos) {
|
||||
std::cerr << "Error: '" << model_arg
|
||||
<< "' does not look like a Hugging Face checkpoint (expected owner/repo)."
|
||||
<< "' does not look like a model registry checkpoint (expected owner/repo)."
|
||||
<< std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Fetch variants from the local server.
|
||||
std::string path = "/api/v1/pull/variants?checkpoint=" + url_encode(checkpoint);
|
||||
std::string path = "/api/v1/pull/variants?checkpoint=" + url_encode(checkpoint) +
|
||||
"&source=" + url_encode(source);
|
||||
json variants_response;
|
||||
try {
|
||||
std::string body = client.make_request(path, "GET");
|
||||
variants_response = json::parse(body);
|
||||
} catch (const lemonade::HttpError& e) {
|
||||
if (e.status_code() == 404) {
|
||||
std::cerr << "Checkpoint '" << checkpoint << "' not found on Hugging Face." << std::endl;
|
||||
std::cerr << "Checkpoint '" << checkpoint << "' not found on "
|
||||
<< (source == "modelscope" ? "ModelScope" : "Hugging Face")
|
||||
<< "." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
std::cerr << "Error fetching variants: " << lemonade::extract_server_error_message(e) << std::endl;
|
||||
@@ -228,9 +277,10 @@ int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
json pull_body;
|
||||
pull_body["model_name"] = model_name;
|
||||
pull_body["recipe"] = "collection.omni";
|
||||
pull_body["source"] = source;
|
||||
// The repo is the checkpoint pointer; /pull resolves components from the
|
||||
// manifest it downloads to disk, and a later `lemonade pull <name>`
|
||||
// refreshes them from Hugging Face.
|
||||
// refreshes them from the recorded remote registry.
|
||||
pull_body["checkpoints"] = json::object();
|
||||
pull_body["checkpoints"]["main"] = checkpoint;
|
||||
|
||||
@@ -312,6 +362,7 @@ int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
pull_body["model_name"] = "user." + suggested_name;
|
||||
pull_body["checkpoint"] = checkpoint;
|
||||
pull_body["recipe"] = recipe;
|
||||
pull_body["source"] = source;
|
||||
|
||||
std::cout << "Pulling " << checkpoint
|
||||
<< " as " << suggested_name << std::endl;
|
||||
@@ -362,6 +413,7 @@ int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
pull_body["model_name"] = normalize_user_model_name(model_name);
|
||||
pull_body["checkpoint"] = checkpoint + ":" + variant_name;
|
||||
pull_body["recipe"] = recipe;
|
||||
pull_body["source"] = source;
|
||||
|
||||
if (variants_response.contains("suggested_labels") &&
|
||||
variants_response["suggested_labels"].is_array() &&
|
||||
@@ -381,4 +433,11 @@ int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
return client.pull_model(pull_body, model_name, /*upgrade=*/true);
|
||||
}
|
||||
|
||||
|
||||
int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
const std::string& model_arg,
|
||||
bool assume_yes) {
|
||||
return registry_pull_flow(client, model_arg, assume_yes, "huggingface");
|
||||
}
|
||||
|
||||
} // namespace lemon_cli
|
||||
@@ -718,7 +718,7 @@ int LemonadeClient::pull_model(const json& model_data, const std::string& displa
|
||||
request_body["stream"] = true;
|
||||
|
||||
// Cache-first by default: an already-downloaded model is reused instead
|
||||
// of triggering a Hugging Face update check (and a possible full
|
||||
// of triggering a remote-registry update check (and a possible full
|
||||
// re-download). Only the explicit `lemonade pull` update flow opts into
|
||||
// an upgrade. An explicit field already in model_data wins.
|
||||
if (!request_body.contains("do_not_upgrade")) {
|
||||
@@ -758,7 +758,7 @@ int LemonadeClient::pull_model(const json& model_data, const std::string& displa
|
||||
state.error_message =
|
||||
"No built-in model with the name '" + model_name + "' is registered.\n\n"
|
||||
"If you meant a built-in model, run `lemonade list` to see available models.\n"
|
||||
"If you meant to add a custom model from Hugging Face, run `lemonade pull CHECKPOINT`.";
|
||||
"If you meant to add a custom model from Hugging Face or ModelScope, run `lemonade pull CHECKPOINT`.";
|
||||
}
|
||||
|
||||
if (!state.error_message.empty()) {
|
||||
|
||||
+63
-13
@@ -149,6 +149,8 @@ struct CliConfig {
|
||||
std::string list_filter;
|
||||
std::map<std::string, std::string> checkpoints;
|
||||
std::string recipe;
|
||||
std::string model_source = "huggingface";
|
||||
bool model_source_explicit = false;
|
||||
std::vector<std::string> labels;
|
||||
std::vector<std::string> components;
|
||||
nlohmann::json recipe_options;
|
||||
@@ -327,6 +329,23 @@ static int handle_import_command(lemonade::LemonadeClient& client, const CliConf
|
||||
config.skip_prompt, config.yes, nullptr, true);
|
||||
}
|
||||
|
||||
static std::optional<std::string> explicit_registry_source_from_url(const std::string& value) {
|
||||
if (value.rfind("https://huggingface.co/", 0) == 0 ||
|
||||
value.rfind("http://huggingface.co/", 0) == 0) {
|
||||
return "huggingface";
|
||||
}
|
||||
for (const char* prefix : {
|
||||
"https://modelscope.cn/models/",
|
||||
"https://www.modelscope.cn/models/",
|
||||
"http://modelscope.cn/models/",
|
||||
"http://www.modelscope.cn/models/",
|
||||
"https://modelscope.ai/models/",
|
||||
"https://www.modelscope.ai/models/"}) {
|
||||
if (value.rfind(prefix, 0) == 0) return "modelscope";
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
static int handle_manual_pull_command(lemonade::LemonadeClient& client, const CliConfig& config) {
|
||||
nlohmann::json model_data;
|
||||
|
||||
@@ -334,14 +353,37 @@ static int handle_manual_pull_command(lemonade::LemonadeClient& client, const Cl
|
||||
model_data["model_name"] = config.model;
|
||||
model_data["recipe"] = config.recipe;
|
||||
|
||||
std::optional<std::string> explicit_source;
|
||||
if (!config.checkpoints.empty()) {
|
||||
nlohmann::json checkpoints = nlohmann::json::object();
|
||||
for (const auto& [type, checkpoint] : config.checkpoints) {
|
||||
checkpoints[type] = lemon_cli::normalize_huggingface_checkpoint_arg(checkpoint);
|
||||
std::string detected_source;
|
||||
checkpoints[type] = lemon_cli::normalize_registry_checkpoint_arg(
|
||||
checkpoint, config.model_source, &detected_source);
|
||||
|
||||
if (auto source_from_url = explicit_registry_source_from_url(checkpoint)) {
|
||||
if (config.model_source_explicit &&
|
||||
config.model_source != *source_from_url) {
|
||||
std::cerr
|
||||
<< "Error: checkpoint URL uses " << *source_from_url
|
||||
<< " but --source was set to " << config.model_source
|
||||
<< "." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (explicit_source && *explicit_source != *source_from_url) {
|
||||
std::cerr << "Error: all checkpoints in one model must use the same "
|
||||
"remote registry." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
explicit_source = *source_from_url;
|
||||
}
|
||||
}
|
||||
model_data["checkpoints"] = std::move(checkpoints);
|
||||
}
|
||||
|
||||
model_data["source"] = explicit_source.value_or(config.model_source);
|
||||
|
||||
if (!config.components.empty()) {
|
||||
model_data["components"] = config.components;
|
||||
}
|
||||
@@ -350,7 +392,7 @@ static int handle_manual_pull_command(lemonade::LemonadeClient& client, const Cl
|
||||
model_data["labels"] = config.labels;
|
||||
}
|
||||
|
||||
// Explicit `lemonade pull`: opt into an upgrade (Hugging Face update check).
|
||||
// Explicit `lemonade pull`: opt into the configured registry update check.
|
||||
return client.pull_model(model_data, "", /*upgrade=*/true);
|
||||
}
|
||||
|
||||
@@ -384,19 +426,20 @@ static int handle_pull_command(lemonade::LemonadeClient& client, const CliConfig
|
||||
return handle_manual_pull_command(client, config);
|
||||
}
|
||||
|
||||
std::string normalized_model = lemon_cli::normalize_huggingface_checkpoint_arg(config.model);
|
||||
std::string detected_source;
|
||||
std::string normalized_model = lemon_cli::normalize_registry_checkpoint_arg(
|
||||
config.model, config.model_source, &detected_source);
|
||||
|
||||
// If the argument looks like a Hugging Face checkpoint id (contains '/'),
|
||||
// run the interactive HF flow that discovers variants and auto-fills the
|
||||
// pull request. Otherwise treat it as a registered model name and pull by
|
||||
// model_name only.
|
||||
// Registry checkpoints use the interactive discovery flow; registered model
|
||||
// names remain source-independent because their persisted provenance wins.
|
||||
if (normalized_model.find('/') != std::string::npos) {
|
||||
return lemon_cli::hf_pull_flow(client, normalized_model, false);
|
||||
return lemon_cli::registry_pull_flow(
|
||||
client, normalized_model, false, detected_source);
|
||||
}
|
||||
|
||||
nlohmann::json model_data;
|
||||
model_data["model_name"] = config.model;
|
||||
// Explicit `lemonade pull`: opt into an upgrade (Hugging Face update check).
|
||||
// Explicit `lemonade pull`: opt into the configured registry update check.
|
||||
return client.pull_model(model_data, "", /*upgrade=*/true);
|
||||
}
|
||||
|
||||
@@ -1212,7 +1255,7 @@ int main(int argc, char* argv[]) {
|
||||
CLI::App* check_updates_cmd = app.add_subcommand(
|
||||
"check-updates", "Check downloaded models for upstream updates")->group("Model management");
|
||||
CLI::App* pull_cmd = app.add_subcommand("pull",
|
||||
"Pull/download a model by registered name or Hugging Face checkpoint")->group("Model management");
|
||||
"Pull/download a model by registered name or remote registry checkpoint")->group("Model management");
|
||||
CLI::App* delete_cmd = app.add_subcommand("delete", "Delete a model")->group("Model management");
|
||||
CLI::App* load_cmd = app.add_subcommand("load", "Load a model")->group("Model management");
|
||||
CLI::App* unload_cmd = app.add_subcommand("unload", "Unload a model (or all models)")->group("Model management");
|
||||
@@ -1220,7 +1263,7 @@ int main(int argc, char* argv[]) {
|
||||
CLI::App* unpin_cmd = app.add_subcommand("unpin", "Unpin a loaded model")->group("Model management");
|
||||
CLI::App* import_cmd = app.add_subcommand("import", "Import a model from JSON file")->group("Model management");
|
||||
CLI::App* export_cmd = app.add_subcommand("export", "Export model information to JSON")->group("Model management");
|
||||
CLI::App* cleanup_cmd = app.add_subcommand("cleanup-cache", "Clean up orphaned files in HuggingFace cache")->group("Model management");
|
||||
CLI::App* cleanup_cmd = app.add_subcommand("cleanup-cache", "Clean up orphaned files in the model hub cache")->group("Model management");
|
||||
|
||||
// List options
|
||||
list_cmd->add_flag("--downloaded", config.downloaded, "Show only downloaded models");
|
||||
@@ -1264,9 +1307,14 @@ int main(int argc, char* argv[]) {
|
||||
|
||||
// Pull options
|
||||
pull_cmd->add_option("model", config.model,
|
||||
"Registered model name, or Hugging Face checkpoint (owner/repo[:variant])")
|
||||
"Registered model name, registry checkpoint (owner/repo[:variant]), or model URL")
|
||||
->required()
|
||||
->type_name("MODEL_OR_CHECKPOINT");
|
||||
CLI::Option* pull_source_opt =
|
||||
pull_cmd->add_option("--source", config.model_source,
|
||||
"Remote registry for checkpoint pulls: huggingface or modelscope")
|
||||
->type_name("SOURCE")
|
||||
->check(CLI::IsMember({"huggingface", "modelscope"}));
|
||||
pull_cmd->add_option("--checkpoint", config.checkpoints,
|
||||
"Add a TYPE CHECKPOINT pair for a custom user.* model. Repeat for multi-file models.")
|
||||
->group("Manual Configuration Options")
|
||||
@@ -1396,6 +1444,8 @@ int main(int argc, char* argv[]) {
|
||||
return app.exit(e);
|
||||
}
|
||||
|
||||
config.model_source_explicit = pull_source_opt->count() > 0;
|
||||
|
||||
if (load_cmd->count() > 0) {
|
||||
if (load_cmd->count("--pinned") > 0) {
|
||||
config.pinned = load_pinned_flag;
|
||||
@@ -1461,7 +1511,7 @@ int main(int argc, char* argv[]) {
|
||||
return client.check_model_updates();
|
||||
} else if (pull_cmd->count() > 0) {
|
||||
if (config.model.empty()) {
|
||||
std::cerr << "Error: 'lemonade pull' requires a model name or Hugging Face checkpoint." << std::endl;
|
||||
std::cerr << "Error: 'lemonade pull' requires a model name or remote registry checkpoint." << std::endl;
|
||||
std::cerr << " See 'lemonade pull --help'." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "lemon_cli/recipe_import.h"
|
||||
|
||||
#include "lemon/model_manager.h"
|
||||
#include "lemon/model_registry.h"
|
||||
#include "lemon/utils/http_client.h"
|
||||
#include "lemon/utils/path_utils.h"
|
||||
|
||||
@@ -31,6 +32,8 @@ const std::vector<std::string> kKnownKeys = {
|
||||
"recipe",
|
||||
"recipe_options",
|
||||
"routing",
|
||||
"source",
|
||||
"registry_source",
|
||||
"size",
|
||||
"system_prompt"
|
||||
};
|
||||
@@ -215,6 +218,34 @@ static void normalize_model_json_keys(nlohmann::json& obj) {
|
||||
for (const auto& key : keys_to_remove) {
|
||||
obj.erase(key);
|
||||
}
|
||||
|
||||
// Export only portable remote provenance. Local origins such as
|
||||
// local_upload/local_path refer to machine-specific paths and were
|
||||
// intentionally omitted by the old transform. Remote registrations keep a
|
||||
// canonical source so an imported model continues to update from the same
|
||||
// registry. `registry_source` alone is accepted for internal/older exports.
|
||||
const bool has_public_source = obj.contains("source") && obj["source"].is_string();
|
||||
const std::string public_source = has_public_source
|
||||
? obj["source"].get<std::string>() : std::string();
|
||||
if (has_public_source && !lemon::is_remote_registry_source(public_source)) {
|
||||
obj.erase("source");
|
||||
obj.erase("registry_source");
|
||||
} else {
|
||||
std::string remote_source = public_source;
|
||||
if (remote_source.empty() && obj.contains("registry_source") &&
|
||||
obj["registry_source"].is_string()) {
|
||||
remote_source = obj["registry_source"].get<std::string>();
|
||||
}
|
||||
if (!remote_source.empty() && lemon::is_remote_registry_source(remote_source)) {
|
||||
const std::string canonical = lemon::remote_registry_source_name(
|
||||
lemon::parse_remote_registry_source(remote_source));
|
||||
obj["source"] = canonical;
|
||||
obj["registry_source"] = canonical;
|
||||
} else {
|
||||
obj.erase("source");
|
||||
obj.erase("registry_source");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -27,6 +27,7 @@ struct CheckpointResolveContext {
|
||||
std::string variant; // checkpoint variant after ':' ("" if none)
|
||||
std::string type; // checkpoint type ("main", "mmproj", "npu_cache", …)
|
||||
std::string checkpoint; // the raw checkpoint string
|
||||
std::string registry_source; // huggingface/modelscope
|
||||
};
|
||||
|
||||
// Stateless per-backend behavior for model management that happens WITHOUT a
|
||||
@@ -49,7 +50,7 @@ public:
|
||||
}
|
||||
|
||||
// Resolve a checkpoint to its absolute on-disk path (file or directory).
|
||||
// Default: the shared HF behavior — locate the variant/aux file in the active
|
||||
// Default: the shared registry-cache behavior — locate the variant/aux file in the active
|
||||
// snapshot, else fall back to the model cache directory.
|
||||
virtual std::string resolve_checkpoint_path(const ModelInfo& info,
|
||||
const CheckpointResolveContext& ctx) const;
|
||||
@@ -88,7 +89,7 @@ public:
|
||||
return {};
|
||||
}
|
||||
|
||||
// Whether a model's local artifacts are present. Default: the shared HF
|
||||
// Whether a model's local artifacts are present. Default: the shared registry
|
||||
// checkpoint-completeness check (ModelManager::checkpoints_complete).
|
||||
virtual bool is_downloaded(const ModelInfo& info, const BackendOpsContext& ctx) const;
|
||||
|
||||
@@ -99,7 +100,7 @@ public:
|
||||
return "";
|
||||
}
|
||||
|
||||
// Download a model's artifacts. Default: the shared Hugging Face download.
|
||||
// Download a model's artifacts. Default: the shared remote-registry download.
|
||||
virtual void download_model(const ModelInfo& info, bool do_not_upgrade,
|
||||
DownloadProgressCallback progress,
|
||||
const BackendOpsContext& ctx) const;
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace lemon {
|
||||
namespace backends {
|
||||
namespace hf_cache {
|
||||
|
||||
// Shared Hugging Face cache mechanics used by backend ops to locate model
|
||||
// Shared model-hub cache mechanics used by backend ops to locate model
|
||||
// artifacts on disk (the same logic model_manager uses for its own cache work).
|
||||
|
||||
// Exists check that tolerates the symlinks HF uses for dedup (Win32 on Windows,
|
||||
@@ -18,12 +18,13 @@ bool exists(const std::filesystem::path& p);
|
||||
// of throwing.
|
||||
std::filesystem::directory_options dir_options();
|
||||
|
||||
// The active HF snapshot directory (snapshots/<refs/main>) for a model cache
|
||||
// The active registry snapshot directory (snapshots/<refs/main>) for a model cache
|
||||
// dir, or an empty path if there is no recorded ref / it doesn't exist.
|
||||
std::filesystem::path active_snapshot_path(const std::filesystem::path& model_cache_path);
|
||||
|
||||
// HF cache directory name for a repo id ("org/repo" -> "models--org--repo").
|
||||
std::string repo_id_to_cache_dir_name(const std::string& repo_id);
|
||||
// Provider-qualified cache directory name for a repository id.
|
||||
std::string repo_id_to_cache_dir_name(const std::string& repo_id,
|
||||
const std::string& registry_source = "huggingface");
|
||||
|
||||
} // namespace hf_cache
|
||||
} // namespace backends
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
namespace lemon {
|
||||
|
||||
// Single GGUF variant detected in a Hugging Face repository.
|
||||
// Single GGUF variant detected in a remote model registry repository.
|
||||
struct GgufVariant {
|
||||
std::string name; // Quant token (e.g. "Q4_K_M") or folder/file name fallback.
|
||||
std::string primary_file; // First file (lexicographic) representing this variant.
|
||||
@@ -17,16 +17,15 @@ struct GgufVariant {
|
||||
uint64_t size_bytes = 0; // Sum of file sizes (0 if unknown).
|
||||
};
|
||||
|
||||
// Result of enumerating GGUF variants in a HF repo file listing.
|
||||
// Result of enumerating GGUF variants in a registry file listing.
|
||||
struct GgufVariantSet {
|
||||
std::vector<GgufVariant> variants;
|
||||
std::vector<std::string> mmproj_files; // Bare filenames of mmproj-*.gguf files.
|
||||
};
|
||||
|
||||
// Enumerate GGUF variants from a list of files in a HuggingFace repository.
|
||||
// Enumerate GGUF variants from a normalized repository file list.
|
||||
//
|
||||
// `repo_files` should be the rfilenames from the HF /api/models/<id> "siblings"
|
||||
// array. `file_sizes` is an optional map (rfilename -> size in bytes) used to
|
||||
// `repo_files` is the normalized path list returned by the selected registry. `file_sizes` is an optional map (rfilename -> size in bytes) used to
|
||||
// populate per-variant size totals; missing entries are treated as 0.
|
||||
//
|
||||
// Mirrors the JS logic in src/app/src/renderer/ModelManager.tsx detectBackend()
|
||||
@@ -37,10 +36,16 @@ GgufVariantSet enumerate_gguf_variants(
|
||||
|
||||
// Build the JSON response body for GET /api/v{0,1}/pull/variants.
|
||||
//
|
||||
// Performs the HTTP call to HuggingFace, runs `enumerate_gguf_variants`,
|
||||
// Queries the selected registry, runs `enumerate_gguf_variants`,
|
||||
// derives suggested labels from the repo id, and returns the response JSON.
|
||||
// Throws std::runtime_error on transport failure; sets `not_found` true if
|
||||
// the HF API returned 404 so the caller can return an HTTP 404.
|
||||
nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_found);
|
||||
// the registry reports a missing/inaccessible repo so the caller can return HTTP 404.
|
||||
nlohmann::json fetch_pull_variants(const std::string& checkpoint,
|
||||
const std::string& registry_source,
|
||||
bool& not_found);
|
||||
|
||||
inline nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_found) {
|
||||
return fetch_pull_variants(checkpoint, "huggingface", not_found);
|
||||
}
|
||||
|
||||
} // namespace lemon
|
||||
@@ -81,9 +81,10 @@ struct ModelInfo {
|
||||
std::vector<std::string> labels;
|
||||
std::vector<std::string> components;
|
||||
bool suggested = false;
|
||||
std::string source; // "local_upload" for locally uploaded models
|
||||
std::string source; // Local origin: local_upload/local_path/extra_models_dir
|
||||
std::string registry_source = "huggingface"; // Remote registry: huggingface/modelscope
|
||||
bool downloaded = false; // Whether model is downloaded and available
|
||||
bool update_available = false; // Whether a newer version exists on HuggingFace
|
||||
bool update_available = false; // Whether a newer remote-registry version exists
|
||||
double size = 0.0; // Model size in GB
|
||||
int64_t max_context_window = 0; // Static model-supported text context, when known
|
||||
|
||||
@@ -243,7 +244,7 @@ public:
|
||||
// Check if model is downloaded
|
||||
bool is_model_downloaded(const std::string& model_name);
|
||||
|
||||
// Check all downloaded models for updates on Hugging Face.
|
||||
// Check all downloaded models for updates in their configured remote registry.
|
||||
// Fetches the latest commit SHA for each model's repo and compares it
|
||||
// with the cached commit (refs/main). Sets update_available on models
|
||||
// whose upstream repo has changed and clears stale flags for repos that
|
||||
@@ -256,17 +257,21 @@ public:
|
||||
// so should be skipped by the router's load-time auto-download path.
|
||||
bool backend_self_manages_downloads(const std::string& recipe) const;
|
||||
|
||||
// Shared Hugging Face completeness check: true if all required checkpoints
|
||||
// are present and complete (per-backend file validation runs via ops). The
|
||||
// default BackendOps::is_downloaded delegates here for HF-backed backends.
|
||||
// Shared registry-backed completeness check: true if all required checkpoints
|
||||
// are present and complete (per-backend file validation runs via ops).
|
||||
bool checkpoints_complete(const ModelInfo& info) const;
|
||||
|
||||
// Shared Hugging Face download engine. The default BackendOps::download_model
|
||||
// Shared remote-registry download engine. The default BackendOps::download_model
|
||||
// delegates here; flm/cloud override with their own download.
|
||||
void download_from_registry_engine(const ModelInfo& info,
|
||||
DownloadProgressCallback progress_callback = nullptr);
|
||||
|
||||
// Source-compatible alias for integrations built against the original API.
|
||||
// The model's registry_source still controls which provider is contacted.
|
||||
void download_from_huggingface_engine(const ModelInfo& info,
|
||||
DownloadProgressCallback progress_callback = nullptr);
|
||||
|
||||
// Get HuggingFace cache directory (respects HF_HUB_CACHE, HF_HOME, and platform defaults)
|
||||
// Get shared model-hub cache directory (respects HF_HUB_CACHE, HF_HOME, and platform defaults)
|
||||
std::string get_hf_cache_dir() const;
|
||||
|
||||
// Set extra models directory for GGUF discovery.
|
||||
@@ -306,13 +311,12 @@ private:
|
||||
std::string get_user_models_file();
|
||||
std::string get_recipe_options_file();
|
||||
|
||||
// Collection manifests (recipe="collection.omni" with an HF-repo checkpoint):
|
||||
// the full collection definition lives on Hugging Face as an exported
|
||||
// collection JSON (conventionally <CollectionName>.json; discovered by
|
||||
// content, not filename). fetch_collection_manifest downloads/refreshes it
|
||||
// into the HF cache (honoring do_not_upgrade and offline mode) and returns
|
||||
// the parsed manifest object.
|
||||
nlohmann::json fetch_collection_manifest(const std::string& repo_id, bool do_not_upgrade);
|
||||
// Collection manifests (recipe="collection.omni" with a registry checkpoint):
|
||||
// the full collection definition lives in the configured remote registry as
|
||||
// an exported collection JSON (discovered by content, not filename).
|
||||
nlohmann::json fetch_collection_manifest(const std::string& repo_id,
|
||||
const std::string& registry_source,
|
||||
bool do_not_upgrade);
|
||||
|
||||
// Resolve a collection's component list against the registry: known names
|
||||
// keep the local definition (local-wins, drift logged); unknown names are
|
||||
@@ -320,12 +324,14 @@ private:
|
||||
// `component_defs` (the `models` array of a collection file/manifest).
|
||||
// Returns the components as canonical cache names, preserving order.
|
||||
std::vector<std::string> register_components(const nlohmann::json& component_names,
|
||||
const nlohmann::json& component_defs);
|
||||
const nlohmann::json& component_defs,
|
||||
const std::string& registry_source = "huggingface");
|
||||
|
||||
// Resolve an HF-backed collection's components at pull time: fetch the
|
||||
// Resolve a registry-backed collection's components at pull time: fetch the
|
||||
// manifest, then register_components() against its components/models arrays.
|
||||
std::vector<std::string> resolve_collection_components_from_manifest(
|
||||
const std::string& repo_id, bool do_not_upgrade);
|
||||
const std::string& repo_id,
|
||||
const std::string& registry_source, bool do_not_upgrade);
|
||||
|
||||
// Populate a collection's components from a manifest already cached on disk
|
||||
// (offline, no registration). Used by build_cache so a pulled collection keeps
|
||||
@@ -347,8 +353,8 @@ private:
|
||||
// Download from a JSON manifest
|
||||
void download_from_manifest(const json& manifest, std::map<std::string, std::string>& headers, DownloadProgressCallback progress_callback);
|
||||
|
||||
// Download from Hugging Face
|
||||
void download_from_huggingface(const ModelInfo& info,
|
||||
// Download from the model's configured remote registry
|
||||
void download_from_registry(const ModelInfo& info,
|
||||
DownloadProgressCallback progress_callback = nullptr);
|
||||
|
||||
// Discover GGUF models from extra_models_dir
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace lemon {
|
||||
|
||||
enum class RemoteRegistrySource {
|
||||
HuggingFace,
|
||||
ModelScope,
|
||||
};
|
||||
|
||||
class RegistryNotFoundError : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
struct RegistryFile {
|
||||
std::string path;
|
||||
std::uint64_t size = 0;
|
||||
std::string hash_algorithm;
|
||||
std::string hash;
|
||||
bool directory = false;
|
||||
};
|
||||
|
||||
struct RegistryRepository {
|
||||
std::string repo_id;
|
||||
std::string revision; // revision used by the remote download endpoint
|
||||
std::string snapshot_id; // immutable/local snapshot identifier stored in refs/main
|
||||
std::vector<RegistryFile> files;
|
||||
nlohmann::json raw_metadata;
|
||||
};
|
||||
|
||||
// Normalized registry names persisted in user_models.json and exposed by APIs.
|
||||
// Empty input intentionally maps to Hugging Face for backward compatibility.
|
||||
RemoteRegistrySource parse_remote_registry_source(const std::string& source);
|
||||
std::string remote_registry_source_name(RemoteRegistrySource source);
|
||||
std::string remote_registry_display_name(RemoteRegistrySource source);
|
||||
bool is_remote_registry_source(const std::string& source);
|
||||
|
||||
// Deterministic snapshot id for providers whose download revision may remain
|
||||
// mutable. Ordering of files does not affect the result.
|
||||
std::string registry_tree_snapshot_id(RemoteRegistrySource source,
|
||||
const std::string& revision,
|
||||
const std::vector<RegistryFile>& files);
|
||||
|
||||
// Provider-qualified cache directory. Hugging Face keeps its historical layout;
|
||||
// ModelScope receives a distinct namespace so identical owner/repo ids never
|
||||
// collide while the snapshot/refs layout below it stays runtime-compatible.
|
||||
std::string registry_repo_cache_dir_name(const std::string& repo_id,
|
||||
RemoteRegistrySource source);
|
||||
|
||||
class ModelRegistry {
|
||||
public:
|
||||
virtual ~ModelRegistry() = default;
|
||||
|
||||
virtual RemoteRegistrySource source() const = 0;
|
||||
virtual std::string default_revision() const = 0;
|
||||
virtual std::map<std::string, std::string> auth_headers() const = 0;
|
||||
|
||||
// Fetch and normalize a repository file tree. Empty revision means the
|
||||
// provider default. snapshot_id is stable for unchanged content and changes
|
||||
// when the provider reports a new immutable revision/file tree.
|
||||
virtual RegistryRepository fetch_repository(
|
||||
const std::string& repo_id,
|
||||
const std::string& revision = "") const = 0;
|
||||
|
||||
virtual std::string resolve_file_url(const std::string& repo_id,
|
||||
const std::string& revision,
|
||||
const std::string& file_path) const = 0;
|
||||
};
|
||||
|
||||
const ModelRegistry& model_registry(RemoteRegistrySource source);
|
||||
const ModelRegistry& model_registry(const std::string& source);
|
||||
|
||||
} // namespace lemon
|
||||
@@ -6,17 +6,24 @@
|
||||
|
||||
namespace lemon_cli {
|
||||
|
||||
// Accept either a bare Hugging Face repo id / checkpoint string or a full
|
||||
// huggingface.co URL and return the canonical checkpoint form expected by the
|
||||
// CLI and server (for example: owner/repo[:variant]).
|
||||
// Accept a bare checkpoint or a Hugging Face / ModelScope model URL. The
|
||||
// returned value is owner/repo[:variant]. When detected_source is non-null it
|
||||
// receives "huggingface" or "modelscope" when the URL identifies a provider;
|
||||
// otherwise it receives the normalized source_hint.
|
||||
std::string normalize_registry_checkpoint_arg(const std::string& arg,
|
||||
const std::string& source_hint,
|
||||
std::string* detected_source = nullptr);
|
||||
|
||||
// Backward-compatible helper retained for existing callers/tests.
|
||||
std::string normalize_huggingface_checkpoint_arg(const std::string& arg);
|
||||
|
||||
// Pull a model from a Hugging Face checkpoint id, optionally with a variant
|
||||
// suffix (`owner/repo[:variant]`). Fetches /api/v1/pull/variants from lemond,
|
||||
// presents an interactive variant menu when needed, then issues /v1/pull.
|
||||
//
|
||||
// `assume_yes` skips the interactive menu and picks the first variant.
|
||||
// Returns 0 on success, non-zero on error.
|
||||
// Discover variants through lemond and pull from the selected remote registry.
|
||||
int registry_pull_flow(lemonade::LemonadeClient& client,
|
||||
const std::string& model_arg,
|
||||
bool assume_yes,
|
||||
const std::string& registry_source);
|
||||
|
||||
// Backward-compatible Hugging Face entry point.
|
||||
int hf_pull_flow(lemonade::LemonadeClient& client,
|
||||
const std::string& model_arg,
|
||||
bool assume_yes);
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace backends {
|
||||
using lemon::utils::path_from_utf8;
|
||||
using lemon::utils::path_to_utf8;
|
||||
|
||||
// Default checkpoint resolution: the shared Hugging Face behavior. Locate the
|
||||
// Default checkpoint resolution: the shared remote-registry cache behavior. Locate the
|
||||
// requested variant (or auxiliary file like mmproj) within the active snapshot,
|
||||
// falling back to the main repo and finally the model cache directory.
|
||||
std::string BackendOps::resolve_checkpoint_path(const ModelInfo& info,
|
||||
@@ -75,7 +75,7 @@ std::string BackendOps::resolve_checkpoint_path(const ModelInfo& info,
|
||||
// Backward-compat: older downloads placed all files in the main repo dir.
|
||||
if (ctx.repo_id != ctx.main_repo_id) {
|
||||
std::string main_cache_path =
|
||||
ctx.hf_cache + "/" + hf_cache::repo_id_to_cache_dir_name(ctx.main_repo_id);
|
||||
ctx.hf_cache + "/" + hf_cache::repo_id_to_cache_dir_name(ctx.main_repo_id, ctx.registry_source);
|
||||
fs::path main_cache_path_fs = path_from_utf8(main_cache_path);
|
||||
if (fs::exists(main_cache_path_fs)) {
|
||||
for (const auto& entry : fs::recursive_directory_iterator(main_cache_path_fs)) {
|
||||
@@ -102,16 +102,16 @@ std::string BackendOps::resolve_checkpoint_path(const ModelInfo& info,
|
||||
}
|
||||
|
||||
bool BackendOps::is_downloaded(const ModelInfo& info, const BackendOpsContext& ctx) const {
|
||||
// Default: the shared HF checkpoint-completeness check.
|
||||
// Default: the shared registry checkpoint-completeness check.
|
||||
return ctx.model_manager != nullptr && ctx.model_manager->checkpoints_complete(info);
|
||||
}
|
||||
|
||||
void BackendOps::download_model(const ModelInfo& info, bool do_not_upgrade,
|
||||
DownloadProgressCallback progress, const BackendOpsContext& ctx) const {
|
||||
// Default: the shared Hugging Face download engine.
|
||||
// Default: the shared remote-registry download engine.
|
||||
(void)do_not_upgrade;
|
||||
if (ctx.model_manager != nullptr) {
|
||||
ctx.model_manager->download_from_huggingface_engine(info, progress);
|
||||
ctx.model_manager->download_from_registry_engine(info, progress);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <fstream>
|
||||
|
||||
#include "lemon/model_registry.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
@@ -59,12 +61,10 @@ fs::path active_snapshot_path(const fs::path& model_cache_path) {
|
||||
return lemon::backends::hf_cache::exists(snapshot_path) ? snapshot_path : fs::path();
|
||||
}
|
||||
|
||||
std::string repo_id_to_cache_dir_name(const std::string& repo_id) {
|
||||
std::string cache_dir_name = "models--";
|
||||
for (char c : repo_id) {
|
||||
cache_dir_name += (c == '/') ? "--" : std::string(1, c);
|
||||
}
|
||||
return cache_dir_name;
|
||||
std::string repo_id_to_cache_dir_name(const std::string& repo_id,
|
||||
const std::string& registry_source) {
|
||||
return registry_repo_cache_dir_name(repo_id,
|
||||
parse_remote_registry_source(registry_source));
|
||||
}
|
||||
|
||||
} // namespace hf_cache
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
#include "lemon/backends/vllm/vllm.h"
|
||||
#include "lemon/backends/backend_registry.h"
|
||||
#include "lemon/backends/backend_utils.h"
|
||||
#include "lemon/backends/hf_cache_util.h"
|
||||
#include "lemon/backends/vllm/vllm_arg_resolver.h"
|
||||
#include "lemon/model_manager.h"
|
||||
#include "lemon/model_registry.h"
|
||||
#include "lemon/runtime_config.h"
|
||||
#include "lemon/system_info.h"
|
||||
#include "lemon/utils/http_client.h"
|
||||
@@ -28,6 +30,11 @@ namespace backends {
|
||||
|
||||
static constexpr int64_t VLLM_MAX_TOKENS_PREFLIGHT_THRESHOLD = 8192;
|
||||
|
||||
static std::string registry_repo_id_from_checkpoint(const std::string& checkpoint) {
|
||||
const auto separator = checkpoint.find(':');
|
||||
return separator == std::string::npos ? checkpoint : checkpoint.substr(0, separator);
|
||||
}
|
||||
|
||||
// Parse quantization_config.quant_method from a config.json body.
|
||||
static std::string parse_quant_method(const std::string& config_json) {
|
||||
try {
|
||||
@@ -125,11 +132,28 @@ json VLLMServer::prepare_openai_request(const json& request) {
|
||||
}
|
||||
|
||||
// Returns quantization_config.quant_method for the model, or empty string.
|
||||
// First checks the HuggingFace hub cache; if config.json isn't there yet,
|
||||
// fetches it over HTTP from huggingface.co directly. This ensures detection
|
||||
// works on first load before vLLM has downloaded anything.
|
||||
static std::string detect_quant_method(const std::string& model_id) {
|
||||
// 1. Check HF cache first (fast path)
|
||||
// Prefer the Lemonade-managed active snapshot. Hugging Face models retain the
|
||||
// historical cache/network fallback; ModelScope models are always loaded from
|
||||
// their normalized local snapshot and must never fall back to Hugging Face.
|
||||
static std::string detect_quant_method(const std::string& model_id,
|
||||
const fs::path& local_snapshot,
|
||||
RemoteRegistrySource registry_source) {
|
||||
if (!local_snapshot.empty()) {
|
||||
fs::path cfg = local_snapshot / "config.json";
|
||||
if (fs::exists(cfg)) {
|
||||
std::ifstream f(cfg);
|
||||
std::stringstream buf;
|
||||
buf << f.rdbuf();
|
||||
std::string result = parse_quant_method(buf.str());
|
||||
if (!result.empty()) return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (registry_source != RemoteRegistrySource::HuggingFace) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Check the historical HF cache location (fast path).
|
||||
std::string hf_dir = "models--";
|
||||
for (char c : model_id) {
|
||||
if (c == '/') hf_dir += "--";
|
||||
@@ -153,7 +177,7 @@ static std::string detect_quant_method(const std::string& model_id) {
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fetch directly from HF
|
||||
// Fetch directly from HF only for Hugging Face registrations.
|
||||
std::string url = "https://huggingface.co/" + model_id + "/resolve/main/config.json";
|
||||
auto resp = HttpClient::get(url);
|
||||
if (resp.status_code == 200) {
|
||||
@@ -342,13 +366,36 @@ void VLLMServer::load(const std::string& model_name,
|
||||
|
||||
backend_manager_->install_backend(vllm::spec()->recipe, vllm_backend);
|
||||
|
||||
// vLLM uses HuggingFace model IDs, not local file paths.
|
||||
std::string model_id = model_info.checkpoint();
|
||||
if (model_id.empty()) {
|
||||
throw std::runtime_error("Model checkpoint (HuggingFace ID) not found for: " + model_name);
|
||||
throw std::runtime_error("Model checkpoint (registry ID) not found for: " + model_name);
|
||||
}
|
||||
|
||||
LOG(DEBUG, "vLLM") << "Using model: " << model_id << std::endl;
|
||||
const RemoteRegistrySource registry_source =
|
||||
parse_remote_registry_source(model_info.registry_source);
|
||||
std::string model_target = model_id;
|
||||
fs::path active_snapshot;
|
||||
|
||||
// vLLM can resolve Hugging Face IDs itself, but it has no native knowledge
|
||||
// of Lemonade's ModelScope cache namespace. Point it at the normalized
|
||||
// active snapshot so it stays offline and uses the exact revision Lemonade
|
||||
// recorded for update checks.
|
||||
if (registry_source == RemoteRegistrySource::ModelScope) {
|
||||
if (model_manager_ == nullptr) {
|
||||
throw std::runtime_error("Model manager is unavailable while resolving ModelScope cache");
|
||||
}
|
||||
const std::string repo_id = registry_repo_id_from_checkpoint(model_id);
|
||||
const fs::path repo_cache = path_from_utf8(model_manager_->get_hf_cache_dir()) /
|
||||
hf_cache::repo_id_to_cache_dir_name(repo_id, model_info.registry_source);
|
||||
active_snapshot = hf_cache::active_snapshot_path(repo_cache);
|
||||
if (active_snapshot.empty() || !fs::exists(active_snapshot)) {
|
||||
throw std::runtime_error(
|
||||
"ModelScope snapshot is not downloaded or refs/main is invalid for: " + model_name);
|
||||
}
|
||||
model_target = path_to_utf8(active_snapshot);
|
||||
}
|
||||
|
||||
LOG(DEBUG, "vLLM") << "Using model target: " << model_target << std::endl;
|
||||
|
||||
std::string vllm_model_config_path =
|
||||
utils::get_resource_path("resources/vllm_model_config.json");
|
||||
@@ -363,7 +410,7 @@ void VLLMServer::load(const std::string& model_name,
|
||||
|
||||
std::vector<std::string> args;
|
||||
args.push_back("--model");
|
||||
args.push_back(model_id);
|
||||
args.push_back(model_target);
|
||||
args.push_back("--port");
|
||||
args.push_back(std::to_string(port_));
|
||||
args.push_back("--host");
|
||||
@@ -390,7 +437,8 @@ void VLLMServer::load(const std::string& model_name,
|
||||
// GPTQ, etc. and forcing --quantization awq would fail the load.
|
||||
// For AWQ specifically we force the 'awq' kernel because vLLM's default
|
||||
// awq_marlin is very slow on consumer GPUs (2 tok/s -> 12 tok/s).
|
||||
std::string quant_method = detect_quant_method(model_id);
|
||||
std::string quant_method = detect_quant_method(
|
||||
model_id, active_snapshot, registry_source);
|
||||
if (quant_method == "awq" && launch_policy.force_awq_kernel) {
|
||||
if (!resolved_vllm_args.has_quantization_arg) {
|
||||
LOG(DEBUG, "vLLM") << "Detected AWQ; forcing --quantization awq" << std::endl;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include "lemon/model_types.h"
|
||||
#include "lemon/model_registry.h"
|
||||
#include "lemon/utils/http_client.h"
|
||||
#include "lemon/utils/json_utils.h"
|
||||
|
||||
@@ -194,49 +195,32 @@ GgufVariantSet enumerate_gguf_variants(
|
||||
return result;
|
||||
}
|
||||
|
||||
nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_found) {
|
||||
nlohmann::json fetch_pull_variants(const std::string& checkpoint,
|
||||
const std::string& registry_source,
|
||||
bool& not_found) {
|
||||
not_found = false;
|
||||
|
||||
if (checkpoint.empty() || checkpoint.find('/') == std::string::npos) {
|
||||
throw std::runtime_error("checkpoint must be a Hugging Face repo id of the form 'owner/name'");
|
||||
throw std::runtime_error("checkpoint must be a repository id of the form 'owner/name'");
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> headers;
|
||||
const char* hf_token = std::getenv("HF_TOKEN");
|
||||
if (hf_token && hf_token[0]) {
|
||||
headers["Authorization"] = "Bearer " + std::string(hf_token);
|
||||
}
|
||||
|
||||
// `?blobs=true` makes HF include per-file `size` in each siblings entry,
|
||||
// which we forward to the variant set so the CLI menu can show real sizes.
|
||||
std::string url = "https://huggingface.co/api/models/" + checkpoint + "?blobs=true";
|
||||
auto response = HttpClient::get(url, headers);
|
||||
// HuggingFace returns 401 (not 404) for nonexistent public repos to mimic
|
||||
// the behavior of gated repos. Treat both as "not found" from the user's
|
||||
// perspective so the CLI can give a clean error message.
|
||||
if (response.status_code == 404 || response.status_code == 401) {
|
||||
const auto source = parse_remote_registry_source(registry_source);
|
||||
const auto& registry = model_registry(source);
|
||||
RegistryRepository repository;
|
||||
try {
|
||||
repository = registry.fetch_repository(checkpoint);
|
||||
} catch (const RegistryNotFoundError&) {
|
||||
not_found = true;
|
||||
return {};
|
||||
}
|
||||
if (response.status_code != 200) {
|
||||
throw std::runtime_error(
|
||||
"Hugging Face API returned status " + std::to_string(response.status_code));
|
||||
}
|
||||
|
||||
auto info = JsonUtils::parse(response.body);
|
||||
if (!info.contains("siblings") || !info["siblings"].is_array()) {
|
||||
throw std::runtime_error("Hugging Face response missing 'siblings' array");
|
||||
}
|
||||
|
||||
const auto headers = registry.auth_headers();
|
||||
std::vector<std::string> repo_files;
|
||||
std::vector<std::pair<std::string, uint64_t>> file_sizes;
|
||||
for (const auto& s : info["siblings"]) {
|
||||
if (!s.contains("rfilename")) continue;
|
||||
std::string name = s["rfilename"].get<std::string>();
|
||||
repo_files.push_back(name);
|
||||
if (s.contains("size") && s["size"].is_number()) {
|
||||
file_sizes.emplace_back(name, s["size"].get<uint64_t>());
|
||||
}
|
||||
for (const auto& file : repository.files) {
|
||||
if (file.directory) continue;
|
||||
repo_files.push_back(file.path);
|
||||
if (file.size > 0) file_sizes.emplace_back(file.path, file.size);
|
||||
}
|
||||
|
||||
// Detect repo kind: GGUF (existing path) vs ONNX RyzenAI vs unknown.
|
||||
@@ -276,6 +260,7 @@ nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_foun
|
||||
|
||||
nlohmann::json out;
|
||||
out["checkpoint"] = checkpoint;
|
||||
out["source"] = remote_registry_source_name(source);
|
||||
out["recipe"] = "ryzenai-llm";
|
||||
out["repo_kind"] = "onnx-ryzenai";
|
||||
out["suggested_name"] = suggested_name;
|
||||
@@ -307,8 +292,8 @@ nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_foun
|
||||
}
|
||||
}
|
||||
|
||||
std::string manifest_url =
|
||||
"https://huggingface.co/" + checkpoint + "/resolve/main/" + manifest_filename;
|
||||
std::string manifest_url = registry.resolve_file_url(
|
||||
checkpoint, repository.revision, manifest_filename);
|
||||
auto manifest_response = HttpClient::get(manifest_url, headers);
|
||||
if (manifest_response.status_code != 200) {
|
||||
throw std::runtime_error(
|
||||
@@ -340,6 +325,7 @@ nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_foun
|
||||
// deliberately omitted — /pull re-downloads it to disk.
|
||||
nlohmann::json out;
|
||||
out["checkpoint"] = checkpoint;
|
||||
out["source"] = remote_registry_source_name(source);
|
||||
out["recipe"] = "collection.omni";
|
||||
out["repo_kind"] = "collection";
|
||||
out["suggested_name"] = suggested_name;
|
||||
@@ -373,6 +359,7 @@ nlohmann::json fetch_pull_variants(const std::string& checkpoint, bool& not_foun
|
||||
|
||||
nlohmann::json out;
|
||||
out["checkpoint"] = checkpoint;
|
||||
out["source"] = remote_registry_source_name(source);
|
||||
out["recipe"] = "llamacpp";
|
||||
out["repo_kind"] = "gguf";
|
||||
out["suggested_name"] = suggested_name;
|
||||
|
||||
+464
-411
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,419 @@
|
||||
#include "lemon/model_registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <iomanip>
|
||||
#include <initializer_list>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#include "lemon/utils/http_client.h"
|
||||
#include "lemon/utils/json_utils.h"
|
||||
|
||||
namespace lemon {
|
||||
namespace {
|
||||
|
||||
using lemon::utils::HttpClient;
|
||||
using lemon::utils::JsonUtils;
|
||||
using json = nlohmann::json;
|
||||
|
||||
std::string lower_copy(std::string value) {
|
||||
std::transform(value.begin(), value.end(), value.begin(),
|
||||
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
return value;
|
||||
}
|
||||
|
||||
bool is_unreserved(unsigned char c) {
|
||||
return std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~';
|
||||
}
|
||||
|
||||
std::string percent_encode(const std::string& value, bool keep_slash = false) {
|
||||
std::ostringstream out;
|
||||
out << std::uppercase << std::hex;
|
||||
for (unsigned char c : value) {
|
||||
if (is_unreserved(c) || (keep_slash && c == '/')) {
|
||||
out << static_cast<char>(c);
|
||||
} else {
|
||||
out << '%' << std::setw(2) << std::setfill('0') << static_cast<int>(c);
|
||||
}
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string env_string(const char* name) {
|
||||
const char* value = std::getenv(name);
|
||||
return (value && value[0]) ? std::string(value) : std::string();
|
||||
}
|
||||
|
||||
std::string trim_trailing_slash(std::string value) {
|
||||
while (!value.empty() && value.back() == '/') value.pop_back();
|
||||
return value;
|
||||
}
|
||||
|
||||
std::uint64_t fnv1a64(const std::string& text, std::uint64_t hash = 14695981039346656037ull) {
|
||||
for (unsigned char c : text) {
|
||||
hash ^= static_cast<std::uint64_t>(c);
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::string safe_revision_component(std::string revision) {
|
||||
if (revision.empty()) revision = "default";
|
||||
for (char& c : revision) {
|
||||
const unsigned char uc = static_cast<unsigned char>(c);
|
||||
if (!std::isalnum(uc) && c != '-' && c != '_' && c != '.') c = '-';
|
||||
}
|
||||
if (revision.size() > 48) revision.resize(48);
|
||||
return revision;
|
||||
}
|
||||
|
||||
std::string tree_snapshot_id(const std::string& prefix,
|
||||
const std::string& revision,
|
||||
std::vector<RegistryFile> files) {
|
||||
std::sort(files.begin(), files.end(), [](const RegistryFile& a, const RegistryFile& b) {
|
||||
return a.path < b.path;
|
||||
});
|
||||
std::uint64_t hash = fnv1a64(revision);
|
||||
for (const auto& file : files) {
|
||||
hash = fnv1a64(file.path, hash);
|
||||
hash = fnv1a64("\n" + std::to_string(file.size) + "\n", hash);
|
||||
hash = fnv1a64(file.hash_algorithm + ":" + file.hash + "\n", hash);
|
||||
}
|
||||
std::ostringstream out;
|
||||
out << prefix << '-' << safe_revision_component(revision) << '-'
|
||||
<< std::hex << std::setw(16) << std::setfill('0') << hash;
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::uint64_t json_size(const json& entry) {
|
||||
for (const char* key : {"size", "Size", "FileSize", "file_size"}) {
|
||||
auto it = entry.find(key);
|
||||
if (it == entry.end()) continue;
|
||||
if (it->is_number_unsigned()) return it->get<std::uint64_t>();
|
||||
if (it->is_number_integer()) {
|
||||
const auto value = it->get<std::int64_t>();
|
||||
return value > 0 ? static_cast<std::uint64_t>(value) : 0;
|
||||
}
|
||||
if (it->is_string()) {
|
||||
try { return static_cast<std::uint64_t>(std::stoull(it->get<std::string>())); }
|
||||
catch (...) { return 0; }
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string first_string(const json& entry,
|
||||
std::initializer_list<const char*> keys) {
|
||||
for (const char* key : keys) {
|
||||
auto it = entry.find(key);
|
||||
if (it != entry.end() && it->is_string()) return it->get<std::string>();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
bool is_modelscope_not_found_or_access_error(const std::string& code_text,
|
||||
const std::string& message) {
|
||||
const std::string code = lower_copy(code_text);
|
||||
if (code == "401" || code == "403" || code == "404" ||
|
||||
code == "e3001" || code == "e3002" || code == "e3020") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string normalized_message = lower_copy(message);
|
||||
for (const char* marker : {
|
||||
"not found",
|
||||
"does not exist",
|
||||
"not exist",
|
||||
"permission denied",
|
||||
"access denied",
|
||||
"not accessible",
|
||||
"unauthorized",
|
||||
"authentication failed",
|
||||
}) {
|
||||
if (normalized_message.find(marker) != std::string::npos) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void ensure_modelscope_success(const json& body, const std::string& repo_id) {
|
||||
if (!body.is_object()) return;
|
||||
|
||||
bool failed = false;
|
||||
std::string code_text;
|
||||
if (auto it = body.find("Code"); it != body.end()) {
|
||||
if (it->is_number_integer()) {
|
||||
const auto code = it->get<long long>();
|
||||
failed = code != 0 && code != 200;
|
||||
code_text = std::to_string(code);
|
||||
} else if (it->is_string()) {
|
||||
code_text = it->get<std::string>();
|
||||
const std::string normalized = lower_copy(code_text);
|
||||
failed = normalized != "0" && normalized != "200" &&
|
||||
normalized != "ok" && normalized != "success";
|
||||
}
|
||||
}
|
||||
if (auto it = body.find("Success"); it != body.end() && it->is_boolean()) {
|
||||
failed = failed || !it->get<bool>();
|
||||
}
|
||||
if (!failed) return;
|
||||
|
||||
std::string message = first_string(body, {"Message", "message", "Msg", "msg"});
|
||||
if (message.empty()) {
|
||||
message = "ModelScope API rejected the request";
|
||||
}
|
||||
|
||||
std::string detail = message;
|
||||
if (!code_text.empty()) {
|
||||
detail += " (code " + code_text + ")";
|
||||
}
|
||||
|
||||
if (is_modelscope_not_found_or_access_error(code_text, message)) {
|
||||
throw RegistryNotFoundError(
|
||||
"ModelScope repository not found or not accessible: " +
|
||||
repo_id + " (" + detail + ")");
|
||||
}
|
||||
|
||||
throw std::runtime_error(detail + " for " + repo_id);
|
||||
}
|
||||
|
||||
class HuggingFaceRegistry final : public ModelRegistry {
|
||||
public:
|
||||
RemoteRegistrySource source() const override {
|
||||
return RemoteRegistrySource::HuggingFace;
|
||||
}
|
||||
|
||||
std::string default_revision() const override { return "main"; }
|
||||
|
||||
std::map<std::string, std::string> auth_headers() const override {
|
||||
std::map<std::string, std::string> headers;
|
||||
const std::string token = env_string("HF_TOKEN");
|
||||
if (!token.empty()) headers["Authorization"] = "Bearer " + token;
|
||||
return headers;
|
||||
}
|
||||
|
||||
RegistryRepository fetch_repository(const std::string& repo_id,
|
||||
const std::string& requested_revision) const override {
|
||||
const std::string revision = requested_revision.empty() ? default_revision() : requested_revision;
|
||||
std::string endpoint = trim_trailing_slash(env_string("HF_ENDPOINT"));
|
||||
if (endpoint.empty()) endpoint = "https://huggingface.co";
|
||||
|
||||
std::string url = endpoint + "/api/models/" + percent_encode(repo_id, true);
|
||||
if (!requested_revision.empty() && revision != "main") {
|
||||
url += "/revision/" + percent_encode(revision, true);
|
||||
}
|
||||
url += "?blobs=true";
|
||||
|
||||
const auto response = HttpClient::get(url, auth_headers());
|
||||
if (response.status_code == 404 || response.status_code == 401 || response.status_code == 403) {
|
||||
throw RegistryNotFoundError("Hugging Face repository not found or not accessible: " + repo_id);
|
||||
}
|
||||
if (response.status_code != 200) {
|
||||
throw std::runtime_error("Hugging Face API returned status " +
|
||||
std::to_string(response.status_code) +
|
||||
" for " + repo_id);
|
||||
}
|
||||
|
||||
json metadata = JsonUtils::parse(response.body);
|
||||
if (!metadata.contains("siblings") || !metadata["siblings"].is_array()) {
|
||||
throw std::runtime_error("Hugging Face response for " + repo_id +
|
||||
" is missing the siblings array");
|
||||
}
|
||||
|
||||
RegistryRepository result;
|
||||
result.repo_id = repo_id;
|
||||
result.revision = revision;
|
||||
result.raw_metadata = metadata;
|
||||
result.snapshot_id = metadata.value("sha", std::string());
|
||||
if (result.snapshot_id.empty()) result.snapshot_id = revision;
|
||||
// Resolve downloads against the immutable commit whenever HF provides it.
|
||||
result.revision = result.snapshot_id;
|
||||
|
||||
for (const auto& sibling : metadata["siblings"]) {
|
||||
if (!sibling.is_object()) continue;
|
||||
RegistryFile file;
|
||||
file.path = first_string(sibling, {"rfilename", "path", "name"});
|
||||
if (file.path.empty()) continue;
|
||||
file.size = json_size(sibling);
|
||||
if (sibling.contains("lfs") && sibling["lfs"].is_object()) {
|
||||
file.hash = first_string(sibling["lfs"], {"oid", "sha256"});
|
||||
if (!file.hash.empty()) file.hash_algorithm = "sha256";
|
||||
if (file.size == 0) file.size = json_size(sibling["lfs"]);
|
||||
}
|
||||
if (file.hash.empty()) {
|
||||
file.hash = first_string(sibling, {"blobId", "oid"});
|
||||
if (!file.hash.empty()) file.hash_algorithm = "git-sha1";
|
||||
}
|
||||
result.files.push_back(std::move(file));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string resolve_file_url(const std::string& repo_id,
|
||||
const std::string& revision,
|
||||
const std::string& file_path) const override {
|
||||
std::string endpoint = trim_trailing_slash(env_string("HF_ENDPOINT"));
|
||||
if (endpoint.empty()) endpoint = "https://huggingface.co";
|
||||
return endpoint + "/" + percent_encode(repo_id, true) + "/resolve/" +
|
||||
percent_encode(revision.empty() ? default_revision() : revision, true) + "/" +
|
||||
percent_encode(file_path, true);
|
||||
}
|
||||
};
|
||||
|
||||
class ModelScopeRegistry final : public ModelRegistry {
|
||||
public:
|
||||
RemoteRegistrySource source() const override {
|
||||
return RemoteRegistrySource::ModelScope;
|
||||
}
|
||||
|
||||
std::string default_revision() const override { return "master"; }
|
||||
|
||||
std::map<std::string, std::string> auth_headers() const override {
|
||||
std::map<std::string, std::string> headers;
|
||||
std::string token = env_string("MODELSCOPE_API_TOKEN");
|
||||
if (token.empty()) token = env_string("MODELSCOPE_ACCESS_TOKEN");
|
||||
if (!token.empty()) {
|
||||
headers["Authorization"] = "Bearer " + token;
|
||||
// Legacy ModelScope endpoints historically authenticate private repos
|
||||
// with this session cookie. Sending both is accepted by current APIs.
|
||||
headers["Cookie"] = "m_session_id=" + token;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
RegistryRepository fetch_repository(const std::string& repo_id,
|
||||
const std::string& requested_revision) const override {
|
||||
const std::string revision = requested_revision.empty() ? default_revision() : requested_revision;
|
||||
const std::string endpoint = base_endpoint();
|
||||
const std::string url = endpoint + "/api/v1/models/" +
|
||||
percent_encode(repo_id, true) + "/repo/files?Revision=" +
|
||||
percent_encode(revision) + "&Recursive=True";
|
||||
|
||||
const auto response = HttpClient::get(url, auth_headers());
|
||||
if (response.status_code == 404 || response.status_code == 401 || response.status_code == 403) {
|
||||
throw RegistryNotFoundError("ModelScope repository not found or not accessible: " + repo_id);
|
||||
}
|
||||
if (response.status_code != 200) {
|
||||
throw std::runtime_error("ModelScope API returned status " +
|
||||
std::to_string(response.status_code) +
|
||||
" for " + repo_id);
|
||||
}
|
||||
|
||||
json body = JsonUtils::parse(response.body);
|
||||
ensure_modelscope_success(body, repo_id);
|
||||
json files_json;
|
||||
if (body.is_array()) {
|
||||
files_json = body;
|
||||
} else if (body.is_object()) {
|
||||
json data = body.contains("Data") ? body["Data"] : body;
|
||||
if (data.is_array()) {
|
||||
files_json = data;
|
||||
} else if (data.is_object()) {
|
||||
if (data.contains("Files")) files_json = data["Files"];
|
||||
else if (data.contains("files")) files_json = data["files"];
|
||||
}
|
||||
}
|
||||
if (!files_json.is_array()) {
|
||||
throw std::runtime_error("ModelScope response for " + repo_id +
|
||||
" does not contain a file list");
|
||||
}
|
||||
|
||||
RegistryRepository result;
|
||||
result.repo_id = repo_id;
|
||||
result.revision = revision;
|
||||
result.raw_metadata = body;
|
||||
for (const auto& entry : files_json) {
|
||||
if (!entry.is_object()) continue;
|
||||
RegistryFile file;
|
||||
file.path = first_string(entry, {"Path", "path", "Name", "name"});
|
||||
if (file.path.empty()) continue;
|
||||
const std::string type = lower_copy(first_string(entry, {"Type", "type"}));
|
||||
file.directory = type == "tree" || type == "dir" || type == "directory";
|
||||
file.size = json_size(entry);
|
||||
file.hash = first_string(entry, {"Sha256", "sha256", "SHA256"});
|
||||
if (!file.hash.empty()) file.hash_algorithm = "sha256";
|
||||
result.files.push_back(std::move(file));
|
||||
}
|
||||
result.snapshot_id = registry_tree_snapshot_id(source(), revision, result.files);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string resolve_file_url(const std::string& repo_id,
|
||||
const std::string& revision,
|
||||
const std::string& file_path) const override {
|
||||
return base_endpoint() + "/api/v1/models/" + percent_encode(repo_id, true) +
|
||||
"/repo?Revision=" + percent_encode(
|
||||
revision.empty() ? default_revision() : revision) +
|
||||
"&FilePath=" + percent_encode(file_path);
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string base_endpoint() {
|
||||
std::string endpoint = trim_trailing_slash(env_string("MODELSCOPE_ENDPOINT"));
|
||||
if (endpoint.empty()) endpoint = "https://modelscope.cn";
|
||||
return endpoint;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
RemoteRegistrySource parse_remote_registry_source(const std::string& source) {
|
||||
const std::string normalized = lower_copy(source);
|
||||
if (normalized.empty() || normalized == "huggingface" || normalized == "hf") {
|
||||
return RemoteRegistrySource::HuggingFace;
|
||||
}
|
||||
if (normalized == "modelscope" || normalized == "ms") {
|
||||
return RemoteRegistrySource::ModelScope;
|
||||
}
|
||||
throw std::invalid_argument("Unsupported model source '" + source +
|
||||
"' (expected 'huggingface' or 'modelscope')");
|
||||
}
|
||||
|
||||
std::string remote_registry_source_name(RemoteRegistrySource source) {
|
||||
return source == RemoteRegistrySource::ModelScope ? "modelscope" : "huggingface";
|
||||
}
|
||||
|
||||
std::string remote_registry_display_name(RemoteRegistrySource source) {
|
||||
return source == RemoteRegistrySource::ModelScope ? "ModelScope" : "Hugging Face";
|
||||
}
|
||||
|
||||
bool is_remote_registry_source(const std::string& source) {
|
||||
const std::string normalized = lower_copy(source);
|
||||
return normalized == "huggingface" || normalized == "hf" ||
|
||||
normalized == "modelscope" || normalized == "ms";
|
||||
}
|
||||
|
||||
std::string registry_tree_snapshot_id(RemoteRegistrySource source,
|
||||
const std::string& revision,
|
||||
const std::vector<RegistryFile>& files) {
|
||||
return tree_snapshot_id(remote_registry_source_name(source), revision, files);
|
||||
}
|
||||
|
||||
std::string registry_repo_cache_dir_name(const std::string& repo_id,
|
||||
RemoteRegistrySource source) {
|
||||
std::string cache_dir_name = source == RemoteRegistrySource::ModelScope
|
||||
? "modelscope--models--"
|
||||
: "models--";
|
||||
for (char c : repo_id) {
|
||||
cache_dir_name += (c == '/') ? "--" : std::string(1, c);
|
||||
}
|
||||
return cache_dir_name;
|
||||
}
|
||||
|
||||
const ModelRegistry& model_registry(RemoteRegistrySource source) {
|
||||
static const HuggingFaceRegistry huggingface;
|
||||
static const ModelScopeRegistry modelscope;
|
||||
return source == RemoteRegistrySource::ModelScope
|
||||
? static_cast<const ModelRegistry&>(modelscope)
|
||||
: static_cast<const ModelRegistry&>(huggingface);
|
||||
}
|
||||
|
||||
const ModelRegistry& model_registry(const std::string& source) {
|
||||
return model_registry(parse_remote_registry_source(source));
|
||||
}
|
||||
|
||||
} // namespace lemon
|
||||
+89
-19
@@ -2,6 +2,7 @@
|
||||
#include <optional>
|
||||
#include "lemon/collection_orchestrator.h"
|
||||
#include "lemon/hf_variants.h"
|
||||
#include "lemon/model_registry.h"
|
||||
#include "lemon/route_decision_response.h"
|
||||
#include "lemon/routing_classifier_services.h"
|
||||
#include "lemon/routing_policy.h"
|
||||
@@ -1003,6 +1004,8 @@ void Server::setup_static_files(httplib::Server &web_server) {
|
||||
{"recipe", info.recipe},
|
||||
{"labels", info.labels},
|
||||
{"suggested", info.suggested},
|
||||
{"source", info.source.empty() ? info.registry_source : info.source},
|
||||
{"registry_source", info.registry_source},
|
||||
{"components", public_components},
|
||||
{"mmproj", info.mmproj()}
|
||||
};
|
||||
@@ -1860,25 +1863,33 @@ nlohmann::json Server::create_model_error(const std::string& requested_model, co
|
||||
// Behavior:
|
||||
// 1. If model is already loaded: Return immediately (no-op)
|
||||
// 2. If model is not downloaded: Download it (first-time use)
|
||||
// 3. If model is downloaded: Use cached version (don't check HuggingFace for updates)
|
||||
// 3. If model is downloaded: Use cached version
|
||||
// (do not check the remote registry for updates)
|
||||
//
|
||||
// Note: Only the /pull endpoint checks HuggingFace for updates (do_not_upgrade=false)
|
||||
// Note: Only the /pull endpoint checks the model's recorded registry for
|
||||
// updates (do_not_upgrade=false).
|
||||
|
||||
// Load-level options that may be forwarded to RecipeOptions during auto-load.
|
||||
// Keep this an explicit allowlist so request-scoped fields don't leak into recipe options.
|
||||
// Keep this an explicit allowlist so request-scoped fields do not leak into
|
||||
// recipe options.
|
||||
nlohmann::json Server::extract_auto_load_options(const json& request) {
|
||||
nlohmann::json result = json::object();
|
||||
auto extract_if_present = [&request, &result](const std::string& key) {
|
||||
if (request.contains(key)) {
|
||||
result[key] = request[key];
|
||||
}
|
||||
};
|
||||
|
||||
auto extract_if_present =
|
||||
[&request, &result](const std::string& key) {
|
||||
if (request.contains(key)) {
|
||||
result[key] = request[key];
|
||||
}
|
||||
};
|
||||
|
||||
extract_if_present("ctx_size");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void Server::auto_load_model_if_needed(
|
||||
const std::string& requested_model, const json& request_options) {
|
||||
const std::string& requested_model,
|
||||
const json& request_options) {
|
||||
// Check if this specific model is already loaded (multi-model aware)
|
||||
if (router_->is_model_loaded(requested_model)) {
|
||||
LOG(DEBUG, "Server") << "Model already loaded: " << requested_model << std::endl;
|
||||
@@ -1910,14 +1921,17 @@ void Server::auto_load_model_if_needed(
|
||||
}
|
||||
|
||||
// Download model if not cached (first-time use)
|
||||
// IMPORTANT: Use do_not_upgrade=true to prevent checking HuggingFace for updates
|
||||
// IMPORTANT: Use do_not_upgrade=true to prevent checking the remote registry for updates
|
||||
// This means:
|
||||
// - If model is NOT downloaded: Download it from HuggingFace
|
||||
// - If model IS downloaded: Skip HuggingFace API check entirely (use cached version)
|
||||
// - If model is NOT downloaded: Download it from its recorded registry
|
||||
// - If model IS downloaded: Skip the registry API check entirely (use cached version)
|
||||
// Only the /pull endpoint should check for updates (uses do_not_upgrade=false)
|
||||
if (!model_manager_->backend_self_manages_downloads(info.recipe) &&
|
||||
!model_manager_->is_model_downloaded(requested_model)) {
|
||||
LOG(INFO, "Server") << "Model not cached, downloading from Hugging Face..." << std::endl;
|
||||
LOG(INFO, "Server") << "Model not cached, downloading from "
|
||||
<< remote_registry_display_name(
|
||||
parse_remote_registry_source(info.registry_source))
|
||||
<< "..." << std::endl;
|
||||
LOG(INFO, "Server") << "This may take several minutes for large models." << std::endl;
|
||||
model_manager_->download_registered_model(info, true);
|
||||
LOG(INFO, "Server") << "Model download complete: " << requested_model << std::endl;
|
||||
@@ -2117,6 +2131,8 @@ nlohmann::json Server::model_info_to_json(const std::string& model_id, const Mod
|
||||
{"downloaded", info.downloaded},
|
||||
{"update_available", info.update_available},
|
||||
{"suggested", info.suggested},
|
||||
{"source", info.source.empty() ? info.registry_source : info.source},
|
||||
{"registry_source", info.registry_source},
|
||||
{"labels", info.labels},
|
||||
{"components", public_components},
|
||||
{"recipe_options", info.recipe_options.to_json()},
|
||||
@@ -3962,7 +3978,7 @@ void Server::handle_image_upscale(const httplib::Request& req, httplib::Response
|
||||
auto info = model_manager_->get_model_info(upscale_model_name);
|
||||
|
||||
if (!model_manager_->is_model_downloaded(upscale_model_name)) {
|
||||
LOG(INFO, "Server") << "Upscale model not cached, downloading from Hugging Face..." << std::endl;
|
||||
LOG(INFO, "Server") << "Upscale model not cached, downloading from its remote registry..." << std::endl;
|
||||
model_manager_->download_registered_model(info, true);
|
||||
LOG(INFO, "Server") << "Upscale model download complete: " << upscale_model_name << std::endl;
|
||||
info = model_manager_->get_model_info(upscale_model_name);
|
||||
@@ -4227,6 +4243,52 @@ void Server::handle_pull(const httplib::Request& req, httplib::Response& res) {
|
||||
bool do_not_upgrade = request_json.value("do_not_upgrade", false);
|
||||
bool stream = request_json.value("stream", false);
|
||||
bool subscribe = request_json.value("subscribe", true);
|
||||
bool local_import = request_json.value("local_import", false);
|
||||
|
||||
// Validate and canonicalize remote-registry provenance before anything is
|
||||
// persisted. `source` remains backward-compatible with local origins, while
|
||||
// remote registrations store a canonical huggingface/modelscope value.
|
||||
if (request_json.contains("source") || request_json.contains("registry_source")) {
|
||||
try {
|
||||
std::optional<std::string> normalized_registry;
|
||||
if (request_json.contains("registry_source")) {
|
||||
normalized_registry = remote_registry_source_name(
|
||||
parse_remote_registry_source(
|
||||
request_json["registry_source"].get<std::string>()));
|
||||
}
|
||||
|
||||
if (request_json.contains("source")) {
|
||||
const std::string public_source = request_json["source"].get<std::string>();
|
||||
if (is_remote_registry_source(public_source)) {
|
||||
const std::string normalized_public = remote_registry_source_name(
|
||||
parse_remote_registry_source(public_source));
|
||||
if (normalized_registry && *normalized_registry != normalized_public) {
|
||||
bad_request("'source' and 'registry_source' must identify the same registry");
|
||||
return;
|
||||
}
|
||||
normalized_registry = normalized_public;
|
||||
request_json["source"] = normalized_public;
|
||||
} else if (!local_import && public_source != "local_upload" &&
|
||||
public_source != "local_path" &&
|
||||
public_source != "extra_models_dir") {
|
||||
bad_request("Unsupported model source '" + public_source +
|
||||
"' (expected 'huggingface' or 'modelscope')");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (normalized_registry) {
|
||||
if (!request_json.contains("source") ||
|
||||
is_remote_registry_source(request_json["source"].get<std::string>())) {
|
||||
request_json["source"] = *normalized_registry;
|
||||
}
|
||||
request_json["registry_source"] = *normalized_registry;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
bad_request(e.what());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
LOG(INFO, "Server") << "Pulling model: " << model_name << std::endl;
|
||||
if (!checkpoint.empty()) {
|
||||
@@ -4268,7 +4330,7 @@ void Server::handle_pull(const httplib::Request& req, httplib::Response& res) {
|
||||
// A body carrying a `models` array is a collection file import: its
|
||||
// components may not be registered yet (download_model registers them
|
||||
// from the embedded definitions and canonicalizes the list itself).
|
||||
// A pointer body (HF-backed collection) has no `components` at all —
|
||||
// A pointer body (registry-backed collection) has no `components` at all —
|
||||
// they come from the downloaded manifest. Only pre-canonicalize an
|
||||
// inline `components` list whose entries must already exist.
|
||||
if (request_json.contains("components") && request_json["components"].is_array() &&
|
||||
@@ -4284,7 +4346,6 @@ void Server::handle_pull(const httplib::Request& req, httplib::Response& res) {
|
||||
}
|
||||
|
||||
// Local import mode: CLI has already copied files to HF cache, just resolve and register
|
||||
bool local_import = request_json.value("local_import", false);
|
||||
if (local_import) {
|
||||
std::string hf_cache = model_manager_->get_hf_cache_dir();
|
||||
std::string model_name_clean = model_name.substr(5); // Remove "user." prefix
|
||||
@@ -4370,10 +4431,13 @@ void Server::handle_pull_variants(const httplib::Request& req, httplib::Response
|
||||
if (checkpoint.find('/') == std::string::npos) {
|
||||
res.status = 400;
|
||||
nlohmann::json error = {{"error",
|
||||
"Malformed 'checkpoint': expected a Hugging Face repo id of the form 'owner/name'"}};
|
||||
"Malformed 'checkpoint': expected a repository id of the form 'owner/name'"}};
|
||||
res.set_content(error.dump(), "application/json");
|
||||
return;
|
||||
}
|
||||
const std::string source = req.has_param("source")
|
||||
? req.get_param_value("source") : "huggingface";
|
||||
const auto parsed_source = parse_remote_registry_source(source);
|
||||
if (config_->offline()) {
|
||||
res.status = 400;
|
||||
nlohmann::json error = {{"error", "Lemond is in offline mode, models not downloaded"}, {"code", "lemond_offline"}};
|
||||
@@ -4381,14 +4445,20 @@ void Server::handle_pull_variants(const httplib::Request& req, httplib::Response
|
||||
return;
|
||||
}
|
||||
bool not_found = false;
|
||||
nlohmann::json body = lemon::fetch_pull_variants(checkpoint, not_found);
|
||||
nlohmann::json body = lemon::fetch_pull_variants(
|
||||
checkpoint, remote_registry_source_name(parsed_source), not_found);
|
||||
if (not_found) {
|
||||
res.status = 404;
|
||||
nlohmann::json error = {{"error", "Checkpoint '" + checkpoint + "' not found on Hugging Face"}};
|
||||
nlohmann::json error = {{"error", "Checkpoint '" + checkpoint + "' not found on " +
|
||||
remote_registry_display_name(parsed_source)}};
|
||||
res.set_content(error.dump(), "application/json");
|
||||
return;
|
||||
}
|
||||
res.set_content(body.dump(), "application/json");
|
||||
} catch (const std::invalid_argument& e) {
|
||||
res.status = 400;
|
||||
nlohmann::json error = {{"error", e.what()}};
|
||||
res.set_content(error.dump(), "application/json");
|
||||
} catch (const std::exception& e) {
|
||||
LOG(ERROR, "Server") << "ERROR in handle_pull_variants: " << e.what() << std::endl;
|
||||
res.status = 500;
|
||||
|
||||
@@ -162,6 +162,24 @@ defineTest('collection export normalizes the /models/{id} object into the import
|
||||
});
|
||||
});
|
||||
|
||||
defineTest('model export preserves remote registry provenance and drops local origins', () => {
|
||||
const remote = modelDataUtils.normalizeModelExportPayload({
|
||||
id: 'remote-model', recipe: 'llamacpp', checkpoint: 'org/repo:Q4_K_M',
|
||||
checkpoints: { main: 'org/repo:Q4_K_M' }, source: 'modelscope',
|
||||
registry_source: 'modelscope', components: [],
|
||||
}).payload;
|
||||
assert.equal(remote.source, 'modelscope');
|
||||
assert.equal(remote.registry_source, 'modelscope');
|
||||
|
||||
const local = modelDataUtils.normalizeModelExportPayload({
|
||||
id: 'local-model', recipe: 'llamacpp', checkpoint: 'models--local/file.gguf',
|
||||
checkpoints: { main: 'models--local/file.gguf' }, source: 'local_upload',
|
||||
registry_source: 'huggingface', components: [],
|
||||
}).payload;
|
||||
assert.ok(!('source' in local));
|
||||
assert.ok(!('registry_source' in local));
|
||||
});
|
||||
|
||||
defineTest('regular-model export carries no collection fields', () => {
|
||||
const raw = {
|
||||
id: 'planner', object: 'model', created: 1234567890, owned_by: 'lemonade',
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#include "lemon/model_manager.h"
|
||||
#include "lemon/model_registry.h"
|
||||
#include "lemon/utils/path_utils.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using lemon::ModelManager;
|
||||
using lemon::RegistryFile;
|
||||
using lemon::RemoteRegistrySource;
|
||||
using lemon::json;
|
||||
|
||||
static int g_failures = 0;
|
||||
|
||||
static void check(const char* name, bool ok) {
|
||||
std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", name);
|
||||
if (!ok) ++g_failures;
|
||||
}
|
||||
|
||||
static fs::path make_temp_dir() {
|
||||
fs::path dir = fs::temp_directory_path();
|
||||
dir /= "model_registry_" +
|
||||
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());
|
||||
fs::create_directories(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
static void test_source_parsing_and_cache_names() {
|
||||
check("empty source preserves Hugging Face default",
|
||||
lemon::parse_remote_registry_source("") == RemoteRegistrySource::HuggingFace);
|
||||
check("HF alias parses",
|
||||
lemon::parse_remote_registry_source("HF") == RemoteRegistrySource::HuggingFace);
|
||||
check("ModelScope alias parses",
|
||||
lemon::parse_remote_registry_source("ms") == RemoteRegistrySource::ModelScope);
|
||||
check("Hugging Face cache layout stays backward compatible",
|
||||
lemon::registry_repo_cache_dir_name("org/repo", RemoteRegistrySource::HuggingFace) ==
|
||||
"models--org--repo");
|
||||
check("ModelScope cache namespace cannot collide with Hugging Face",
|
||||
lemon::registry_repo_cache_dir_name("org/repo", RemoteRegistrySource::ModelScope) ==
|
||||
"modelscope--models--org--repo");
|
||||
|
||||
bool rejected = false;
|
||||
try {
|
||||
(void)lemon::parse_remote_registry_source("unknown");
|
||||
} catch (const std::invalid_argument&) {
|
||||
rejected = true;
|
||||
}
|
||||
check("unknown registry is rejected", rejected);
|
||||
}
|
||||
|
||||
static void test_tree_snapshot_fingerprint() {
|
||||
std::vector<RegistryFile> files = {
|
||||
{"model.gguf", 100, "sha256", "abc", false},
|
||||
{"config.json", 20, "sha256", "def", false},
|
||||
};
|
||||
const std::string first = lemon::registry_tree_snapshot_id(
|
||||
RemoteRegistrySource::ModelScope, "master", files);
|
||||
|
||||
std::reverse(files.begin(), files.end());
|
||||
const std::string reordered = lemon::registry_tree_snapshot_id(
|
||||
RemoteRegistrySource::ModelScope, "master", files);
|
||||
check("snapshot fingerprint is independent of API file ordering", first == reordered);
|
||||
|
||||
files[0].size += 1;
|
||||
const std::string changed = lemon::registry_tree_snapshot_id(
|
||||
RemoteRegistrySource::ModelScope, "master", files);
|
||||
check("snapshot fingerprint changes when the remote tree changes", first != changed);
|
||||
check("snapshot id records provider and revision",
|
||||
first.rfind("modelscope-master-", 0) == 0);
|
||||
}
|
||||
|
||||
static void test_registration_persists_remote_provenance() {
|
||||
fs::path temp = make_temp_dir();
|
||||
lemon::utils::set_cache_dir(temp.string());
|
||||
|
||||
ModelManager manager;
|
||||
manager.register_user_model("user.FromModelScope", json{
|
||||
{"source", "modelscope"},
|
||||
{"checkpoint", "org/repo:Q4_K_M"},
|
||||
{"recipe", "llamacpp"},
|
||||
});
|
||||
auto remote = manager.get_model_info("user.FromModelScope");
|
||||
check("remote source is persisted separately from local origin",
|
||||
remote.source.empty() && remote.registry_source == "modelscope");
|
||||
|
||||
manager.register_user_model("user.LocalMirror", json{
|
||||
{"source", "local_upload"},
|
||||
{"registry_source", "modelscope"},
|
||||
{"checkpoint", "org/repo:Q4_K_M"},
|
||||
{"recipe", "llamacpp"},
|
||||
});
|
||||
auto local = manager.get_model_info("user.LocalMirror");
|
||||
check("local origin and remote provenance can coexist",
|
||||
local.source == "local_upload" && local.registry_source == "modelscope");
|
||||
|
||||
fs::remove_all(temp);
|
||||
}
|
||||
|
||||
int main() {
|
||||
test_source_parsing_and_cache_names();
|
||||
test_tree_snapshot_fingerprint();
|
||||
test_registration_persists_remote_provenance();
|
||||
|
||||
if (g_failures == 0) {
|
||||
std::printf("All model registry tests passed.\n");
|
||||
}
|
||||
return g_failures == 0 ? 0 : 1;
|
||||
}
|
||||
Reference in new issue
Block a user