Spaces:
Running on Zero
Running on Zero
File size: 16,320 Bytes
cd5905f d640927 cd5905f d640927 cd5905f d640927 cd5905f d640927 cd5905f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import base64 # noqa: E402
import gc # noqa: E402
import html # noqa: E402
import io # noqa: E402
import queue # noqa: E402
import random # noqa: E402
import re # noqa: E402
import threading # noqa: E402
import time # noqa: E402
import gradio as gr # noqa: E402
import numpy as np # noqa: E402
import torch # noqa: E402
from accelerate import init_empty_weights # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
from PIL import Image # noqa: E402
from safetensors.torch import load_file as load_safetensors # noqa: E402
from transformers import Qwen2Tokenizer # noqa: E402
from models.bagel import Bagel, BagelConfig # noqa: E402
from models.bagel.autoencoder import load_ae # noqa: E402
from models.bagel.data_utils import add_special_tokens # noqa: E402
from models.bagel.inferencer import InterleaveInferencer # noqa: E402
from models.bagel.qwen2_navit import Qwen2Config # noqa: E402
from models.bagel.siglip_navit import SiglipVisionConfig # noqa: E402
from models.bagel.transforms import ImageTransform # noqa: E402
MODEL_ID = "ThinkMorph/ThinkMorph-SSL-Instruct"
# System prompt the model was trained with (configs/train/stage2_instruct.yaml / model card).
SYSTEM_PROMPT = """Use <think>...</think> for intermediate reasoning or planning.
To generate an image, write <gen_image> followed by an image-size declaration:
<gen_image>[Image size: (height, width)]
Generated images become part of your context and can inform subsequent reasoning. You may generate more than one image if needed.
If the task requires a final textual answer, wrap it in <answer>...</answer>.
If no textual answer is needed, the response may end after reasoning or image generation.
Example:
<think>reasoning step</think>
<gen_image>[Image size: (512, 512)]
<think>observe and reason about the generated image</think>
<answer>final answer</answer>"""
# ---------------------------------------------------------------------------
# Model loading -- mirrors eval/VLMEvalKit/vlmeval/vlm/ThinkMorphInterleaved.py
# ---------------------------------------------------------------------------
model_path = snapshot_download(MODEL_ID)
llm_cfg = Qwen2Config.from_json_file(os.path.join(model_path, "llm_config.json"))
llm_cfg.qk_norm = True
llm_cfg.tie_word_embeddings = False
llm_cfg.layer_module = "Qwen2MoTDecoderLayer"
vit_cfg = SiglipVisionConfig.from_json_file(os.path.join(model_path, "vit_config.json"))
vit_cfg.rope = False
vit_cfg.num_hidden_layers -= 1
vae_model, vae_cfg = load_ae(local_path=os.path.join(model_path, "ae.safetensors"))
config = BagelConfig(
visual_gen=True,
visual_und=True,
llm_config=llm_cfg.to_dict(),
vit_config=vit_cfg.to_dict(),
vae_config=vae_cfg,
vit_max_num_patch_per_side=70,
connector_act="gelu_pytorch_tanh",
latent_patch_size=2,
max_latent_size=64,
)
with init_empty_weights():
model = Bagel(config)
sd = load_safetensors(os.path.join(model_path, "ema.safetensors"), device="cpu")
missing, unexpected = model.load_state_dict(sd, assign=True, strict=False)
print(f"[load] missing={len(missing)} unexpected={len(unexpected)}")
if missing:
print("[load] first missing:", missing[:10])
del sd
gc.collect()
model = model.to("cuda").eval()
vae_model = vae_model.to("cuda").to(torch.bfloat16).eval()
tokenizer = Qwen2Tokenizer.from_pretrained(model_path)
tokenizer, new_token_ids, _ = add_special_tokens(tokenizer)
ACTION_TOKEN = "<gen_image>"
new_token_ids["image_action_token_id"] = tokenizer.convert_tokens_to_ids(ACTION_TOKEN)
new_token_ids["register_action_token"] = True
inferencer = InterleaveInferencer(
model=model,
vae_model=vae_model,
tokenizer=tokenizer,
vae_transform=ImageTransform(1024, 512, 16),
vit_transform=ImageTransform(980, 224, 14),
new_token_ids=new_token_ids,
)
_ORIG_DECODE = inferencer._decode_text_until_stop_with_generate_text
_ORIG_GEN_IMAGE = inferencer.gen_image
# ---------------------------------------------------------------------------
# Rendering helpers
# ---------------------------------------------------------------------------
def _img_to_data_uri(img: Image.Image) -> str:
buf = io.BytesIO()
img.convert("RGB").save(buf, format="JPEG", quality=90)
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
def _format_text(text: str) -> str:
t = html.escape(text)
t = re.sub(r"<answer>(.*?)(</answer>|$)",
r'<div class="tm-answer"><b>Answer:</b> \1</div>', t, flags=re.S)
t = re.sub(r"</?think>", "", t)
t = re.sub(r"<gen_image>", "", t)
t = t.strip()
if not t:
return ""
return f'<div class="tm-text">{t}</div>'
def _render(items, status: str) -> str:
parts = [f'<div class="tm-status">{html.escape(status)}</div>']
n_img = 0
for kind, val in items:
if kind == "input":
parts.append(
f'<div class="tm-img"><img src="{_img_to_data_uri(val)}"/>'
f"<span>Input image</span></div>"
)
elif kind == "text":
parts.append(_format_text(val))
else:
n_img += 1
parts.append(
f'<div class="tm-img tm-gen"><img src="{_img_to_data_uri(val)}"/>'
f"<span>Generated image #{n_img} ({val.size[1]}x{val.size[0]})</span></div>"
)
return '<div class="tm-trace">' + "\n".join(parts) + "</div>"
def _extract_answer(texts) -> str:
full = "\n".join(texts)
m = re.findall(r"<answer>(.*?)(?:</answer>|$)", full, flags=re.S)
if m:
return m[-1].strip()
return ""
def _duration(image, question, max_images=2, max_text_tokens=1024, num_timesteps=50, *args, **kwargs):
# Measured on ZeroGPU: ~0.95 s per denoising step for a ~1024px image (CFG), ~10 s of text decoding.
est = 15 + int(max_images) * 0.95 * int(num_timesteps) + int(max_text_tokens) * 0.01
return int(min(300, est * 1.15))
@spaces.GPU(duration=_duration)
def reason(
image: Image.Image | None,
question: str,
max_images: int = 2,
max_text_tokens: int = 1024,
num_timesteps: int = 50,
cfg_text_scale: float = 3.0,
cfg_img_scale: float = 1.5,
timestep_shift: float = 3.0,
seed: int = 42,
):
"""Answer a (visual) question with ThinkMorph-SSL's interleaved text + image reasoning.
The model thinks in text, generates intermediate images when they help (zoom-ins, depth maps,
bird's-eye views, novel views, ...), feeds them back into its context and finally answers.
Args:
image: optional input image the question is about.
question: the question / instruction.
max_images: maximum number of intermediate images the model may generate.
max_text_tokens: total budget of text tokens across the reasoning trace.
num_timesteps: denoising steps per generated image.
cfg_text_scale: text classifier-free guidance scale for image generation.
cfg_img_scale: image classifier-free guidance scale for image generation.
timestep_shift: flow-matching timestep shift for image generation.
seed: random seed.
Returns:
(trace_html, generated_images, final_answer)
"""
question = (question or "").strip()
if not question:
raise gr.Error("Please enter a question.")
random.seed(int(seed))
np.random.seed(int(seed))
torch.manual_seed(int(seed))
torch.cuda.manual_seed_all(int(seed))
input_list = []
items = []
if image is not None:
image = image.convert("RGB")
input_list.append(image)
items.append(("input", image))
input_list.append("<img><|image_1|></img> " + question)
else:
input_list.append(question)
q: "queue.Queue" = queue.Queue()
DONE = object()
def decode_hook(*a, **k):
out = _ORIG_DECODE(*a, **k)
if out[0]:
q.put(("text", out[0]))
return out
def gen_image_hook(image_shape, *a, **k):
q.put(("status", f"Generating image {image_shape[0]}x{image_shape[1]} ..."))
out = _ORIG_GEN_IMAGE(image_shape, *a, **k)
img = out.get("image") if isinstance(out, dict) else out
if isinstance(img, Image.Image):
q.put(("image", img.copy()))
return out
inferencer._decode_text_until_stop_with_generate_text = decode_hook
inferencer.gen_image = gen_image_hook
result = {}
def worker():
try:
with torch.no_grad():
result["out"] = inferencer.interleave_inference(
input_list,
think=True,
understanding_output=False,
use_action_token_control=True,
use_action_control_system_prompt=True,
action_control_system_prompt=SYSTEM_PROMPT,
image_action_token=ACTION_TOKEN,
enable_size_tokens=True,
enable_ref_image=False,
do_sample=False,
text_temperature=0.3,
cfg_text_scale=float(cfg_text_scale),
cfg_img_scale=float(cfg_img_scale),
cfg_interval=[0.4, 1.0],
cfg_renorm_type="global",
cfg_renorm_min=1.0,
timestep_shift=float(timestep_shift),
num_timesteps=int(num_timesteps),
max_turn_text_tokens=int(max_text_tokens),
max_think_token_n=int(max_text_tokens),
max_auto_images=int(max_images),
image_shapes=(512, 512),
feedback_generated_image_to_context=True,
feedback_generated_image_as_vae_condition=True,
feedback_generated_image_as_vit_condition=True,
inline_image_latents=True,
)
except Exception as e: # surface errors to the UI
result["err"] = e
finally:
q.put((DONE, None))
t0 = time.perf_counter()
th = threading.Thread(target=worker, daemon=True)
th.start()
texts, gen_images = [], []
status = "Thinking ..."
try:
while True:
kind, val = q.get()
if kind is DONE:
break
if kind == "status":
status = val
elif kind == "text":
texts.append(val)
items.append(("text", val))
status = "Thinking ..."
elif kind == "image":
gen_images.append(val)
items.append(("image", val))
status = "Thinking ..."
yield _render(items, status), gen_images, _extract_answer(texts)
finally:
th.join()
inferencer._decode_text_until_stop_with_generate_text = _ORIG_DECODE
inferencer.gen_image = _ORIG_GEN_IMAGE
if "err" in result:
raise gr.Error(f"Inference failed: {result['err']!r}")
diag = getattr(inferencer, "last_interleave_diagnostics", {}) or {}
stop = diag.get("stop_reason", "completed")
elapsed = time.perf_counter() - t0
note = f"Done in {elapsed:.1f}s 路 {len(gen_images)} generated image(s) 路 stop: {stop}"
if stop == "image_limit":
note += " (raise 'Max generated images' to let the model continue)"
elif stop == "max_text_tokens":
note += " (raise 'Max text tokens' to let the model continue)"
print(f"[reason] {note}")
yield _render(items, note), gen_images, _extract_answer(texts)
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
.tm-trace { display: flex; flex-direction: column; gap: 10px; }
.tm-status { font-size: 0.85em; opacity: 0.75; }
.tm-text { white-space: pre-wrap; line-height: 1.5; padding: 8px 12px; border-radius: 8px;
background: var(--block-background-fill); border: 1px solid var(--border-color-primary); }
.tm-answer { margin-top: 6px; padding: 6px 10px; border-radius: 6px;
background: rgba(34,197,94,0.15); border-left: 4px solid #22c55e; }
.tm-img { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
.tm-img img { max-width: 420px; max-height: 420px; border-radius: 8px; }
.tm-gen img { outline: 3px solid #ec4899; }
.tm-img span { font-size: 0.8em; opacity: 0.7; }
"""
EXAMPLES = [
["examples/living_room_blue_couch.jpg",
"Imagine you are standing behind the fireplace looking toward the sofa. Is the TV on your left or your right? Answer with a word, not a letter."],
["examples/cafe_interior.jpg",
"Which is closer to the camera: the teapot on the nearest table or the turquoise cabinet? Think about the depth of the scene."],
["examples/sign_beach.jpg",
"Zoom in on the sign. What exactly does it say, and what object is lying next to it?"],
["examples/rubber_ducks.jpg",
"Sketch a bird's-eye view of this arrangement. In what order do the ducks appear from smallest to largest, left to right?"],
]
with gr.Blocks(title="ThinkMorph-SSL") as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# ThinkMorph-SSL: interleaved text + image reasoning\n"
"Ask a question about an image. **ThinkMorph-SSL-Instruct** (a BAGEL-7B-MoT fine-tune) thinks in text, "
"*generates its own intermediate images* when they help (zoom-ins, depth maps, bird's-eye views, other "
"viewpoints), looks at them, and then answers.\n\n"
"[Paper](https://huggingface.co/papers/2611.32183) 路 "
"[Code](https://github.com/ThinkMorph/ThinkMorph-SSL) 路 "
"[Project page](https://thinkmorph.github.io/ssl/) 路 "
"[Model](https://huggingface.co/ThinkMorph/ThinkMorph-SSL-Instruct)"
)
with gr.Row():
with gr.Column(scale=1):
image_in = gr.Image(label="Image (optional)", type="pil", height=320)
question_in = gr.Textbox(
label="Question",
lines=3,
placeholder="e.g. If you walked to the window and turned around, what would you see?",
)
run_btn = gr.Button("Reason", variant="primary")
with gr.Accordion("Advanced settings", open=False):
max_images = gr.Slider(1, 5, value=2, step=1, label="Max generated images")
max_text_tokens = gr.Slider(256, 2048, value=1024, step=64, label="Max text tokens (whole trace)")
num_timesteps = gr.Slider(10, 50, value=50, step=1, label="Denoising steps per image")
cfg_text_scale = gr.Slider(1.0, 8.0, value=3.0, step=0.1, label="CFG text scale")
cfg_img_scale = gr.Slider(1.0, 4.0, value=1.5, step=0.1, label="CFG image scale")
timestep_shift = gr.Slider(1.0, 6.0, value=3.0, step=0.1, label="Timestep shift")
seed = gr.Number(value=42, precision=0, label="Seed")
with gr.Column(scale=2):
answer_out = gr.Textbox(label="Final answer", lines=2)
trace_out = gr.HTML(label="Reasoning trace", value='<div class="tm-status">The interleaved reasoning trace will appear here.</div>')
gallery_out = gr.Gallery(label="Generated images", columns=3, height="auto")
inputs = [image_in, question_in, max_images, max_text_tokens, num_timesteps,
cfg_text_scale, cfg_img_scale, timestep_shift, seed]
outputs = [trace_out, gallery_out, answer_out]
run_btn.click(reason, inputs=inputs, outputs=outputs, api_name="reason", concurrency_limit=1)
question_in.submit(reason, inputs=inputs, outputs=outputs, concurrency_limit=1)
gr.Examples(
examples=EXAMPLES,
inputs=[image_in, question_in],
outputs=outputs,
fn=reason,
cache_examples=True,
cache_mode="lazy",
)
if __name__ == "__main__":
demo.queue().launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
|