Ming-Image-0.2-Design-Layer / ming_engine.py
akhaliq's picture
akhaliq HF Staff
Official Ming-Image adapter pinned to 041945f, layer-decompose task
6307c74 verified
Raw History Blame Contribute Delete
5.88 kB
"""Runtime adapter for the official inclusionAI/Ming-Image implementation.
The Layer checkpoint is a component package rather than a stock Diffusers
pipeline. This module downloads the authors' inference code at an immutable
commit, then uses their own model loader and generation entry point with the
layer-decompose task: one input image and a layer specification in, the
composite plus editable RGBA layers out.
"""
from __future__ import annotations
import importlib
import os
from pathlib import Path, PurePosixPath
import shutil
import sys
import tempfile
import threading
from types import SimpleNamespace
from typing import Any
import urllib.request
import zipfile
import torch
MODEL_ID = "inclusionAI/Ming-Image-0.2-Design-Layer"
SOURCE_COMMIT = "041945f5c36d20cbf0fc6debc0a810a747e19644"
SOURCE_URL = f"https://github.com/inclusionAI/Ming-Image/archive/{SOURCE_COMMIT}.zip"
_engine: Any = None
_engine_lock = threading.Lock()
def _safe_extract(archive: zipfile.ZipFile, destination: Path) -> None:
"""Reject absolute or parent-traversing paths before extracting."""
for member in archive.infolist():
path = PurePosixPath(member.filename)
if path.is_absolute() or ".." in path.parts:
raise RuntimeError(f"Unsafe path in official source archive: {member.filename}")
archive.extractall(destination)
def _official_source_directory() -> Path:
cache = Path(os.environ.get("HF_HOME", "/tmp/huggingface")) / "ming-image-source"
cache.mkdir(parents=True, exist_ok=True)
final_root = cache / f"Ming-Image-{SOURCE_COMMIT}"
if (final_root / "infer.py").is_file():
return final_root
with tempfile.TemporaryDirectory(prefix="ming-source-", dir=cache) as temporary:
temporary_path = Path(temporary)
archive_path = temporary_path / "source.zip"
request = urllib.request.Request(
SOURCE_URL,
headers={"User-Agent": "Ming-Image-Hugging-Face-Space/1.0"},
)
with urllib.request.urlopen(request, timeout=120) as response, archive_path.open("wb") as output:
shutil.copyfileobj(response, output)
extracted = temporary_path / "extracted"
extracted.mkdir()
with zipfile.ZipFile(archive_path) as archive:
_safe_extract(archive, extracted)
candidates = [
path for path in extracted.iterdir()
if path.is_dir() and (path / "infer.py").is_file()
]
if len(candidates) != 1:
raise RuntimeError("Could not locate infer.py in the official Ming-Image source archive")
if final_root.exists():
shutil.rmtree(final_root)
candidates[0].rename(final_root)
return final_root
def _load_official_module():
source = _official_source_directory()
source_string = str(source)
if source_string not in sys.path:
sys.path.insert(0, source_string)
module = importlib.import_module("infer")
if Path(module.__file__).resolve().parent != source.resolve():
raise RuntimeError(f"Imported an unexpected infer module: {module.__file__}")
return module
class OfficialMingEngine:
"""Owns the official model, processor, profile, and generation functions."""
def __init__(self):
self.runtime = _load_official_module()
model_directory = self.runtime.resolve_model_directory(MODEL_ID)
self.profile = self.runtime.load_checkpoint_capabilities(model_directory)
self.profile.validate_task(
"layer-decompose",
has_reference_image=True,
num_layers=1,
)
arguments = SimpleNamespace(
processor=None,
dtype="bfloat16",
attn_implementation="eager",
device="cuda",
device_map="balanced",
num_gpus=1,
revision=None,
cache_dir=None,
local_files_only=False,
)
self.model, self.processor = self.runtime.load_model_and_processor(
model_directory,
arguments,
)
self.model.eval()
self.model.requires_grad_(False)
def generate(
self,
*,
prompt: str,
input_image,
resolution: int,
steps: int,
guidance_scale: float,
seed: int,
num_layers: int,
):
sampling = self.profile.resolve_sampling_parameters(
steps=int(steps),
cfg=float(guidance_scale),
)
self.profile.validate_task(
"layer-decompose",
has_reference_image=True,
num_layers=int(num_layers),
)
with torch.inference_mode():
images = self.runtime.run_generation(
self.model,
self.processor,
self.profile,
task="layer-decompose",
prompt=prompt,
input_image=input_image,
resolution=int(resolution),
sampling=sampling,
seed=int(seed),
num_layers=int(num_layers),
dtype=torch.bfloat16,
)
expected_outputs = int(num_layers) + 1
if len(images) != expected_outputs:
raise RuntimeError(f"Expected {expected_outputs} output image(s), received {len(images)}")
return images
def get_engine() -> OfficialMingEngine:
"""Load once per process; callers check CUDA availability before calling."""
global _engine
if _engine is None:
with _engine_lock:
if _engine is None:
print(
f"Loading {MODEL_ID} with official Ming-Image code at {SOURCE_COMMIT}",
flush=True,
)
_engine = OfficialMingEngine()
print("Ming-Image layer pipeline ready", flush=True)
return _engine