m64_06024fa73190 / moss_image_server.py
260 lines, 13.6 KBraw
1"""OpenAI-compatible /v1/images/generations front end for the MOSS-Image family.23ONE SERVER, SEVERAL CHECKPOINTS. MOSS-Image-Base, MOSS-Image-SFT (OpenMOSS-Team) and4Kromoss (lodestones) share an architecture, an inference pipeline, a text encoder, a5VAE and a repo layout, so which one is served is purely MODEL_DIR. Kromoss is a full6fine-tune of MOSS-Image-Base at 1024 px — same architecture, pipeline, text7encoder (Qwen3.5-9B) and VAE (the FLUX.2 SMALL decoder) as MOSS-Image-SFT, published as8the EMA weights at update 11000 over 704k training images. Author-measured on9PartiPrompts (100 prompts, CLIP ViT-L/14): 27.90 against MOSS-Image-Base's 27.19 at 5010steps, and 28.13 with the DMD2 LoRA.1112THREE SAMPLER CONTRACTS OVER ONE SET OF WEIGHTS, selected by MOSS_LORA, straight from13the README's settings table:1415 "" full model 50 steps, CFG 3, negative branch skipping layer 2216 dmd2 + LoRA 8 steps, CFG 1, NO negative branch <- the author's pick17 dmd + LoRA 8 steps, CFG 1, NO negative branch1819Flow-matching Euler with shift 5 in every case; shift is not a request field because it20already lives in the scheduler config, and the pipeline reads it from there.2122uncond_skip_layers IS NOT A NEGATIVE PROMPT KNOB. It defaults to (22,) and REPLACES CFG's23negative-prompt prediction with a skipped-block prediction of the positive prompt, which24is why the full model still costs two forwards per step while ignoring what you put in25negative_prompt. Pass null or [] to get an ordinary negative branch back. Under the26LoRAs, guidance_scale is 1.0 so there is no second branch at all and the field is moot —27the server sets it to null for them, matching the README.2829THE LoRAs ARE APPLIED UNMERGED, VIA FORWARD HOOKS, using the author's own apply_lora from30the model card. That is not a style choice: the card is explicit that the delta is close31to bf16's rounding step, so merging it into the bf16 weights would quietly lose most of32it. Both are rank 128 / alpha 128 fp32 with kohya keys, and only one is used at a time.3334The text encoder is Qwen3.5-9B loaded as a transformers Qwen3_5Model — a PIPELINE35COMPONENT, not a served LLM, so this rig's vLLM gap on the qwen3_5 architecture (the wall36q-judger and the FLUX 3 prompt upsampler both hit) never applies here.3738Dtypes follow the card exactly: transformer and text encoder in bfloat16, VAE in float32,39and the initial noise generated on CPU in float32.4041LICENSE: Apache-2.0 for both the weights and the bundled inference code42(pipeline_moss_image.py, from MOSS-Image-SFT), and not gated — one of the genuinely43unencumbered image models on this rig, unlike flux3-klein (non-commercial) or lens (MIT44but research-only).4546Defaults are hardcoded below and echoed per call under "params_used"; query them via47GET /v1/config.48"""49import base64, io, os, threading, time50from typing import List, Optional5152import torch53from fastapi import FastAPI, HTTPException54from fastapi.responses import JSONResponse55from pydantic import BaseModel, Field56from safetensors.torch import load_file57import uvicorn58from diffusers import DiffusionPipeline5960# lora file, default steps, default CFG, default uncond_skip_layers61VARIANTS = {62 "": {"lora": None, "steps": 50, "cfg": 3.0, "skip": [22],63 "about": "full model, negative branch skipping layer 22"},64 "dmd2": {"lora": "8-steps-dmd2-lora.safetensors", "steps": 8, "cfg": 1.0, "skip": None,65 "about": "8-step DMD2 turbo LoRA (DMD plus a GAN stage against real images)"},66 "dmd": {"lora": "8-steps-dmd-lora.safetensors", "steps": 8, "cfg": 1.0, "skip": None,67 "about": "8-step data-space DMD turbo LoRA"},68}6970MOSS_LORA = os.environ.get("MOSS_LORA", "")71# The turbo LoRAs ship in the Kromoss repo but were distilled from72# MOSS-Image-Base, so they transfer across the family; point this at whichever73# directory actually holds them.74MOSS_LORA_DIR = os.environ.get("MOSS_LORA_DIR", os.environ.get("MODEL_DIR", "/model"))75if MOSS_LORA not in VARIANTS:76 raise SystemExit(f"MOSS_LORA must be one of {list(VARIANTS)}; got {MOSS_LORA!r}")77SPEC = VARIANTS[MOSS_LORA]78MODEL_DIR = os.environ.get("MODEL_DIR", "/model")79PORT = int(os.environ.get("PORT", "9218"))80SERVED_MODEL_ID = os.environ.get("SERVED_MODEL_ID",81 "moss-image" + (f"-{MOSS_LORA}" if MOSS_LORA else ""))82VAE_TILE = 16 # the pipeline rejects height/width that are not multiples of 168384app = FastAPI()85_lock = threading.Lock()86_state = {}878889def apply_lora(transformer, path, strength=1.0):90 """Kromoss's own apply_lora, verbatim in behaviour.9192 Registers a forward hook per adapted module instead of merging, because the card93 states the delta is close to bf16's rounding step — merging would lose it.94 """95 state = load_file(path, device="cuda")96 modules = dict(transformer.named_modules())97 n = 098 for key in [k for k in state if k.endswith(".lora_down.weight")]:99 name = key[len("diffusion_model."):-len(".lora_down.weight")]100 down, up = state[key].float(), state[key.replace("lora_down", "lora_up")].float()101 scale = strength * state[f"diffusion_model.{name}.alpha"].item() / down.shape[0]102103 def hook(module, args, out, down=down, up=up, scale=scale):104 return out + (scale * (args[0].float() @ down.T) @ up.T).to(out.dtype)105106 modules[name].register_forward_hook(hook)107 n += 1108 return n109110111def _load():112 t0 = time.time()113 pipe = DiffusionPipeline.from_pretrained(114 MODEL_DIR, custom_pipeline="pipeline_moss_image", trust_remote_code=True,115 torch_dtype={"default": torch.bfloat16, "vae": torch.float32},116 )117 # The card rebuilds the scheduler from its own config before use.118 pipe.scheduler = type(pipe.scheduler).from_config(pipe.scheduler.config)119 pipe.to("cuda")120 adapted = 0121 if SPEC["lora"]:122 adapted = apply_lora(pipe.transformer, os.path.join(MOSS_LORA_DIR, SPEC["lora"]))123 _state.update(pipe=pipe, adapted=adapted,124 shift=getattr(pipe.scheduler.config, "shift", None)125 if not isinstance(pipe.scheduler.config, dict)126 else pipe.scheduler.config.get("shift"))127 print(f"moss-image loaded in {time.time()-t0:.1f}s | variant={MOSS_LORA or 'full'} "128 f"({SPEC['about']}) | defaults {SPEC['steps']} steps / CFG {SPEC['cfg']} / "129 f"skip {SPEC['skip']} | lora modules hooked: {adapted} | shift {_state['shift']}",130 flush=True)131132133class ImageRequest(BaseModel):134 prompt: str = Field(..., description="Text prompt, encoded by Qwen3.5-9B (token budget 4096).")135 n: int = Field(1, description="Images per prompt (num_images_per_prompt).")136 size: str = Field("1024x1024", description=f"WxH in pixels, both positive multiples of {VAE_TILE}; the pipeline rejects anything else. The fine-tune was done at 1024 px.")137 negative_prompt: str = Field("", description="Negative prompt. ONLY TAKES EFFECT when guidance_scale > 1 AND uncond_skip_layers is null/empty — by default the uncond branch is a skipped-block prediction of the POSITIVE prompt, not this text.")138 num_inference_steps: Optional[int] = Field(None, description=f"Flow-matching Euler steps. Default for this variant: {SPEC['steps']}.")139 guidance_scale: Optional[float] = Field(None, description=f"CFG scale. Default for this variant: {SPEC['cfg']}." + (" The turbo LoRAs are distilled for CFG 1; raising it is off-contract." if MOSS_LORA else ""))140 uncond_skip_layers: Optional[List[int]] = Field(None, description=f"Zero-based block indices whose skipped prediction replaces the CFG negative branch. Default for this variant: {SPEC['skip']}. Pass [] for a conventional negative branch driven by negative_prompt.")141 slg_layers: Optional[List[int]] = Field(None, description="Skip-Layer Guidance block indices. Adds a third forward per step and the correction slg_scale * (cond - cond_skip). Off by default.")142 slg_scale: float = Field(0.0, description="Skip-Layer Guidance strength. 0 disables the extra forward.")143 max_sequence_length: int = Field(4096, description="Text encoder token budget.")144 seed: Optional[int] = Field(None, description="Random seed. The initial noise is generated on CPU in float32, as the card specifies.")145 response_format: str = Field("b64_json", description="Only b64_json supported.")146147148def _params_doc():149 out = {}150 for name, info in ImageRequest.model_fields.items():151 d = info.default152 out[name] = {"default": None if d is ... else d, "description": info.description}153 out["num_inference_steps"]["resolved_default"] = SPEC["steps"]154 out["guidance_scale"]["resolved_default"] = SPEC["cfg"]155 out["uncond_skip_layers"]["resolved_default"] = SPEC["skip"]156 return out157158159@app.get("/health")160def health():161 return {"status": "ok" if _state else "degraded", "model": SERVED_MODEL_ID,162 "loaded": bool(_state), "variant": MOSS_LORA or "full",163 "lora_modules": _state.get("adapted")}164165166@app.get("/v1/models")167def models():168 return {"object": "list", "data": [{"id": SERVED_MODEL_ID, "object": "model"}]}169170171@app.get("/v1/config")172def config():173 return {"model": SERVED_MODEL_ID, "variant": MOSS_LORA or "full",174 "lora": SPEC["lora"], "params": _params_doc(),175 "scheduler": {"type": "flow-matching Euler", "shift": _state.get("shift")},176 "notes": [177 f"This variant is the {SPEC['about']}: {SPEC['steps']} steps at CFG "178 f"{SPEC['cfg']}. The three Kromoss variants do NOT share a sampler "179 "contract — send only a prompt to get the right one.",180 "uncond_skip_layers is NOT a negative-prompt control: by default the CFG "181 "uncond branch is a skipped-block prediction of the POSITIVE prompt, so "182 "negative_prompt is ignored unless you pass uncond_skip_layers: [].",183 "The LoRA is applied UNMERGED through forward hooks, as the card requires "184 "— its delta is close to bf16's rounding step, so merging would lose it."185 if SPEC["lora"] else186 "No LoRA: this is the full 50-step model. kromoss-dmd2 is the author's "187 "recommended 8-step variant and scores higher on PartiPrompts.",188 "Text encoder is Qwen3.5-9B as a pipeline component, not a served LLM, so "189 "this rig's vLLM gap on the qwen3_5 architecture does not apply.",190 "VAE is the FLUX.2 small decoder, run in float32 while the transformer and "191 "text encoder run in bfloat16, exactly as the card specifies.",192 "LICENSE: Apache-2.0, weights and bundled inference code, not gated.",193 ]}194195196@app.post("/v1/images/generations")197def generate_images(req: ImageRequest):198 if not _state:199 raise HTTPException(503, "model not loaded")200 if req.response_format != "b64_json":201 raise HTTPException(400, "only response_format=b64_json is supported")202 try:203 w, h = (int(x) for x in req.size.lower().split("x"))204 except ValueError:205 raise HTTPException(400, f"size must look like 1024x1024; got {req.size}")206 if w <= 0 or h <= 0 or w % VAE_TILE or h % VAE_TILE:207 raise HTTPException(400, f"size must be positive multiples of {VAE_TILE} in both "208 f"dimensions; got {req.size}")209210 steps = req.num_inference_steps if req.num_inference_steps is not None else SPEC["steps"]211 cfg = req.guidance_scale if req.guidance_scale is not None else SPEC["cfg"]212 skip = req.uncond_skip_layers if req.uncond_skip_layers is not None else SPEC["skip"]213 seed = req.seed if req.seed is not None else int(time.time() * 1000) % (2**31)214 t0 = time.time()215216 with _lock:217 queued = time.time() - t0218 # CPU generator in fp32: the card is explicit that the initial noise is fp32.219 generator = torch.Generator("cpu").manual_seed(seed)220 try:221 out = _state["pipe"](222 req.prompt, height=h, width=w, num_inference_steps=steps,223 guidance_scale=cfg, negative_prompt=req.negative_prompt,224 num_images_per_prompt=req.n, generator=generator,225 max_sequence_length=req.max_sequence_length,226 uncond_skip_layers=skip, slg_layers=req.slg_layers,227 slg_scale=req.slg_scale)228 except ValueError as exc:229 # The pipeline validates skip-layer indices, slg bounds and the size rule.230 raise HTTPException(400, str(exc))231 images = out.images232233 data = []234 for image in images:235 buf = io.BytesIO(); image.save(buf, format="PNG")236 data.append({"b64_json": base64.b64encode(buf.getvalue()).decode()})237238 elapsed = time.time() - t0239 print(f"Generated {len(data)} image(s) {req.size} in {elapsed:.1f}s "240 f"({MOSS_LORA or 'full'}, {steps} steps, CFG {cfg}, skip {skip})", flush=True)241 return JSONResponse({242 "created": int(time.time()),243 "data": data,244 "params_used": {245 "n": req.n, "variant": MOSS_LORA or "full", "lora": SPEC["lora"],246 "size": req.size, "num_inference_steps": steps, "guidance_scale": cfg,247 "uncond_skip_layers": skip, "slg_layers": req.slg_layers,248 "slg_scale": req.slg_scale, "shift": _state.get("shift"),249 "negative_prompt": req.negative_prompt,250 "negative_prompt_effective": bool(req.negative_prompt) and cfg > 1 and not skip,251 "max_sequence_length": req.max_sequence_length, "seed": seed,252 "queued_s": round(queued, 3), "elapsed_s": round(elapsed, 3),253 },254 })255256257if __name__ == "__main__":258 print(f"{SERVED_MODEL_ID} adapter on :{PORT}", flush=True)259 _load()260 uvicorn.run(app, host="0.0.0.0", port=PORT)