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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion internal/imagegen/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ func NewDiffusersEngine(ctx context.Context, modelName, modelDir string, runtime
return nil, err
}
workerPath := filepath.Join(runtimeManager.RootDir(), "diffusers_worker.py")
cmd := exec.CommandContext(ctx, runtimeManager.PythonPath(), workerPath,
// The engine stays cached across requests, so the worker must outlive the
// request that loaded it. waitReady(ctx) still aborts a load whose caller
// went away, and Close()/the idle evictor stop the process.
cmd := exec.Command(runtimeManager.PythonPath(), workerPath,
"--model-dir", modelDir, "--model-name", modelName,
"--backend", backend, "--port", strconv.Itoa(port))
cmd.Env = WithPythonPath(os.Environ(), overlayDir)
Expand Down
19 changes: 14 additions & 5 deletions internal/imagegen/worker/diffusers_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,21 +107,30 @@ def _safetensors_header(path: Path) -> Dict[str, Any]:

def uses_direct_qwen21_loader(model_dir: str) -> bool:
"""Reports whether model_dir needs load_mlx_native_qwen21 rather than
mflux's own loader. Both layouts it covers keep the text encoder under a
language_model prefix, which mflux's text-to-image loader silently fails to
match (leaving an unloaded, unquantized ~32 GB encoder):
mflux's own loader. The direct loader is required whenever the text encoder
is quantized or nested under a language_model prefix: mflux's text-to-image
loader skips text-encoder quantization and fails to match that prefix
(leaving an unloaded, unquantized ~32 GB encoder).

- pre-converted MLX checkpoints such as mlx-community/Qwen-Image-2.1-MLX-4bit
(diffusers folder layout, mlx-lm style keys, quantization in config.json);
- mflux bundles saved through the edit variant, such as
OsaurusAI/Qwen-Image-2.1-Turbo-mflux-4bit (text encoder plus vision tower).
OsaurusAI/Qwen-Image-2.1-Turbo-mflux-4bit (text encoder plus vision tower);
- mflux text-to-image bundles whose quantized text encoder already uses the
mflux module layout, such as mlx-community/Qwen-Image-2.1-mflux-q4.
"""
root = Path(model_dir)
for name in MLX_NATIVE_COMPONENTS:
if not any((root / name).glob("*.safetensors")):
return False
for shard in sorted((root / "text_encoder").glob("*.safetensors")):
if any(key.startswith("language_model.") for key in _safetensors_header(shard)):
header = _safetensors_header(shard)
if any(key.startswith("language_model.") for key in header):
return True
# Packed weights carry per-layer scales. Stock mflux treats the packed
# uint32 weight as a float tensor, shrinking the embedding output from
# the hidden size (4096) to hidden/8 (512) and failing the first add.
if any(key.endswith(".scales") for key in header):
return True
return False

Expand Down
5 changes: 4 additions & 1 deletion internal/server/handlers_marketplace.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,10 @@ func (s *Server) handleMarketplaceModelDetail(w http.ResponseWriter, r *http.Req
// Quantized weights cannot be converted even though the upstream framework
// tag reports safetensors or pytorch. Keep this verdict in sync with the
// list filter, which rejects the same repositories.
if support.Supported && !strings.EqualFold(inferenceFormat, "gguf") &&
// The native MLX image runtime loads its own quantized checkpoints, so the
// quantized-name rule must not hide a model it can serve.
if support.Supported && support.Runtime != "mlx-image" &&
!strings.EqualFold(inferenceFormat, "gguf") &&
marketplaceLooksLikeQuantizedWeights(marketplaceModelFullName(*details)) {
support = api.LocalInferenceSupport{Mode: "none", Architecture: support.Architecture}
}
Expand Down
63 changes: 63 additions & 0 deletions internal/server/handlers_marketplace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"reflect"
"runtime"
"strconv"
"strings"
"sync/atomic"
Expand Down Expand Up @@ -959,6 +960,68 @@ func TestHandleMarketplaceModelDetailRejectsQuantizedWeights(t *testing.T) {
}
}

func TestHandleMarketplaceModelDetailKeepsNativeMLXImageSupport(t *testing.T) {
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/models/mlx-community/Qwen-Image-2.1-mflux-q4":
_ = json.NewEncoder(w).Encode(csghub.APIResponse[csghub.Model]{
Msg: "OK",
Data: csghub.Model{
ID: 1,
Name: "Qwen-Image-2.1-mflux-q4",
Path: "mlx-community/Qwen-Image-2.1-mflux-q4",
Tags: []csghub.Tag{
{Name: "image-to-image", Category: "task"},
{Name: "mflux", Category: "task"},
{Name: "mlx", Category: "task"},
{Name: "qwen-image", Category: "task"},
{Name: "text-to-image", Category: "task"},
},
},
})
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/models/mlx-community/Qwen-Image-2.1-mflux-q4/tree":
_ = json.NewEncoder(w).Encode(csghub.APIResponse[[]csghub.RepoFile]{Msg: "OK"})
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos/extra":
_ = json.NewEncoder(w).Encode(csghub.APIResponse[[]csghub.RepoExtraItem]{Msg: "OK"})
default:
t.Fatalf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
}
}))
defer apiServer.Close()

s := newTestServer(t)
s.cfg.ServerURL = apiServer.URL
s.localInferenceLimits = func() marketplaceLocalInferenceLimits {
return marketplaceLocalInferenceLimits{maxDownloadBytes: 200 << 30, maxMemoryBytes: 64 << 30}
}

req := httptest.NewRequest(http.MethodGet, "/api/marketplace/models/mlx-community/Qwen-Image-2.1-mflux-q4", nil)
req.SetPathValue("namespace", "mlx-community")
req.SetPathValue("name", "Qwen-Image-2.1-mflux-q4")
w := httptest.NewRecorder()

s.handleMarketplaceModelDetail(w, req)

if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusOK, w.Body.String())
}

var resp marketplaceModelDetailResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("decode response: %v", err)
}
if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
if !resp.LocalInference.Supported || resp.LocalInference.Runtime != "mlx-image" || resp.LocalInference.Mode != "image" {
t.Fatalf("local_inference = %#v, want mlx-image", resp.LocalInference)
}
return
}
if resp.LocalInference.Supported {
t.Fatalf("local_inference = %#v, want unsupported outside darwin/arm64", resp.LocalInference)
}
}

func TestHandleMarketplaceModelDetailUsesRoutedTaskTag(t *testing.T) {
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
Expand Down
20 changes: 19 additions & 1 deletion internal/server/marketplace_local_inference.go
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,10 @@ func marketplaceDecideLocalInference(m csghub.Model) marketplaceLocalInferenceDe
}
// GGUF repositories are exempt: a quantized repository name there describes
// the quantization of the GGUF files, which llama.cpp can load directly.
if d.format != string(model.FormatGGUF) && marketplaceLooksLikeQuantizedWeights(marketplaceModelFullName(m)) {
// Native MLX Qwen-Image-2.1 checkpoints are exempt for the same reason: the
// mlx-image runtime loads their quantized weights as-is.
if d.format != string(model.FormatGGUF) && !marketplaceNativeMLXImageModel(m, d.task) &&
marketplaceLooksLikeQuantizedWeights(marketplaceModelFullName(m)) {
d.exclude = true
return d
}
Expand Down Expand Up @@ -1388,6 +1391,21 @@ func marketplaceLooksLikeQuantizedWeights(repo string) bool {
return false
}

// marketplaceNativeMLXImageModel reports whether the repository is an MLX
// Qwen-Image-2.1 checkpoint, which the mlx-image runtime loads without
// conversion. Other MLX image checkpoints and MLX text models have no runtime
// here, so they keep the quantized-name verdict.
func marketplaceNativeMLXImageModel(m csghub.Model, task string) bool {
switch strings.ToLower(strings.TrimSpace(task)) {
case "text-to-image", "image-to-image":
default:
return false
}
return model.ImageBackendForMetadata(
m.Path, m.Metadata.ClassName, marketplaceLibraryName(&m), task,
) == model.ImageBackendMLXQwen21
}

// marketplaceRepoHasToken reports whether token appears as one whole segment of
// a repository path such as "Qwen/Qwen2.5-72B-Instruct-Int4".
func marketplaceRepoHasToken(repo, token string) bool {
Expand Down
43 changes: 43 additions & 0 deletions internal/server/marketplace_local_inference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,49 @@ func TestMarketplaceLocalInferenceFilterExcludesQuantizedWeights(t *testing.T) {
}
}

func TestMarketplaceDecideLocalInferenceKeepsNativeMLXImageModel(t *testing.T) {
mlxImageTags := func() []csghub.Tag {
return []csghub.Tag{
localInferenceTag("image-to-image", "task"),
localInferenceTag("mflux", "task"),
localInferenceTag("mlx", "task"),
localInferenceTag("qwen-image", "task"),
localInferenceTag("text-to-image", "task"),
}
}
tests := []struct {
name string
model csghub.Model
wantExclude bool
}{
{
name: "native mlx qwen image stays",
model: localInferenceModel("mlx-community/Qwen-Image-2.1-mflux-q4", mlxImageTags()...),
},
{
name: "mlx text model stays excluded",
model: localInferenceModel("mlx-community/GLM-5.2-mxfp4",
localInferenceTag("safetensors", "framework"),
localInferenceTag("text-generation", "task")),
wantExclude: true,
},
{
name: "other mlx image stays excluded",
model: localInferenceModel("mlx-community/FLUX.1-schnell-4bit",
localInferenceTag("safetensors", "framework"),
localInferenceTag("text-to-image", "task")),
wantExclude: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := marketplaceDecideLocalInference(tt.model).exclude; got != tt.wantExclude {
t.Fatalf("exclude = %v, want %v", got, tt.wantExclude)
}
})
}
}

func TestMarketplaceLocalInferenceFilterProbesTTSArchitecture(t *testing.T) {
for _, format := range []string{"safetensors", "gguf"} {
t.Run(format, func(t *testing.T) {
Expand Down
Loading