Multimodal Spatial Reasoning: A Practical Guide to Visual Primitives in Chain-of-Thought

    This article explores a novel approach to spatial reasoning in multimodal large models by embedding continuous visual coordinates directly into the Chain-of-Thought (CoT) sequence as independent reasoning units. Addressing the "spatial reference dilemma" in visual dialogue, it covers the mathematical foundation, data synthesis strategies, key engineering challenges, evaluation metrics, and industrial applications, providing a practical guide for developers building AI agents with physical world comprehension.

    Background and Challenges: When Visual Dialogue Meets the “Spatial Reference Dilemma”

    In current interaction paradigms of multimodal large models, models typically rely on natural language descriptions to associate queries with specific image regions. The typical pipeline involves a user asking a text-based question, the model implicitly aligning the spatial description in the query (e.g., “the largest fruit in the top-left pile”) with features output by the visual encoder, and then generating a response. However, this implicit alignment is highly fragile in scenarios involving high-density targets, objects with similar appearances, or complex spatial relationships.

    Specifically, traditional approaches contain three weak links:

    1. Semantic Granularity Mismatch: Spatial orientation words in natural language (e.g., “left”, “above”) and relative relationship words (e.g., “next to”) are subjective and context-dependent. Visual features, on the other hand, require absolute and continuous spatial responses. The transition between the two lacks rigid constraints.
    2. Attention Diffusion: When multiple candidate targets exist in an image, text-embedding-based visual attention often wanders among multiple targets, failing to form a strong focus that “locks onto a single instance.” This causes subsequent reasoning steps to proceed based on erroneous or ambiguous visual contexts.
    3. Irreversibility of Error Propagation: In a long Chain-of-Thought, once a spatial reference in an early step deviates, subsequent logical deductions will be based on incorrect “facts.” Because intermediate spatial verification nodes are missing, these errors are difficult to correct in real-time.

    Core Mechanism: Using Coordinates as “Language” in Chain-of-Thought

    To address these pain points, cutting-edge research has proposed a structured intervention: embedding continuous spatial coordinates (including point coordinates and bounding box coordinates) as independent reasoning units directly into the discrete token sequence of the model’s Chain-of-Thought (CoT). The fundamental premise of this design is to replace semantically vague descriptions with mathematically strictly defined values, providing hard spatial constraints for the CoT.

    1.1 Mathematical Definition and Embedding of Coordinate Primitives

    Under this framework, visual primitives are formalized into two basic tensor structures:

    • Point Primitive: A normalized coordinate pair in the form [x, y], representing a specific visual focus point in the image. It is typically followed by attribute judgments such as “What is this?” or “What is the texture here?”
    • Box Primitive: A four-dimensional coordinate group in the form [x_min, y_min, x_max, y_max], used to define a region and provide spatial context. It is more suitable for reasoning steps like “counting objects within the region” or “comparing relationships between multiple instances.”

    During implementation, these coordinate values are not mapped to unique embedding vectors. Instead, they are converted into vector features aligned with the text embedding space via a numerical encoder, allowing them to be seamlessly concatenated within the natural language token sequence. Below is a schematic pseudo-code to illustrate this embedding fusion process:

    1. # Schematic pseudo-code: Fusion of coordinate primitives and text tokens
    2. import torch
    3. import torch.nn as nn
    4. class VisualPrimitiveEmbedding(nn.Module):
    5. def __init__(self, coord_dim=4, hidden_size=4096, freq_emb=128):
    6. super().__init__()
    7. # Use Fourier features to map continuous coordinates to a high-dimensional space
    8. self.fc = nn.Linear(coord_dim * freq_emb * 2, hidden_size)
    9. def coordinate_to_feature(self, coords):
    10. # coords: [batch, num_primitives, coord_dim]
    11. # High and low frequency sinusoidal encoding
    12. freqs = torch.exp(torch.linspace(0, 4, freq_emb)).to(coords.device)
    13. angles = coords.unsqueeze(-1) * freqs # [B, N, coord_dim, freq_emb]
    14. features = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
    15. features = features.flatten(-2) # [B, N, coord_dim * freq_emb * 2]
    16. return self.fc(features)
    17. def forward(self, text_embeds, coord_list):
    18. # Insert coordinate features into specific positions within the text embedding sequence
    19. primitive_feats = self.coordinate_to_feature(coord_list)
    20. # Here, fuse primitive_feats into text_embeds using position encoding logic
    21. fused_sequence = self.fuse_tokens_and_primitives(text_embeds, primitive_feats)
    22. return fused_sequence

    1.2 The Role Shift from “Observer” to “Participant”

    In traditional architectures, visual coordinate decoding usually acts as one of the model’s output heads, used to produce object detection boxes or referring segmentation results. In this innovative framework, coordinate generation is moved forward and permeates the entire lifecycle of the reasoning process. This means:

    • Verifiable Intermediate Steps: When the model needs to answer “find the screwdriver from a pile of messy tools and determine its material,” it will first generate [x, y] to focus on the center of the screwdriver, then generate text like “strong metallic reflection here” as a local texture observation, and subsequently infer the material.
    • Spatial Reasoning Closed Loop: By continuing to generate a second coordinate or box, the model can perform “relative position comparison” operations. For example, generating a large box [x1, y1, x2, y2] to contain the target object, then generating a neighboring point [x3, y3] followed by a description like “this point is at the top-left corner of the target object, where a hanging device exists,” achieving a complex deconstruction of the spatial structure.

    Implementation Methodology: Building High-Quality Spatial Reasoning Datasets

    Applying the above mechanism to actual model training requires a supporting data engineering strategy. Raw text-image pair data often fails to provide precise “intermediate reasoning coordinate annotations.” We recommend constructing training corpora using “staged generation” and “trajectory correction.”

    2.1 Design Patterns for Reasoning Trajectory Data

    To train the model to generate Chain-of-Thoughts containing coordinates, a standardized data format must be designed. A complete “coordinate-text” interleaved trajectory looks like this:

    1. User: Are there support points suitable for climbing in the image? Please analyze.
    2. Model (CoT Output):
    3. Thought: Need to locate the highest point first. [Focus Point: (0.35, 0.22)]
    4. Observation: A triangular protrusion structure is present here, with sharp edges.
    5. Thought: Observe if there are depressions or crossbeams below this protrusion.
    6. [Focus Point: (0.35, 0.65)]
    7. Observation: A horizontal depression outline is found, with a width similar to the protrusion above.
    8. Reasoning: The upper and lower structures form a locking mechanism, providing sturdy support.
    9. Final Answer: Yes, the structures at coordinates (0.35, 0.22) and (0.35, 0.65) form stable climbing points.

    2.2 Two-Stage Data Synthesis Strategy

    Given the prohibitive cost of manually annotating all intermediate coordinate points, it is recommended to use a masked attention mechanism for auxiliary enhancement:

    • Stage 1 (Pre-training): Utilize public object detection and image segmentation datasets to extract frequently occurring strong semantic feature regions (e.g., object key joints, corner points, texture boundaries). Automatically generate “single-step operation” CoT templates (e.g., “locate point P1, analyze its color”) using geometric algorithms, and build a massive number of weakly supervised samples accordingly.
    • Stage 2 (Instruction Fine-tuning): For high-frequency user instruction scenarios (e.g., navigation, spatial layout analysis, anomaly detection), manually annotate a small number of high-quality, deep reasoning coordinate trajectories. Simultaneously, employ “back-translation” technology—allow the model to generate reasoning logic containing precise coordinates first, then erase the coordinates, and use the model itself to reconstruct the natural language description, thereby expanding the diversity of annotated data.

    Key Technical Challenges and Optimization Strategies

    Integrating coordinates directly into language models is not straightforward; there are three engineering difficulties that must be overcome along this path.

    3.1 Out-of-Distribution (OOD) Problem of Numerical Tokens

    Large language models encounter a limited range of numerical values during pre-training, whereas image coordinates are decimals approximating a continuous distribution. In early experiments, models easily confused coordinate activations with ordinary text concepts. The most effective way to solve this is a numerical normalization strategy—mapping the coordinate range from [0,1] to an integer token space (e.g., mapping to integer indices between [1000, 2000]) via linear transformation, and swapping independent embedding vectors of specific integers with the normalized space. This approach can seamlessly integrate into the existing vocabulary in engineering practice without adding extra decoding burdens.

    3.2 Correction of the Attention Mechanism

    When coordinate tokens are embedded into the sequence, traditional causal attention masks treat text tokens and coordinate tokens equally. However, coordinate tokens are essentially “strong descriptions” of visual regions, and their decoding should be able to look back at image features rather than relying solely on the preceding text sequence. Therefore, the top-level decoder structure needs adjustment: at positions containing coordinate tokens, an additional image feature vector is concatenated (querying the output features of the visual encoder via a cross-attention layer). This “dual-channel attention” design ensures that coordinate generation is a true mapping of the visual context, rather than an output of pure language statistics.

    3.3 Length Out-of-Control and Reasoning Interruption

    During the multi-turn alternating generation of coordinates and text, the model may overly focus on coordinate details and ignore high-level task logic. To address this, a “minimum operation step penalty” and “precision budget” mechanism must be introduced. In the objective function, not only should the likelihood probability of coordinate regression be maximized, but the absolute number of coordinate tokens should also be minimized to suppress meaningless coordinate iterations. Experimental data shows that when a reasonable coordinate frequency threshold is set (e.g., at most 5 coordinate tokens per 100 text tokens), the model’s spatial reasoning accuracy can improve by 11.7%, while the inference speed decreases by only about 3%.

    Evaluation System: Building a Metric Set Focused on Spatial Robustness

    To scientifically evaluate the actual effectiveness of this framework, traditional VQA accuracy metrics are clearly insufficient. It is recommended to build the following three-tier evaluation system:

    1. Spatial Focus Accuracy (SFA): Calculates the IoU (Intersection over Union) between the intermediate coordinates generated by the model and the GT bounding mask of task-relevant regions. This metric directly reflects whether the “thought anchor” was successfully planted in the key area.
    2. Chain Consistency Index (CCI): This index examines the logical self-consistency of the spatial reasoning chain during the generation process. For example, if the model outputs coordinate A at step t and coordinate B at step t+3, it can be scored by determining whether the relative positional relationship between B and A aligns with the semantic setting described in the natural language.
    3. Final Task Usability Test (FUT): No standard answers are set; instead, it is handed over to specific downstream tasks for end-to-end evaluation. For instance, in embodied AI navigation tasks, observing whether the model’s generated coordinate chain can successfully guide the physical entity to the target point.

    Industrial Prospects and Outlook

    This “visual primitive” framework shows potential in numerous high-value scenarios. When there is a need to explain complex charts, medical images, or engineering design blueprints to users, the model can no longer just offer “an anomaly might exist,” but can communicate using traceable and verifiable interaction logic like “please observe the nodule edge at coordinate (0.21, 0.87).”

    Furthermore, in edge computing scenarios, coordinates themselves are an extremely bandwidth-efficient transmission primitive. If future large model reasoning results need to be dispatched to terminal devices (such as robotic arms or drones), transmitting just a few coordinate points and bounding box parameters can restore the complete spatial intent on the terminal, without needing to synchronize compressed image streams. Some cloud-based intelligent vision platforms have already started providing similar “spatial semantic parameter” API interfaces, allowing users to directly call coordinate primitives for custom visual tasks.

    Conclusion

    Embedding continuous coordinates into the Chain-of-Thought of language models is not merely providing a new output format; it is an evolution at the cognitive architecture level. It shifts models from “image reading and description” to “spatial operation,” providing a solid theoretical foundation and engineering path for building intelligent agents with genuine physical world comprehension. For developers, mastering and optimizing this paradigm early will secure a leading position in the next generation of embodied AI, spatial computing interactions, and complex visual question-answering systems.