multimodalart HF Staff commited on
Commit
8704f25
·
verified ·
1 Parent(s): 2382dbb

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,60 @@
1
  ---
2
- title: Spatialblock Demo
3
- emoji: ⚡
4
  colorFrom: purple
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.26.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: SpatialBlock
3
+ emoji: 🧱
4
  colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.26.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
+ short_description: Spatial intelligence in LVLMs via synthetic block-stacking
12
+ startup_duration_timeout: 1h
13
+ models:
14
+ - rsoohyun/SpatialBlock-7B-reason
15
+ datasets:
16
+ - rsoohyun/SpatialBlock-15k
17
+ license: apache-2.0
18
+ short_name: paper-2609.07064
19
  ---
20
 
21
+ # SpatialBlock — Spatial Intelligence in LVLMs
22
+
23
+ Demo for **SpatialBlock: Enhancing Spatial Intelligence in LVLMs via Synthetic
24
+ Block-Stacking Problem** ([arXiv 2609.07064](https://arxiv.org/abs/2609.07064)).
25
+
26
+ Large vision-language models describe what a scene contains well, yet still
27
+ struggle to reconstruct the 3D structure behind a 2D image and reason about it.
28
+ **SpatialBlock** trains LVLMs on [SpatialBlock-15k](https://huggingface.co/datasets/rsoohyun/SpatialBlock-15k),
29
+ a fully synthetic, scalable set of 15,000 block-stacking problems spanning
30
+ 3D-to-2D projection, viewpoint transformation, and structural combination.
31
+
32
+ ## Usage
33
+
34
+ Upload the images for a spatial multiple-choice question — one image per
35
+ `<image>` marker in the question text, in order — then ask. The demo runs
36
+ **SpatialBlock-7B-reason**, which thinks step by step and answers between
37
+ `<answer> </answer>` tags. The paper also trains a direct variant that answers
38
+ immediately ([SpatialBlock-7B-direct](https://huggingface.co/rsoohyun/SpatialBlock-7B-direct)).
39
+
40
+ ## Acknowledgements
41
+
42
+ - Model: [rsoohyun/SpatialBlock-7B-reason](https://huggingface.co/rsoohyun/SpatialBlock-7B-reason)
43
+ (Apache-2.0), fine-tuned from Qwen2.5-VL-7B-Instruct.
44
+ - Example images are drawn from the
45
+ [SpatialBlock-15k](https://huggingface.co/datasets/rsoohyun/SpatialBlock-15k)
46
+ dataset (Apache-2.0) and the repo's [demo assets](https://github.com/rsoohyun/SpatialBlock).
47
+
48
+ ## Citation
49
+
50
+ ```bibtex
51
+ @misc{ryu2026spatialblockenhancingspatialintelligence,
52
+ title={SpatialBlock: Enhancing Spatial Intelligence in LVLMs via Synthetic Block-Stacking Problem},
53
+ author={Soohyun Ryu and Sohee Kim and Eunho Yang},
54
+ year={2026},
55
+ eprint={2609.07064},
56
+ archivePrefix={arXiv},
57
+ primaryClass={cs.CV},
58
+ url={https://arxiv.org/abs/2609.07064},
59
+ }
60
+ ```
app.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
4
+
5
+ import spaces # noqa: E402 (must be imported before any torch/CUDA usage)
6
+ import time # noqa: E402
7
+ from pathlib import Path # noqa: E402
8
+
9
+ import gradio as gr # noqa: E402
10
+ import torch # noqa: E402
11
+ from jinja2 import Template # noqa: E402
12
+ from PIL import Image # noqa: E402
13
+ from transformers import ( # noqa: E402
14
+ AutoProcessor,
15
+ Qwen2_5_VLForConditionalGeneration,
16
+ )
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Model — mirrors the authors' reference implementation in
20
+ # SpatialBlock/src/demo.py (Apache-2.0). The reason model wraps the question
21
+ # in a chain-of-thought prompt and answers between <answer> </answer> tags.
22
+ # ---------------------------------------------------------------------------
23
+
24
+ MODEL_ID = "rsoohyun/SpatialBlock-7B-reason"
25
+ MAX_PIXELS = 128 * 28 * 28 # authors' default (demo.py)
26
+ MIN_PIXELS = 16 * 28 * 28
27
+ MAX_NEW_TOKENS = 1024 # authors' demo.sh default for the reason variant
28
+
29
+ IMAGE_TOKEN = "<image>"
30
+ HERE = Path(__file__).parent
31
+ COT_TEMPLATE_FILE = HERE / "rl_cot.jinja"
32
+
33
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
34
+ MODEL_ID,
35
+ dtype=torch.bfloat16,
36
+ attn_implementation="sdpa",
37
+ )
38
+ model.eval()
39
+ model = model.to("cuda")
40
+
41
+ processor = AutoProcessor.from_pretrained(
42
+ MODEL_ID,
43
+ use_fast=True,
44
+ max_pixels=MAX_PIXELS,
45
+ min_pixels=MIN_PIXELS,
46
+ )
47
+
48
+
49
+ def apply_cot_template(text: str) -> str:
50
+ """Exactly the authors' apply_cot_template() from src/demo.py."""
51
+ format_prompt = COT_TEMPLATE_FILE.read_text(encoding="utf-8")
52
+ format_prompt = Template(format_prompt.strip())
53
+ return format_prompt.render(content=text + "\n")
54
+
55
+
56
+ def build_messages(text: str, images: list) -> list:
57
+ """Exactly the authors' build_messages() from src/demo.py."""
58
+ chunks = text.split(IMAGE_TOKEN)
59
+ content = []
60
+ if len(chunks) == 1:
61
+ content += [{"type": "image", "image": image} for image in images]
62
+ content.append({"type": "text", "text": text})
63
+ else:
64
+ if len(chunks) - 1 != len(images):
65
+ raise ValueError(
66
+ f"{len(chunks) - 1} '{IMAGE_TOKEN}' markers but {len(images)} images"
67
+ )
68
+ for i, chunk in enumerate(chunks):
69
+ if chunk:
70
+ content.append({"type": "text", "text": chunk})
71
+ if i < len(images):
72
+ content.append({"type": "image", "image": images[i]})
73
+ return [{"role": "user", "content": content}]
74
+
75
+
76
+ def _parse_answer_letter(text: str) -> str:
77
+ """Extract the option letter from '<answer>X</answer>' (or a bare letter)."""
78
+ if "<answer>" in text:
79
+ inner = text.split("<answer>")[-1].split("</answer>")[0]
80
+ return inner.strip()
81
+ stripped = text.strip()
82
+ return stripped[:1] if stripped else ""
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Inference
87
+ # ---------------------------------------------------------------------------
88
+
89
+
90
+ @spaces.GPU(duration=120)
91
+ def answer(images, question):
92
+ if not images:
93
+ raise gr.Error("Please upload at least one image (or pick an example).")
94
+ if not question or not question.strip():
95
+ raise gr.Error("Please enter a question.")
96
+
97
+ # gr.Gallery passes a list of (media, caption) tuples; keep the media.
98
+ if images and not isinstance(images[0], (str, Image.Image)):
99
+ images = [item[0] for item in images]
100
+
101
+ pil_images = [Image.open(p).convert("RGB") for p in images]
102
+
103
+ text = apply_cot_template(question.strip())
104
+ messages = build_messages(text, pil_images)
105
+
106
+ inputs = processor.apply_chat_template(
107
+ messages,
108
+ tokenize=True,
109
+ add_generation_prompt=True,
110
+ return_dict=True,
111
+ return_tensors="pt",
112
+ ).to(model.device, dtype=torch.bfloat16)
113
+
114
+ start = time.perf_counter()
115
+ with torch.inference_mode():
116
+ generated_ids = model.generate(
117
+ **inputs,
118
+ max_new_tokens=MAX_NEW_TOKENS,
119
+ do_sample=False,
120
+ )
121
+ elapsed = time.perf_counter() - start
122
+
123
+ trimmed = [
124
+ out_ids[len(in_ids):]
125
+ for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)
126
+ ]
127
+ output = processor.batch_decode(
128
+ trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
129
+ )[0]
130
+
131
+ letter = _parse_answer_letter(output)
132
+ timing = f"_{elapsed:.1f}s on GPU"
133
+ return letter, output.strip(), timing
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # UI
138
+ # ---------------------------------------------------------------------------
139
+
140
+ EXAMPLES_DIR = HERE / "examples"
141
+
142
+ FLIP_QUESTION = (
143
+ "Question : Here is an image of a 3D structure made of block.<image>\n"
144
+ "Based on the images, how does the 3D structure appear when flip vertically?\n"
145
+ "Options:\nA.<image>\nB.<image>\nC.<image>\nD.<image>"
146
+ )
147
+
148
+ Q1_QUESTION = (
149
+ "Question : Here are images of a 3D structure made of block <image>\n"
150
+ "and the direction of views.<image>\n"
151
+ "Based on the images, how does the 3D structure appear when viewed from the front?\n"
152
+ "Options:\nA.<image>\nB.<image>\nC.<image>\nD.<image>"
153
+ )
154
+
155
+ Q3_QUESTION = (
156
+ "Question : Here are images of two 3D structures made of block.\n"
157
+ "Structure 1 : <image>\n"
158
+ "Structure 2 : <image>\n"
159
+ "Based on the images, if we move Structure 2 so that its orange and purple "
160
+ "blocks overlap with the matching ones in Structure 1, which 3D structure "
161
+ "can be formed?\n"
162
+ "Options:\nA.<image>\nB.<image>\nC.<image>\nD.<image>"
163
+ )
164
+
165
+
166
+ def _ex(question: str, files: list):
167
+ return [[str(EXAMPLES_DIR / f) for f in files], question]
168
+
169
+
170
+ EXAMPLES = [
171
+ _ex(
172
+ FLIP_QUESTION,
173
+ ["image1.png", "image2.png", "image3.png", "image4.png", "image5.png"],
174
+ ),
175
+ _ex(
176
+ Q1_QUESTION,
177
+ ["q1_img1.jpg", "q1_img2.jpg", "q1_opt_a.jpg", "q1_opt_b.jpg",
178
+ "q1_opt_c.jpg", "q1_opt_d.jpg"],
179
+ ),
180
+ _ex(
181
+ Q3_QUESTION,
182
+ ["q3_struct1.jpg", "q3_struct2.jpg", "q3_opt_a.jpg", "q3_opt_b.jpg",
183
+ "q3_opt_c.jpg", "q3_opt_d.jpg"],
184
+ ),
185
+ ]
186
+
187
+ with gr.Blocks(theme=gr.themes.Citrus(), title="SpatialBlock") as demo:
188
+ gr.HTML(
189
+ """
190
+ <div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
191
+ <span style="font-size: 36px;">🧱</span>
192
+ <h1 style="margin: 0; font-size: 26px;">SpatialBlock — Spatial Intelligence in LVLMs</h1>
193
+ </div>
194
+ <p style="margin-top: 4px;">
195
+ <em>SpatialBlock: Enhancing Spatial Intelligence in LVLMs via Synthetic
196
+ Block-Stacking Problem</em> — vision-language models fine-tuned on
197
+ 15,000 synthetic block-stacking problems to reason about the 3D
198
+ structure behind 2D images.
199
+ <a href="https://huggingface.co/papers/2609.07064">Paper</a> ·
200
+ <a href="https://github.com/rsoohyun/SpatialBlock">GitHub</a> ·
201
+ <a href="https://huggingface.co/rsoohyun/SpatialBlock-7B-reason">Model</a> ·
202
+ <a href="https://huggingface.co/datasets/rsoohyun/SpatialBlock-15k">Dataset</a>
203
+ </p>
204
+ """
205
+ )
206
+ gr.Markdown(
207
+ "Upload the images for a spatial multiple-choice question — one image per "
208
+ "`<image>` marker in the question — and ask. The model "
209
+ "(`SpatialBlock-7B-reason`) thinks step by step, then gives its final "
210
+ "answer between `<answer> </answer>` tags. "
211
+ "**Try the examples below** to see it in action."
212
+ )
213
+
214
+ with gr.Row():
215
+ with gr.Column():
216
+ images_in = gr.Gallery(
217
+ label="Images (one per <image> marker, in order)",
218
+ file_types=["image"],
219
+ columns=3,
220
+ height=240,
221
+ type="filepath",
222
+ interactive=True,
223
+ )
224
+ question_in = gr.Textbox(
225
+ label="Question (use <image> where each uploaded image goes)",
226
+ placeholder=(
227
+ "Question : Here are images of a 3D structure made of block <image>\n"
228
+ "and the direction of views.<image>\n..."
229
+ ),
230
+ lines=9,
231
+ max_lines=14,
232
+ )
233
+ submit_btn = gr.Button("Answer", variant="primary")
234
+
235
+ with gr.Column():
236
+ answer_letter = gr.Textbox(
237
+ label="Answer",
238
+ interactive=False,
239
+ show_copy_button=True,
240
+ )
241
+ reasoning_out = gr.Textbox(
242
+ label="Step-by-step reasoning",
243
+ lines=14,
244
+ max_lines=24,
245
+ interactive=False,
246
+ show_copy_button=True,
247
+ )
248
+ timing_out = gr.Markdown()
249
+
250
+ submit_btn.click(
251
+ fn=answer,
252
+ inputs=[images_in, question_in],
253
+ outputs=[answer_letter, reasoning_out, timing_out],
254
+ )
255
+
256
+ gr.Examples(
257
+ examples=EXAMPLES,
258
+ inputs=[images_in, question_in],
259
+ fn=answer,
260
+ outputs=[answer_letter, reasoning_out, timing_out],
261
+ cache_examples=True,
262
+ cache_mode="lazy",
263
+ label="Examples from SpatialBlock-15k (and the repo's flip demo)",
264
+ )
265
+
266
+ gr.Markdown(
267
+ """
268
+ <details>
269
+ <summary><b>How this works</b></summary>
270
+
271
+ The question text contains `<image>` markers; each uploaded image is
272
+ substituted for one marker, in upload order. This is exactly the
273
+ interface of the authors' `src/demo.py` reference implementation.
274
+
275
+ - The question is wrapped in the authors' reasoning prompt, and the
276
+ model produces a numbered reasoning sequence ending with
277
+ `<answer>X</answer>`.
278
+ - The paper also trains a **direct** model that predicts the option
279
+ letter immediately
280
+ ([SpatialBlock-7B-direct](https://huggingface.co/rsoohyun/SpatialBlock-7B-direct));
281
+ this demo runs the reasoning variant.
282
+
283
+ The checkpoint is a Qwen2.5-VL-7B-Instruct fine-tune on
284
+ [SpatialBlock-15k](https://huggingface.co/datasets/rsoohyun/SpatialBlock-15k),
285
+ a fully synthetic set of block-stacking problems covering 3D-to-2D
286
+ projection, viewpoint transformation, and structural combination.
287
+ </details>
288
+
289
+ <details>
290
+ <summary><b>Citation</b></summary>
291
+
292
+ ```bibtex
293
+ @misc{ryu2026spatialblockenhancingspatialintelligence,
294
+ title={SpatialBlock: Enhancing Spatial Intelligence in LVLMs via Synthetic Block-Stacking Problem},
295
+ author={Soohyun Ryu and Sohee Kim and Eunho Yang},
296
+ year={2026},
297
+ eprint={2609.07064},
298
+ archivePrefix={arXiv},
299
+ primaryClass={cs.CV},
300
+ url={https://arxiv.org/abs/2609.07064},
301
+ }
302
+ ```
303
+ </details>
304
+ """
305
+ )
306
+
307
+ if __name__ == "__main__":
308
+ demo.launch()
examples/image1.png ADDED
examples/image2.png ADDED
examples/image3.png ADDED
examples/image4.png ADDED
examples/image5.png ADDED
examples/q1_img1.jpg ADDED
examples/q1_img2.jpg ADDED
examples/q1_opt_a.jpg ADDED
examples/q1_opt_b.jpg ADDED
examples/q1_opt_c.jpg ADDED
examples/q1_opt_d.jpg ADDED
examples/q3_opt_a.jpg ADDED
examples/q3_opt_b.jpg ADDED
examples/q3_opt_c.jpg ADDED
examples/q3_opt_d.jpg ADDED
examples/q3_struct1.jpg ADDED
examples/q3_struct2.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers==4.57.6
2
+ accelerate
3
+ pillow
4
+ numpy
5
+ jinja2
rl_cot.jinja ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {{ content | trim }}
2
+ Please think about this question step by step and provide your detailed reasoning in a numbered reasoning sequence (1., 2., 3., ...).
3
+ Then give your final answer between the <answer> </answer> tags.
4
+ Output must be EXACTLY in this format (including tags):
5
+ ...
6
+ <answer>X</answer>
7
+
8
+ Please provide only the single option letter (e.g., A, B, C, D, etc.) within the <answer> </answer> tags.