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 ... for intermediate reasoning or planning. To generate an image, write followed by an image-size declaration: [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 .... If no textual answer is needed, the response may end after reasoning or image generation. Example: reasoning step [Image size: (512, 512)] observe and reason about the generated image final 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 = "" 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'
Answer: \1
', 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'
{t}
' def _render(items, status: str) -> str: parts = [f'
{html.escape(status)}
'] n_img = 0 for kind, val in items: if kind == "input": parts.append( f'
' f"Input image
" ) elif kind == "text": parts.append(_format_text(val)) else: n_img += 1 parts.append( f'
' f"Generated image #{n_img} ({val.size[1]}x{val.size[0]})
" ) return '
' + "\n".join(parts) + "
" def _extract_answer(texts) -> str: full = "\n".join(texts) m = re.findall(r"(.*?)(?:|$)", 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("<|image_1|> " + 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='
The interleaved reasoning trace will appear here.
') 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)