"""Native MOSS Image Edit backend for the unified ZeroGPU worker. prepare() only downloads and inspects files on CPU. generate() must be called inside the app's single GPU allocation; it never requests another GPU. Model components are transient, keeping a second 27 GB pipeline out of the parent process and preserving the Qwen pipeline and its adapter state. """ from __future__ import annotations import gc from fractions import Fraction import hashlib import json import math import os from pathlib import Path import secrets import tempfile import threading from urllib.parse import quote, unquote, urlparse from PIL import Image, ImageOps from guidance import guidance_values from moss_lora import inspect_lora, read_header MODEL_ID = "OpenMOSS-Team/MOSS-Image-SFT" MODEL_REVISION = "f972bd4b4b9e3852133cc5da954d87bc32cd8fb9" EDIT_ID = "chinoll/Moss-Image-Edit" EDIT_REVISION = "3be9c40037e1b89b17aa85ff6f8ee805872aa558" EDIT_CONTRACT = "ref-prefix-only-t0__target-text-original-moss-v1" MAX_REFERENCES = 4 MAX_OUTPUT_EDGE = 4096 MAX_OUTPUT_AREA = 4 * 1024 ** 2 MAX_WORK_EDGE = 1024 MAX_LORA_BYTES = 1024 * 1024 * 1024 MAX_TOTAL_LORA_BYTES = 3 * MAX_LORA_BYTES _DOWNLOAD_LOCK = threading.Lock() _PATHS = None def _pil(value): if isinstance(value, (tuple, list)): value = value[0] if value else None if isinstance(value, dict): value = value.get("path") or value.get("name") or value.get("image") if value is None: return None if isinstance(value, Image.Image): image = value elif isinstance(value, (str, os.PathLike)): with Image.open(value) as opened: image = opened.copy() elif hasattr(value, "shape"): image = Image.fromarray(value) else: raise ValueError("MOSS needs an uploaded image, not a remote image URL.") return ImageOps.exif_transpose(image).convert("RGB") def request_images(data): values = [data.get("input_image_1"), data.get("input_image_2")] values.extend(data.get("input_images_extra") or []) images = [image for value in values if (image := _pil(value)) is not None] if not 1 <= len(images) <= MAX_REFERENCES: raise ValueError("MOSS Image Edit needs one to four reference images.") return images def request_canvas(data): return _output_size(data, request_images(data)[0]) def _output_size(data, image): aspect = str(data.get("aspect_ratio") or "Match Image 1") mp = float(data.get("target_megapixels", 0)) if not math.isfinite(mp) or not (mp == 0 or 0.0625 <= mp <= 4): raise ValueError("MOSS output size must be 0 (match input), or 0.0625–4 megapixels.") if aspect == "Custom": width = int(data.get("custom_width", 1024)) height = int(data.get("custom_height", data.get("height", 1024))) if (min(width, height) < 64 or max(width, height) > MAX_OUTPUT_EDGE or width * height > MAX_OUTPUT_AREA): raise ValueError("MOSS custom output must use 64–4096 pixel sides and at most 4 megapixels.") return width, height area = min(image.width * image.height, MAX_OUTPUT_AREA) if mp: area = min(area, mp * 1024 ** 2) if aspect == "Match Image 1": scale = min(math.sqrt(area / (image.width * image.height)), MAX_OUTPUT_EDGE / max(image.size)) return tuple(max(1, int(side * scale)) for side in image.size) try: left, right = map(Fraction, aspect.split(":")) ratio = left / right except (ValueError, ZeroDivisionError) as error: raise ValueError("Choose a valid output aspect ratio.") from error if ratio <= 0 or max(ratio.numerator, ratio.denominator) > MAX_OUTPUT_EDGE: raise ValueError("Choose a valid output aspect ratio.") width, height = ratio.numerator, ratio.denominator units = max(1, int(min(math.sqrt(area / (width * height)), MAX_OUTPUT_EDGE / max(width, height)))) if width * height * units ** 2 > MAX_OUTPUT_AREA: raise ValueError("Choose an output aspect ratio within MOSS's size limit.") return width * units, height * units def _working_sizes(output_size, max_edge): scale = min(1.0, max_edge / max(output_size)) visible = tuple(max(1, round(side * scale)) for side in output_size) aligned = tuple((side + 15) // 16 * 16 for side in visible) return visible, aligned def _extend_edges(image, size, *, centered=False): """Pad with edge pixels so the source content keeps its full frame.""" if image.size == size: return image width, height = image.size left, top = ((size[0] - width) // 2, (size[1] - height) // 2) if centered else (0, 0) right, bottom = left + width, top + height horizontal = Image.new(image.mode, (size[0], height)) horizontal.paste(image, (left, 0)) if left: horizontal.paste(image.crop((0, 0, 1, height)).resize((left, height)), (0, 0)) if right < size[0]: horizontal.paste(image.crop((width - 1, 0, width, height)).resize((size[0] - right, height)), (right, 0)) if height == size[1]: return horizontal result = Image.new(image.mode, size) result.paste(horizontal, (0, top)) if top: result.paste(horizontal.crop((0, 0, size[0], 1)).resize((size[0], top)), (0, 0)) if bottom < size[1]: result.paste(horizontal.crop((0, height - 1, size[0], height)).resize((size[0], size[1] - bottom)), (0, bottom)) return result def _prepare_primary(image, visible, aligned, *, match_source): if match_source: picture = image.resize(visible, Image.Resampling.LANCZOS) else: scale = min(visible[0] / image.width, visible[1] / image.height) size = tuple(max(1, round(side * scale)) for side in image.size) picture = _extend_edges(image.resize(size, Image.Resampling.LANCZOS), visible, centered=True) return _extend_edges(picture, aligned) def _finish_output(result, visible, output_size): if result.size != visible: result = result.crop((0, 0, *visible)) return result.resize(output_size, Image.Resampling.LANCZOS) if result.size != output_size else result def estimate_gpu_seconds(data): images = request_images(data) _, (width, height) = _working_sizes(_output_size(data, images[0]), MAX_WORK_EDGE) _, _, passes = guidance_values(data, default=4, min_cfg=0, max_cfg=20) # Conservative allocation estimate, including on-demand component loading. estimate = 80 + int(data.get("steps", 30)) * passes * 2 * width * height / 1024 ** 2 estimate += 6 * len(images) return max(90, min(400, math.ceil(estimate))) def init_model(): """Download a pinned snapshot only; never instantiate weights in the parent.""" global _PATHS if _PATHS is not None: return dict(_PATHS) from huggingface_hub import snapshot_download with _DOWNLOAD_LOCK: if _PATHS is None: token = os.environ.get("HF_TOKEN") or None model_dir = snapshot_download( MODEL_ID, revision=MODEL_REVISION, token=token, allow_patterns=["model_index.json", "transformer/*", "text_encoder/*", "tokenizer/*", "scheduler/*", "vae/*"], ) edit_dir = snapshot_download( EDIT_ID, revision=EDIT_REVISION, token=token, allow_patterns=["adapter_config.json", "adapter_model.safetensors"], ) config = json.loads((Path(edit_dir) / "adapter_config.json").read_text()) if (config.get("format") != "moss-edit-lora" or config.get("format_version") != 1 or (config.get("metadata") or {}).get("edit_contract") != EDIT_CONTRACT): raise ValueError("The built-in MOSS edit adapter has an unsupported format.") weights = Path(edit_dir) / "adapter_model.safetensors" digest = hashlib.sha256() with weights.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): digest.update(block) if digest.hexdigest() != config.get("weights_sha256"): raise ValueError("The built-in MOSS edit adapter failed its checksum check.") header, _ = read_header(weights) embedded = json.loads((header.get("__metadata__") or {}).get("adapter_config", "null")) if embedded != {key: value for key, value in config.items() if key != "weights_sha256"}: raise ValueError("The built-in MOSS edit adapter's metadata is inconsistent.") _PATHS = {"model": model_dir, "edit": edit_dir} return dict(_PATHS) def _upload_path(value): if isinstance(value, dict): value = value.get("path") or value.get("name") if value is not None and not isinstance(value, (str, os.PathLike)): value = getattr(value, "name", None) return str(value) if value else "" def _bucket_url(reference): ref = str(reference).strip() if ref.startswith("hf://buckets/"): ref = ref[5:] if ref.startswith("buckets/"): parts = ref.split("/", 3) if len(parts) != 4 or not parts[3] or ".." in parts[3].split("/"): raise ValueError("Use buckets/owner/name/path/file.safetensors.") return f"https://huggingface.co/buckets/{parts[1]}/{parts[2]}/resolve/{quote(parts[3], safe='/')}" return ref def _check_lora_size(path): size = Path(path).stat().st_size if size > MAX_LORA_BYTES: raise ValueError("Each MOSS LoRA file must be at most 1024 MiB.") return size def _download_direct(reference): """Cache an exact HF bucket/Civitai weight URL; never send HF auth elsewhere.""" import requests url = _bucket_url(reference) parsed = urlparse(url) host = (parsed.hostname or "").lower() civitai = host in {"civitai.com", "civitai.red", "civitai.green", "civitai.work"} bucket = host == "huggingface.co" and parsed.path.startswith("/buckets/") if parsed.scheme != "https" or parsed.username or parsed.password or not (civitai or bucket): raise ValueError("Use an exact HTTPS Hugging Face bucket or Civitai download link.") if bucket: parts = unquote(parsed.path).strip("/").split("/") if len(parts) < 5 or parts[3] != "resolve" or ".." in parts: raise ValueError("Use the bucket's exact resolve URL for the safetensors file.") cache = Path(tempfile.gettempdir()) / "moss-lora-downloads" cache.mkdir(parents=True, exist_ok=True) destination = cache / (hashlib.sha256(url.encode()).hexdigest() + ".safetensors") if destination.is_file(): _check_lora_size(destination) read_header(destination) return str(destination) token = os.environ.get("HF_TOKEN" if bucket else "CIVITAI_TOKEN", "").strip() headers = {"User-Agent": "MOSS-Image-Edit-Space"} if token: headers["Authorization"] = "Bearer " + token temporary = destination.with_name(destination.name + "." + secrets.token_hex(8) + ".part") try: # Requests removes Authorization when a redirect changes hostname. with requests.get(url, headers=headers, stream=True, timeout=(20, 180)) as response: if response.status_code != 200: raise ValueError(f"LoRA download from {host} returned HTTP {response.status_code}.") if "text/html" in response.headers.get("content-type", "").lower(): raise ValueError("That link returned a webpage. Use its download URL or upload the file.") advertised = response.headers.get("Content-Length", "") if advertised.isdigit() and int(advertised) > MAX_LORA_BYTES: raise ValueError("Each MOSS LoRA file must be at most 1024 MiB.") written = 0 with temporary.open("wb") as stream: for block in response.iter_content(1024 * 1024): if block: written += len(block) if written > MAX_LORA_BYTES: raise ValueError("Each MOSS LoRA file must be at most 1024 MiB.") stream.write(block) read_header(temporary) temporary.replace(destination) except requests.RequestException as error: # URLs can contain access tokens, so do not echo requests' exception. raise ValueError(f"Could not download the MOSS LoRA from {host} ({type(error).__name__}).") from None finally: temporary.unlink(missing_ok=True) return str(destination) def _resolve_lora(uploaded, reference): """Return a cached weight path and optional PEFT metadata, before GPU use.""" from huggingface_hub import get_hf_file_metadata, hf_hub_download, hf_hub_url, list_repo_files from huggingface_hub.errors import EntryNotFoundError path = _upload_path(uploaded) if path: if not Path(path).is_file() or Path(path).suffix.lower() != ".safetensors": raise ValueError("Upload a readable .safetensors MOSS LoRA.") _check_lora_size(path) sidecar = Path(path).with_name("adapter_config.json") return path, json.loads(sidecar.read_text()) if sidecar.is_file() else {} ref = str(reference or "").strip().rstrip("/") if not ref: raise ValueError("Choose a MOSS LoRA file or repository for each enabled slot.") token = os.environ.get("HF_TOKEN") or None ref = _bucket_url(ref) parsed = urlparse(ref) if (parsed.hostname == "huggingface.co" and parsed.path.startswith("/buckets/")) or ( parsed.hostname in {"civitai.com", "civitai.red", "civitai.green", "civitai.work"}): return _download_direct(ref), {} revision, filename = "main", None if ref.startswith(("https://", "http://")): url = urlparse(ref) parts = unquote(url.path).strip("/").split("/") if url.scheme != "https" or url.netloc != "huggingface.co" or len(parts) < 2: raise ValueError("Use a Hugging Face MOSS LoRA reference or upload its safetensors file.") repo = "/".join(parts[:2]) if len(parts) > 2: if len(parts) < 5 or parts[2] not in {"blob", "resolve"}: raise ValueError("Use an exact Hugging Face file URL.") revision, filename = parts[3], "/".join(parts[4:]) else: parts = ref.split("/") if len(parts) < 2: raise ValueError("Enter owner/repo or owner/repo/file.safetensors.") repo = "/".join(parts[:2]) filename = "/".join(parts[2:]) or None if filename is None: files = [name for name in list_repo_files(repo, revision=revision, token=token) if name.endswith(".safetensors")] if len(files) != 1: raise ValueError(f"Choose an exact safetensors filename in {repo}; found {len(files)} files.") filename = files[0] if not filename.endswith(".safetensors") or ".." in Path(filename).parts: raise ValueError("Choose a .safetensors LoRA file.") metadata = get_hf_file_metadata(hf_hub_url(repo, filename, revision=revision), token=token) if metadata.size is None: raise ValueError("Could not verify the MOSS LoRA file size before downloading it.") if metadata.size > MAX_LORA_BYTES: raise ValueError("Each MOSS LoRA file must be at most 1024 MiB.") path = hf_hub_download(repo, filename=filename, revision=revision, token=token) _check_lora_size(path) sidecar_name = str(Path(filename).parent / "adapter_config.json").replace("\\", "/") try: sidecar = hf_hub_download(repo, filename=sidecar_name, revision=revision, token=token) except EntryNotFoundError: return path, {} return path, json.loads(Path(sidecar).read_text()) def prepare(data): """Validate the request and resolve all downloads outside GPU allocation.""" prepared = dict(data) images = request_images(prepared) output_size = _output_size(prepared, images[0]) prompt = str(prepared.get("prompt") or "").strip() if not prompt: raise ValueError("Enter an instruction describing how to edit the reference image.") steps = int(prepared.get("steps", 30)) negative, cfg, _ = guidance_values(prepared, default=4, min_cfg=0, max_cfg=20) shift = float(prepared.get("moss_shift", 5)) _, aligned = _working_sizes(output_size, MAX_WORK_EDGE) edge = int(prepared.get("moss_reference_max_edge") or max(aligned)) if not 1 <= steps <= 100: raise ValueError("MOSS steps must be between 1 and 100.") if not math.isfinite(shift) or not 0 < shift <= 20: raise ValueError("MOSS shift must be greater than 0 and at most 20.") if not 16 <= edge <= 1024 or edge % 16: raise ValueError("MOSS reference edge must be a multiple of 16 between 16 and 1024.") seed = int(prepared.get("seed", 0)) if not prepared.get("randomize_seed") and not 0 <= seed < 2 ** 32: raise ValueError("MOSS seed must be between 0 and 4294967295.") # Validate optional adapters first so an incompatible upload fails quickly. specs = [] total_lora_bytes = 0 for slot in range(1, 4): scale = float(prepared.get(f"user_lora_{slot}_scale") or 0) if not math.isfinite(scale) or not 0 <= scale <= 4: raise ValueError("MOSS LoRA strengths must be between 0 and 4.") if scale == 0: continue path, sidecar = _resolve_lora(prepared.get(f"user_lora_{slot}_file"), prepared.get(f"user_lora_{slot}_ref")) total_lora_bytes += _check_lora_size(path) if total_lora_bytes > MAX_TOTAL_LORA_BYTES: raise ValueError("Enabled MOSS LoRAs must total at most 3072 MiB.") plan = inspect_lora(path, sidecar=sidecar) specs.append({"path": path, "scale": scale, "plan": plan}) paths = init_model() prepared.update(prompt=prompt, steps=steps, guidance_scale=cfg, negative_prompt_text=negative or "", moss_shift=shift, moss_reference_max_edge=edge, _moss_model_dir=paths["model"], _moss_edit_dir=paths["edit"], _moss_loras=specs, _moss_prepared=True) return prepared def generate(data, progress=None): """Run image editing in an existing GPU allocation; return image/seed/image.""" if not data.get("_moss_prepared"): raise ValueError("Call moss_backend.prepare before GPU allocation.") negative, cfg, _ = guidance_values(data, default=4, min_cfg=0, max_cfg=20) import torch from diffusers import AutoencoderKLFlux2 from transformers import AutoModel, AutoTokenizer from pipeline_moss_image import MOSSImageScheduler, MOSSImageTransformer from moss_runtime.components import TextComponents, encode_prompts, torch_dtype from moss_runtime.model import MossEditModel from moss_runtime.processing import decode_latents, encode_image, image_to_tensor, prepare_reference from moss_runtime.sampling import sample_latents from moss_runtime.weights import inject_lora, load_adapter, read_adapter_options from moss_lora import attach_loras def report(fraction, message): if progress is not None: progress(fraction, desc=message) def release(): gc.collect() torch.cuda.empty_cache() snapshot, adapter = data["_moss_model_dir"], data["_moss_edit_dir"] images = request_images(data) output_size = _output_size(data, images[0]) visible, aligned = _working_sizes(output_size, MAX_WORK_EDGE) width, height = aligned primary = _prepare_primary(images[0], visible, aligned, match_source=(data.get("aspect_ratio") or "Match Image 1") == "Match Image 1") seed = secrets.randbelow(2 ** 31) if data.get("randomize_seed") else int(data.get("seed", 0)) encoder = text = vae = transformer = editor = conditions = latents = refs = decoded = None handles = [] # Reference-cache stamps need tensor version counters, so inference_mode # must be disabled even when the enclosing app uses it for other models. with torch.inference_mode(False), torch.no_grad(): try: report(0.02, "Loading MOSS prompt encoder") tokenizer = AutoTokenizer.from_pretrained(snapshot, subfolder="tokenizer", local_files_only=True) encoder = AutoModel.from_pretrained( snapshot, subfolder="text_encoder", local_files_only=True, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, ).eval().to("cuda") text = TextComponents(encoder, tokenizer, torch.device("cuda"), torch.device("cuda"), metadata={"text_dim": 4096}) conditions = encode_prompts( text, [data["prompt"]], # MOSS also uses unconditional conditioning for CFG below 1. negative_prompts=[negative or ""] if cfg != 1 else None, max_sequence_length=4096, device="cuda", ) # Drop the encoder before loading the denoiser. Do not copy the # large transient encoder back to host RAM just to discard it. text = encoder = None release() report(0.13, "Encoding MOSS reference images") vae = AutoencoderKLFlux2.from_pretrained( snapshot, subfolder="vae", torch_dtype=torch.float32, local_files_only=True, low_cpu_mem_usage=True, ).eval().to("cuda") vae.disable_tiling() refs = [encode_image(vae, image_to_tensor(primary), sample_posterior=False)] refs.extend(encode_image(vae, prepare_reference(image, data["moss_reference_max_edge"]), sample_posterior=False) for image in images[1:]) report(0.2, "Loading MOSS editing model") transformer = MOSSImageTransformer.from_pretrained( snapshot, subfolder="transformer", torch_dtype=torch.bfloat16, local_files_only=True, low_cpu_mem_usage=True, ) options, metadata = read_adapter_options(adapter) if metadata.get("edit_contract") != EDIT_CONTRACT: raise ValueError("Incompatible MOSS edit reference format.") options = {**options, "param_dtype": torch_dtype(options["param_dtype"])} inject_lora(transformer, **options) load_adapter(transformer, adapter) transformer.requires_grad_(False).eval().to("cuda") handles = attach_loras(transformer, data.get("_moss_loras", [])) editor = MossEditModel(transformer).eval() scheduler = MOSSImageScheduler.from_pretrained( snapshot, subfolder="scheduler", local_files_only=True, shift=data["moss_shift"], training_shift=1.0, ) latents = sample_latents( editor, scheduler, refs, conditions.positive, conditions.negative, height=height, width=width, steps=data["steps"], cfg=cfg, seed=seed, device="cuda", latent_channels=int(transformer.config.latent_channels), use_kv_cache=True, progress=lambda done, total: report(0.25 + 0.67 * done / total, f"MOSS editing: {done}/{total}"), ) for handle in handles: handle.remove() handles.clear() editor = transformer = refs = conditions = None release() report(0.94, "Decoding edited image") if data.get("vae_tiling"): vae.enable_tiling() decoded = decode_latents(vae, latents) pixels = (decoded[0].float().cpu() + 1).mul_(0.5).clamp_(0, 1) result = Image.fromarray((pixels.permute(1, 2, 0).numpy() * 255).round().astype("uint8")) result = _finish_output(result, visible, output_size) report(1.0, "MOSS edit complete") return result, seed, result finally: for handle in handles: handle.remove() encoder = text = vae = transformer = editor = conditions = latents = refs = decoded = None release()