Spaces:
Sleeping
Sleeping
H3-Image version
Browse files- README.md +16 -13
- app.py +157 -0
- requirements.txt +4 -0
README.md
CHANGED
|
@@ -1,13 +1,16 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: H3 Image Encoder
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 6.32.0
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: H3 Image Encoder
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.32.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
python_version: "3.12"
|
| 10 |
+
short_description: Qwen3-VL conditioning backend for photo-person-swap-h3
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
+
models:
|
| 13 |
+
- MiniMaxAI/MiniMax-H3-Image
|
| 14 |
+
---
|
| 15 |
+
Backend for Ultronprime/photo-person-swap-h3. It turns a prompt and its reference images into MiniMax-H3-Image
|
| 16 |
+
conditioning tensors. Nothing is stored.
|
app.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MiniMax-H3-Image prompt encoder service for Ultronprime/photo-person-swap-h3.
|
| 2 |
+
|
| 3 |
+
Adapted from CozyByte/minimax-h3-image-encoder so user photos stay inside this account's own Spaces.
|
| 4 |
+
|
| 5 |
+
Turns a prompt (plus up to 8 reference images) into the two tensors the MiniMax-H3-Image
|
| 6 |
+
diffusion transformer reads: `prompt_embeds` of shape `(1, tokens, 5120)` — the 50th hidden
|
| 7 |
+
state of the 33B Qwen3-VL conditioner — and `text_token_tags`, the modality tag of every row.
|
| 8 |
+
The presentation is built exactly as the diffusers `MiniMaxH3ImageEditTextEncoderStep` builds
|
| 9 |
+
it: a `Picture i: ` label and a vision block per reference, then the prompt verbatim.
|
| 10 |
+
|
| 11 |
+
This runs on its own ZeroGPU slice so the studio Space can keep the 66 GB transformer resident
|
| 12 |
+
on its own. See https://huggingface.co/MiniMaxAI/MiniMax-H3-Image.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
# Before anything that could initialize CUDA.
|
| 16 |
+
import spaces
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import tempfile
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
import torch
|
| 24 |
+
from PIL import Image, ImageOps
|
| 25 |
+
from safetensors.torch import save_file
|
| 26 |
+
from transformers import AutoTokenizer, Qwen3VLForConditionalGeneration, Qwen3VLProcessor
|
| 27 |
+
|
| 28 |
+
REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3-Image")
|
| 29 |
+
MAX_IMAGES = 8
|
| 30 |
+
MULTIPLE = 32
|
| 31 |
+
VISION_SHORT_EDGE = 1024
|
| 32 |
+
MAX_SEQUENCE_LENGTH = 4096
|
| 33 |
+
TEXT_ENCODER_LAYER = 50
|
| 34 |
+
TEXT_TAG, IMAGE_TAG = 1, 0
|
| 35 |
+
|
| 36 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO, subfolder="tokenizer")
|
| 37 |
+
processor = Qwen3VLProcessor.from_pretrained(REPO, subfolder="processor")
|
| 38 |
+
text_encoder = (
|
| 39 |
+
Qwen3VLForConditionalGeneration.from_pretrained(
|
| 40 |
+
REPO, subfolder="text_encoder", dtype=torch.bfloat16
|
| 41 |
+
)
|
| 42 |
+
.to("cuda")
|
| 43 |
+
.eval()
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def image_paths(images):
|
| 48 |
+
"""Gradio hands back a list of paths, sometimes wrapped in one-element lists."""
|
| 49 |
+
return [item[0] if isinstance(item, (list, tuple)) else item for item in images or []]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def bound_short_edge(width: int, height: int, min_short_edge: int, max_short_edge: int, multiple: int):
|
| 53 |
+
short_edge = min(width, height)
|
| 54 |
+
if min_short_edge <= short_edge <= max_short_edge:
|
| 55 |
+
return width, height
|
| 56 |
+
scale = (min_short_edge if short_edge < min_short_edge else max_short_edge) / short_edge
|
| 57 |
+
return (
|
| 58 |
+
max(multiple, round(width * scale / multiple) * multiple),
|
| 59 |
+
max(multiple, round(height * scale / multiple) * multiple),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def presentation(prompt: str, paths: list[str]):
|
| 64 |
+
"""The token ids and per-row modality tags of an H3-Image presentation."""
|
| 65 |
+
images = []
|
| 66 |
+
for path in paths[:MAX_IMAGES]:
|
| 67 |
+
image = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
|
| 68 |
+
size = bound_short_edge(*image.size, VISION_SHORT_EDGE, VISION_SHORT_EDGE, MULTIPLE)
|
| 69 |
+
if image.size != size:
|
| 70 |
+
image = image.resize(size, Image.LANCZOS)
|
| 71 |
+
images.append(image)
|
| 72 |
+
|
| 73 |
+
token_ids: list[int] = []
|
| 74 |
+
token_tags: list[int] = []
|
| 75 |
+
vision = {"pixel_values": None, "image_grid_thw": None}
|
| 76 |
+
if images:
|
| 77 |
+
vision = processor.image_processor(images=images, return_tensors="pt")
|
| 78 |
+
merge_size = processor.image_processor.merge_size**2
|
| 79 |
+
for index, grid in enumerate(vision["image_grid_thw"]):
|
| 80 |
+
# The label carries no angle brackets; the prompt refers to it as `<Picture i>`.
|
| 81 |
+
label_ids = tokenizer(f"Picture {index + 1}: ", add_special_tokens=False)["input_ids"]
|
| 82 |
+
label_ids = label_ids[:MAX_SEQUENCE_LENGTH]
|
| 83 |
+
vision_ids = (
|
| 84 |
+
[tokenizer.convert_tokens_to_ids("<|vision_start|>")]
|
| 85 |
+
+ [tokenizer.convert_tokens_to_ids("<|image_pad|>")] * (int(grid.prod()) // merge_size)
|
| 86 |
+
+ [tokenizer.convert_tokens_to_ids("<|vision_end|>")]
|
| 87 |
+
)
|
| 88 |
+
token_ids += label_ids + vision_ids
|
| 89 |
+
token_tags += [TEXT_TAG] * len(label_ids) + [IMAGE_TAG] * len(vision_ids)
|
| 90 |
+
|
| 91 |
+
prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"][:MAX_SEQUENCE_LENGTH]
|
| 92 |
+
token_ids += prompt_ids
|
| 93 |
+
token_tags += [TEXT_TAG] * len(prompt_ids)
|
| 94 |
+
return token_ids, token_tags, vision
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def embed(token_ids: list[int], token_tags: list[int], vision: dict) -> tuple[torch.Tensor, torch.Tensor]:
|
| 98 |
+
"""One forward through the conditioner, keeping hidden state 50 and the row tags."""
|
| 99 |
+
input_ids = torch.tensor([token_ids], dtype=torch.long, device="cuda")
|
| 100 |
+
mm_token_type_ids = torch.tensor(
|
| 101 |
+
processor.create_mm_token_type_ids([token_ids]), dtype=torch.long, device="cuda"
|
| 102 |
+
)
|
| 103 |
+
kwargs = {}
|
| 104 |
+
if vision.get("pixel_values") is not None:
|
| 105 |
+
kwargs["pixel_values"] = vision["pixel_values"].to("cuda", text_encoder.dtype)
|
| 106 |
+
kwargs["image_grid_thw"] = vision["image_grid_thw"].to("cuda")
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
outputs = text_encoder.model(
|
| 109 |
+
input_ids=input_ids,
|
| 110 |
+
attention_mask=torch.ones_like(input_ids),
|
| 111 |
+
mm_token_type_ids=mm_token_type_ids,
|
| 112 |
+
use_cache=False,
|
| 113 |
+
output_hidden_states=True,
|
| 114 |
+
**kwargs,
|
| 115 |
+
)
|
| 116 |
+
embeds = outputs.hidden_states[TEXT_ENCODER_LAYER].to(torch.bfloat16).cpu().contiguous()
|
| 117 |
+
tags = torch.tensor(token_tags, dtype=torch.long).contiguous()
|
| 118 |
+
return embeds, tags
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _duration(prompt, images):
|
| 122 |
+
# One vision block per reference is ~1k extra rows for the 33B conditioner.
|
| 123 |
+
return min(120, 30 + 15 * len(image_paths(images)))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@spaces.GPU(duration=_duration, size="xlarge")
|
| 127 |
+
def encode(prompt: str, images: list[str] | None = None):
|
| 128 |
+
"""Encode a prompt and up to 8 reference images into `prompt_embeds` + `text_token_tags`.
|
| 129 |
+
|
| 130 |
+
Reference images are ordered: the prompt refers to them as `<Picture 1>`, `<Picture 2>`, ...
|
| 131 |
+
Returns a safetensors file holding both tensors.
|
| 132 |
+
"""
|
| 133 |
+
if not prompt or not prompt.strip():
|
| 134 |
+
raise gr.Error("Enter a prompt.")
|
| 135 |
+
paths = image_paths(images)
|
| 136 |
+
if len(paths) > MAX_IMAGES:
|
| 137 |
+
raise gr.Error(f"At most {MAX_IMAGES} reference images.")
|
| 138 |
+
start = time.time()
|
| 139 |
+
token_ids, token_tags, vision = presentation(prompt.strip(), paths)
|
| 140 |
+
embeds, tags = embed(token_ids, token_tags, vision)
|
| 141 |
+
path = tempfile.NamedTemporaryFile(suffix=".safetensors", delete=False).name
|
| 142 |
+
save_file({"prompt_embeds": embeds, "text_token_tags": tags}, path)
|
| 143 |
+
print(f"encoded {len(token_ids)} tokens ({len(paths)} refs) in {time.time() - start:.1f}s")
|
| 144 |
+
return path, f"{len(token_ids)} tokens · {len(paths)} reference image(s) · {time.time() - start:.1f}s"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
with gr.Blocks(title="H3-Image encoder") as demo:
|
| 148 |
+
gr.Markdown("**H3-Image prompt encoder**: backend for Ultronprime/photo-person-swap-h3. Nothing is stored.")
|
| 149 |
+
prompt = gr.Textbox(label="Prompt", lines=4)
|
| 150 |
+
files = gr.File(label="Reference images, in <Picture N> order", file_count="multiple", file_types=["image"],
|
| 151 |
+
type="filepath")
|
| 152 |
+
run = gr.Button("Encode")
|
| 153 |
+
wire = gr.File(label="prompt_embeds + text_token_tags")
|
| 154 |
+
info = gr.Markdown()
|
| 155 |
+
run.click(encode, [prompt, files], [wire, info], api_name="encode")
|
| 156 |
+
|
| 157 |
+
demo.queue(default_concurrency_limit=2).launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=5.22.1
|
| 2 |
+
accelerate
|
| 3 |
+
safetensors
|
| 4 |
+
torchvision
|