Structure-Aware Reasoning: How Large Models Read and Verify 3D Structures

    Large language models can talk about molecular structures but struggle to reason about their 3D geometry. This article introduces structure-aware reasoning: an architecture that encodes 3D coordinates into geometric features, injects them into an LLM's hidden space through a cross-modal adapter, and lets the chain of thought invoke deterministic geometry primitives such as distances, dihedral angles, contact maps, and buriedness. You will find runnable PyTorch code for the structure encoder and the geometry primitives, a verification-and-back-translation scheme to curb "geometric hallucinations," a three-stage training plan, layered evaluation guidance, and a candid discussion of capabilities, limitations, and compliance boundaries for protein and antibody design.

    1. Where the Problem Starts: Language Models Can “Talk About” Structure but Can’t Compute It

    Over the past few years, large language models have begun to take part in early-stage research tasks such as drug discovery, antibody design, and protein engineering. A common workflow is to let the model help interpret targets, generate molecular or antibody hypotheses, and explain the likely impact of mutations. But once the task moves into protein structure, antibody design, or structure encoding, the weaknesses of language models become increasingly obvious: they are good at processing token sequences, whereas proteins, antibodies, and small molecules are fundamentally three-dimensional structures.

    A common workaround is to convert 3D coordinates into text and stitch them back into the prompt. The typical pipeline looks like this: the model requests structural information, a structure-prediction service returns coordinates, the caller serializes atom indices, atom types, and x/y/z values into text, and finally the model reasons over that text context.

    This chain looks feasible, but the information loss is significant:

    • Sampling loss: Atom coordinates can run to tens of thousands of lines. To keep the context length manageable, people often keep only backbone atoms, or even only residue-level information, discarding side chains, water molecules, ions, and ligand details.
    • Semantic loss: Once 3D geometry is turned into text, the model has no explicit geometric operators and must rely on fuzzy priors from language statistics to estimate distances, angles, and orientations.
    • Broken reasoning: Structure-prediction tools usually return only the final structure and a confidence score, with no inspectable reasoning process. The model can only accept the black-box result as fact.

    The core goal of structure-aware reasoning, therefore, is not to make the model “read coordinate text.” It is to let 3D geometric information enter the reasoning process as features, and to make key conclusions computable and reviewable wherever possible.

    2. The Core Idea: Making 3D Structure a “Native Input” to the Reasoning Chain

    Here is a developer-oriented definition of structure-aware reasoning: structure-aware reasoning means the model receives not only sequence text during inference but also geometric features encoded from 3D coordinates, and can call deterministic geometric primitives such as distance, dihedral angles, contact maps, and buriedness within its chain of thought, ultimately producing structure-related conclusions that can be translated back and verified.

    The overall architecture breaks into four layers:

    1. Structure encoder: encodes atom coordinates into per-atom, per-residue features.
    2. Cross-modal adapter: projects structure features into the language model’s hidden space.
    3. Structured chain of thought: calls geometric primitives (distance, dihedral angles, contact maps) during reasoning and feeds the results back into the reasoning state.
    4. Verification and back-translation: rewrites key conclusions into computable assertions that are checked by dedicated tools or deterministic functions.

    The numbered flow is:

    1. Input the protein sequence and optional structure coordinates.
    2. The sequence enters the language model, forming text tokens and hidden states.
    3. The structure coordinates enter the structure encoder, forming atom features and residue features.
    4. The cross-modal adapter projects the structure features into the language model’s hidden space.
    5. Geometric primitives are called within the reasoning chain, yielding distances, angles, contacts, and buriedness.
    6. Key conclusions are back-translated into verifiable assertions.
    7. Dedicated tools or deterministic computation are responsible for verification.

    Compared with the traditional “text + tool” pattern, the advantage of structure-aware reasoning is that structure features are not compressed into text, geometry query results can participate in the same round of reasoning, and multi-objective trade-offs can be completed within a single reasoning chain.

    3. Technical Breakdown 1: Encoding 3D Structure into Information the Model Can Use

    1. Why You Can’t Just Feed Coordinates to the Model as Text

    If you simply concatenate atom coordinates into the prompt, the model can indeed see the numbers, but it does not gain reliable geometric equivariance/invariance. Translate or rotate the same molecule as a whole, and every coordinate value changes, so the text changes too. The patterns the model learns cannot transfer reliably, and it may even mistake “the order of residue numbering” for a spatial relationship.

    A sound approach is to design the encoder around geometric priors. The physical relationships between atoms depend mainly on relative positions, so the encoder should strive to:

    • Be invariant to global translation and rotation, or learn directional information only in a local coordinate frame.
    • Use relative distances, direction vectors, dihedral angles, and other rotation-invariant or equivariant features.
    • Pool atom features to the residue level, aligning with the residue-level semantic granularity of the language model.

    A clarification is needed here: the example encoder below mainly uses distance radial basis functions and scalar message passing, so its output is invariant to global translation and rotation. The example does not output vector representations and does not claim strict equivariant vector updates. If you later introduce backbone vectors, normal vectors, or local coordinate frames, you should re-specify their equivariance/invariance properties.

    2. Input/Output Contract and Minimum Runtime Conditions

    The illustrative code below assumes single-sample input; in practice, you can extend it to batching.

    Input contract:

    • coords: [N, 3], atom Cartesian coordinates, with Å (angstroms) as the recommended unit.
    • atom_types: [N], atomic element number (e.g., 1 for hydrogen).
    • residue_ids: [N], the residue index each atom belongs to, ideally numbered consecutively from 0.
    • atom_names: [N], atom names, e.g., N, CA, C, O, CB, ND1, NE2.
    • atom_slot: [N], an integer ID after mapping atom_names to atom slots, rather than stacking raw residue indices directly.
    • res_names: [R], the three-letter code for each residue.
    • chain_ids: [R], the chain each residue belongs to.
    • edge_src, edge_dst: [E], endpoints of edges in the k-nearest-neighbor atom graph.
    • text_ids: [L], language-side tokens.
    • text_mask: [L], a boolean mask marking which positions are replaced by structure features.
    • text_mask.sum() should equal the residue count R.

    Output contract:

    • token_ids: [R], residue-level language tokens.
    • Structure encoding output: [R, d_struct], residue-level structure features.
    • Adapter output: [R, H], aligned with the language model’s hidden space.
    • Language model output: text hidden states or logits.

    Minimum runtime conditions:

    • Python 3.10 with PyTorch 2.1 or later is recommended.
    • coords, residue_ids, atom_types, edge_src, edge_dst must be on the same device.
    • coords should be in Å; the cutoff should initially be set to 5.0 Å; k-nearest-neighbor should initially be 16.
    • If using a Hugging Face language model, construct aa_vocab and atom_vocab first, and ensure text_mask.sum() == len(res_names).
    • Single-sample input can unsqueeze(0) at the end; batching requires padding, an attention mask, and residue counts.

    3. The Revised Core Code

    1. import torch
    2. import torch.nn as nn
    3. def build_knn_edges(coords, k=16):
    4. """Build a k-nearest-neighbor atom graph. Automatically reduces k when N is small."""
    5. n = coords.size(0)
    6. k = min(k, n - 1)
    7. if k <= 0:
    8. empty = torch.empty(0, dtype=torch.long, device=coords.device)
    9. return empty, empty
    10. d = torch.cdist(coords, coords)
    11. idx = d.topk(k + 1, largest=False).indices[:, 1:]
    12. src = idx.reshape(-1)
    13. dst = torch.arange(n, device=coords.device).repeat_interleave(k)
    14. return src, dst
    15. def scatter_mean(src, index, dim_size):
    16. """Group by residue and take the mean."""
    17. out = torch.zeros(dim_size, src.size(-1), device=src.device, dtype=src.dtype)
    18. out.index_add_(0, index, src)
    19. counts = torch.zeros(dim_size, device=src.device, dtype=src.dtype)
    20. counts.index_add_(0, index, torch.ones_like(index, dtype=src.dtype))
    21. return out / counts.clamp_min(1).unsqueeze(-1)
    22. def tokenize_structure(
    23. coords,
    24. atom_types,
    25. residue_ids,
    26. res_names,
    27. chain_ids,
    28. atom_names,
    29. aa_vocab,
    30. atom_vocab,
    31. ):
    32. """Convert a structure into model input."""
    33. coords = torch.as_tensor(coords, dtype=torch.float32)
    34. atom_types = torch.as_tensor(atom_types, dtype=torch.long)
    35. residue_ids = torch.as_tensor(residue_ids, dtype=torch.long)
    36. token_ids = torch.tensor(
    37. [aa_vocab.get(r, aa_vocab.get("UNK", 0)) for r in res_names],
    38. dtype=torch.long,
    39. )
    40. chain_map = {c: i for i, c in enumerate(sorted(set(chain_ids)))}
    41. chain_tensor = torch.tensor([chain_map[c] for c in chain_ids], dtype=torch.long)
    42. # Atom slots should come from a mappable vocabulary, e.g., CA/CB/N/O/UNK,
    43. # rather than concatenating raw residue_ids directly into the features.
    44. atom_slot = torch.tensor(
    45. [atom_vocab.get(a.upper(), atom_vocab["UNK"]) for a in atom_names],
    46. dtype=torch.long,
    47. )
    48. edge_src, edge_dst = build_knn_edges(coords)
    49. return {
    50. "token_ids": token_ids, # [R]
    51. "coords": coords, # [N, 3]
    52. "atom_types": atom_types, # [N] atomic number, 1 means hydrogen
    53. "atom_slot": atom_slot, # [N] atom slot ID
    54. "atom_names": list(atom_names), # [N]
    55. "residue_ids": residue_ids, # [N]
    56. "edge_src": edge_src, # [E]
    57. "edge_dst": edge_dst, # [E]
    58. "chain_ids": chain_tensor, # [R]
    59. }
    60. class InvariantLayer(nn.Module):
    61. """Scalar message-passing layer.
    62. Note: this layer updates only scalar hidden states and outputs no vector hidden states.
    63. Coordinates are used only to construct relative distances and radial basis features,
    64. so the output is invariant to global translation and rotation.
    65. """
    66. def __init__(self, d_model, n_rbf):
    67. super().__init__()
    68. self.msg = nn.Sequential(
    69. nn.Linear(2 * d_model + n_rbf, d_model),
    70. nn.SiLU(),
    71. nn.Linear(d_model, d_model),
    72. )
    73. self.gate = nn.Sequential(
    74. nn.Linear(n_rbf, d_model),
    75. nn.Sigmoid(),
    76. )
    77. self.update = nn.Sequential(
    78. nn.Linear(2 * d_model, d_model),
    79. nn.SiLU(),
    80. )
    81. self.norm = nn.LayerNorm(d_model)
    82. @staticmethod
    83. def gaussian_rbf(d, n_rbf, cutoff):
    84. centers = torch.linspace(0, cutoff, n_rbf, device=d.device)
    85. widths = (cutoff / n_rbf) ** 2
    86. return torch.exp(-((d.unsqueeze(-1) - centers) ** 2) / widths)
    87. def forward(self, h, coords, src, dst, n_rbf, cutoff):
    88. vec = coords[dst] - coords[src] # [E, 3]
    89. dist = vec.norm(dim=-1) # [E]
    90. rbf = self.gaussian_rbf(dist, n_rbf, cutoff)
    91. rbf = rbf * (dist < cutoff).float().unsqueeze(-1)
    92. msg = self.msg(torch.cat([h[src], h[dst], rbf], dim=-1))
    93. msg = msg * self.gate(rbf)
    94. agg = torch.zeros_like(h)
    95. agg.index_add_(0, dst, msg)
    96. return self.norm(h + self.update(torch.cat([h, agg], dim=-1)))
    97. class StructureTokenizer(nn.Module):
    98. """Structure encoder: atom features propagate layer by layer, then pool to the residue level."""
    99. def __init__(
    100. self,
    101. hidden_size,
    102. d_struct=512,
    103. n_layers=4,
    104. n_rbf=16,
    105. cutoff=5.0,
    106. num_atom_slots=64,
    107. ):
    108. super().__init__()
    109. self.n_rbf = n_rbf
    110. self.cutoff = cutoff
    111. self.atom_emb = nn.Embedding(num_atom_slots, d_struct)
    112. self.layers = nn.ModuleList(
    113. [InvariantLayer(d_struct, n_rbf) for _ in range(n_layers)]
    114. )
    115. # Project the language hidden layer to d_struct first, then concatenate with
    116. # the structure features, to avoid a residue_head dimension error when
    117. # d_struct and hidden_size differ.
    118. self.lang_proj = nn.Linear(hidden_size, d_struct)
    119. self.residue_head = nn.Linear(d_struct * 2, d_struct)
    120. def forward(self, batch, residue_hidden):
    121. h = self.atom_emb(batch["atom_slot"]) # [N, d_struct]
    122. coords = batch["coords"]
    123. src, dst = batch["edge_src"], batch["edge_dst"]
    124. for layer in self.layers:
    125. h = layer(h, coords, src, dst, self.n_rbf, self.cutoff)
    126. res_feat = scatter_mean(
    127. h,
    128. batch["residue_ids"],
    129. residue_hidden.size(0),
    130. )
    131. res_sem = self.lang_proj(residue_hidden)
    132. return self.residue_head(torch.cat([res_feat, res_sem], dim=-1))
    133. class StructureAwareLM(nn.Module):
    134. """Inject structure features into the language model's hidden space via a residual."""
    135. def __init__(self, llm, d_struct=512, num_atom_slots=64, **encoder_kwargs):
    136. super().__init__()
    137. self.llm = llm
    138. self.res_embed = llm.get_input_embeddings()
    139. self.encoder = StructureTokenizer(
    140. hidden_size=llm.hidden_size,
    141. d_struct=d_struct,
    142. num_atom_slots=num_atom_slots,
    143. **encoder_kwargs,
    144. )
    145. self.adapter = nn.Sequential(
    146. nn.LayerNorm(d_struct),
    147. nn.Linear(d_struct, llm.hidden_size),
    148. nn.GELU(),
    149. nn.Linear(llm.hidden_size, llm.hidden_size),
    150. )
    151. # Zero-initialize the output projection: at the start of training the
    152. # structure increment is 0, so the model is equivalent to a pure language
    153. # model, which makes convergence smooth.
    154. nn.init.zeros_(self.adapter[-1].weight)
    155. nn.init.zeros_(self.adapter[-1].bias)
    156. def forward(self, batch, text_ids, text_mask):
    157. text_ids = text_ids.to(self.res_embed.weight.device)
    158. text_mask = text_mask.to(torch.bool)
    159. text_hidden = self.res_embed(text_ids) # [L, H]
    160. residue_hidden = text_hidden[text_mask] # [R, H]
    161. n_res = batch["chain_ids"].size(0)
    162. assert residue_hidden.size(0) == n_res
    163. struct_out = self.encoder(batch, residue_hidden) # [R, d_struct]
    164. struct_delta = self.adapter(struct_out) # [R, H]
    165. inputs_embeds = text_hidden.clone()
    166. # Residual injection: if the adapter output is zero, this is identical to a pure language model.
    167. inputs_embeds[text_mask] += struct_delta
    168. return self.llm(inputs_embeds=inputs_embeds.unsqueeze(0))

    Several points are key to this design:

    • On the text side, each residue still occupies only one token, so the sequence length does not balloon because of the structure input.
    • Zero-initializing the adapter’s output layer makes the model start training from a state equivalent to a pure language model.
    • Distances use Gaussian radial basis expansion, which retains finer geometric resolution than textualizing coordinates directly.
    • The atom graph builds edges via k-nearest-neighbor, and a cutoff distance can control the message-passing range.
    • atom_slot uses a mappable vocabulary of atom names, avoiding feeding raw residue_ids directly as continuous features.

    4. Technical Breakdown 2: Letting the Chain of Thought “Operate on” Structure Rather Than “Read” It

    Once structural information enters the model, the next step is to let the reasoning process operate on geometry. A common approach is to require the model to output structured statements, such as:

    • Residue contact pairs.
    • A list of interface residues.
    • Mutation sites and the rationale.
    • Candidate salt bridges, hydrogen bonds, and disulfide bonds.
    • Binding-pocket or buried-region judgments.

    Going further, you can wrap common geometric computations as geometry primitives. They are called on demand during reasoning, and the results are fed back into the reasoning state as features.

    Example geometry primitives:

    1. def atom_indices(mode, batch):
    2. """Select CA or CB by atom name.
    3. - mode: "ca" or "cb"
    4. - If some residues lack CB (e.g., glycine), the example falls back to CA;
    5. production systems should record missing atoms explicitly and consider
    6. using side-chain centers, SASA, or a mask marker.
    7. """
    8. mode = mode.lower()
    9. target = {"ca": "CA", "cb": "CB"}.get(mode)
    10. if target is None:
    11. raise ValueError("mode must be 'ca' or 'cb'")
    12. res = batch["residue_ids"]
    13. names = batch["atom_names"]
    14. selected = []
    15. for rid in torch.unique(res).tolist():
    16. idx = torch.nonzero(res == rid, as_tuple=True)[0].tolist()
    17. matched = [i for i in idx if names[i].upper() == target]
    18. if not matched and target == "CB":
    19. # Example-only fallback; production systems should mark or exclude explicitly.
    20. matched = [i for i in idx if names[i].upper() == "CA"]
    21. if not matched:
    22. raise ValueError(f"Residue {rid} missing atom {target}")
    23. selected.append(matched[0])
    24. return torch.tensor(selected, device=res.device, dtype=torch.long)
    25. def heavy_atom_indices_for_residue(rid, batch):
    26. """Get the heavy-atom indices of residue i, excluding hydrogens."""
    27. mask = (batch["residue_ids"] == rid) & (batch["atom_types"] != 1)
    28. return torch.nonzero(mask, as_tuple=True)[0]
    29. def geometry_primitives(batch):
    30. """Output geometry primitives such as distance, dihedral angle, contact map, and buriedness."""
    31. coords = batch["coords"]
    32. res = batch["residue_ids"]
    33. def distance(i, j):
    34. """Minimum heavy-atom distance between residue i and residue j."""
    35. ai = heavy_atom_indices_for_residue(i, batch)
    36. aj = heavy_atom_indices_for_residue(j, batch)
    37. if ai.numel() == 0 or aj.numel() == 0:
    38. return torch.tensor(float("inf"), device=coords.device)
    39. d = torch.cdist(coords[ai], coords[aj])
    40. return d.min()
    41. def dihedral(p0, p1, p2, p3):
    42. """Dihedral angle, used to judge side-chain or backbone relative orientation."""
    43. b0 = p0 - p1
    44. b1 = p2 - p1
    45. b2 = p3 - p2
    46. b1 = b1 / b1.norm().clamp_min(1e-6)
    47. v = b0 - (b0 * b1).sum() * b1
    48. w = b2 - (b2 * b1).sum() * b1
    49. x = (v * w).sum()
    50. y = (torch.cross(b1, v, dim=-1) * w).sum()
    51. return torch.atan2(y, x)
    52. def contacts(cutoff=8.0):
    53. """Residue contact map, excluding self-contacts."""
    54. idx = atom_indices("ca", batch)
    55. d = torch.cdist(coords[idx], coords[idx])
    56. contact_map = (d < cutoff).float()
    57. contact_map.fill_diagonal_(0.0)
    58. return contact_map
    59. def buriedness(radius=10.0):
    60. """Simplified buriedness: count the number of neighboring residues."""
    61. idx = atom_indices("cb", batch)
    62. d = torch.cdist(coords[idx], coords[idx])
    63. return ((d > 0) & (d < radius)).sum(dim=-1).float()
    64. return {
    65. "distance": distance,
    66. "dihedral": dihedral,
    67. "contacts": contacts,
    68. "buriedness": buriedness,
    69. }

    The call site can look like this:

    1. # model = StructureAwareLM(llm, d_struct=512, num_atom_slots=len(atom_vocab))
    2. # batch = tokenize_structure(...)
    3. # batch = {k: v.to(device) if torch.is_tensor(v) else v for k, v in batch.items()}
    4. # text_ids, text_mask = prepare_text(sequence)
    5. # outputs = model(batch, text_ids, text_mask)
    6. # logits = outputs.logits
    7. # ops = geometry_primitives(batch)
    8. # contact_map = ops["contacts"](cutoff=8.0)
    9. # buried = ops["buriedness"](radius=10.0)

    This design has three layers of value:

    1. The numbers used in reasoning come from deterministic computation, not from what the model generates from memory.
    2. Geometry query results can enter the hidden space directly, without being compressed into text.
    3. Each geometric operation is traceable and reproducible, which makes auditing easier.

    5. Technical Breakdown 3: Constraining “Geometric Hallucinations” with Verification and Back-Translation

    Once structure enters the reasoning chain, a corresponding risk appears: the model may see the structure yet misinterpret it. For example, a model might claim that a residue forms a salt bridge with an antigen, when the actual heavy-atom distance far exceeds the range for bridge formation.

    To avoid “geometric hallucinations,” three mechanisms are recommended:

    1. Back-translatable assertions: each key conclusion maps to a machine-computable assertion.
    2. Tiered trust: when deterministic computation agrees with an assertion, use it with high confidence; when it disagrees, trigger a review.
    3. Dedicated-tool fallback: structure prediction, energy evaluation, and interface assessment tools independently validate the model’s conclusions.

    Examples of back-translatable assertions:

    • “The minimum heavy-atom distance of residue pair (i, j) is less than 4.0 Å.”
    • “The buriedness of the mutation site is above a threshold.”
    • “The candidate interface residue set is consistent with the contact map.”
    • “Candidate disulfide-bond residues satisfy the geometric distance constraints.”

    Example verification function:

    1. def verify_claims(design, claims, predictor, evaluator, tolerance=0.5):
    2. """Independently verify the key structural claims given by the model."""
    3. struct = predictor.predict(design)
    4. metrics = evaluator.evaluate(design, struct)
    5. checked = []
    6. for c in claims:
    7. if c["type"] == "pairwise_distance":
    8. observed = metrics["distance"][c["i"], c["j"]]
    9. ok = abs(observed - c["value"]) <= tolerance
    10. elif c["type"] == "buried":
    11. observed = metrics["buriedness"][c["i"]]
    12. ok = observed >= c["threshold"]
    13. else:
    14. checked.append({**c, "status": "UNSUPPORTED"})
    15. continue
    16. checked.append({
    17. **c,
    18. "observed": observed,
    19. "status": "PASS" if ok else "CONFLICT",
    20. })
    21. return checked

    Whether structure-aware reasoning can rival dedicated models depends not on whether it “sees” the structure, but on whether the output is verifiable knowledge. A design proposal that can be reviewed item by item can still locate the problem along the reasoning chain even if some hypotheses are overturned. In contrast, a fluent-sounding but unverifiable conclusion is still just “guessing at the structure based on impression.”

    6. Training Plan: First Align Geometry with Language, Then Learn Design Reasoning

    Structure-aware capability does not appear out of nowhere; it is typically acquired in three steps.

    1. Geometry–Language Alignment

    The goal is to teach the adapter to “translate” structure features. Available supervision signals include:

    • Experimental structure descriptions.
    • Residue contact relationships.
    • Binding-site annotations.
    • Interface residue lists.
    • Functional-site descriptions.

    The loss function can use:

    • Contrastive learning: pull correct structure descriptions closer and push wrong ones farther.
    • Binary cross-entropy: judge whether a residue belongs to a contact, interface, or binding site.
    • Regression loss: predict distances, dihedral angles, or buriedness.

    Negative-sample construction can include:

    • Random residue pairs as non-contact negatives.
    • Shuffling sequence–structure pairings.
    • Wrong descriptions of different conformations of the same protein.
    • Residue pairs that are near the interface but at insufficient distance.

    2. Pretraining-Style Self-Supervision

    Without relying on manual annotation, structure self-supervised tasks can be used:

    • Masked coordinate reconstruction: mask some atom coordinates and predict their positions.
    • Structure description generation: input a structure and output descriptions of functional sites, binding pockets, and so on.
    • Contact prediction: input partial structure and predict the adjacency of missing residues.
    • Dihedral-angle prediction: predict backbone or side-chain angles.

    3. Instruction Fine-Tuning

    Train on “task instruction + structure input → design reasoning” samples. Data can come from:

    • Public structure and sequence databases.
    • Functional annotations in the literature.
    • Internal experimental records.
    • Historical design projects.

    Each sample should ideally come with verifiable labels, such as an interface residue list, mutation sites, distance thresholds, contact maps, and buriedness thresholds.

    Recommended training configuration:

    • Freeze the language model backbone; train the structure encoder and adapter.
    • If GPU memory allows, train the encoder first, then jointly fine-tune the adapter.
    • Learning rate: 1e-4 to 5e-5 works for the encoder and adapter.
    • Batch size: adjust dynamically based on structure size; for large proteins, chunk by residue first.
    • Zero-initialize the output projection to avoid disrupting language-model behavior early in training.
    • If you later unfreeze the language model, prefer parameter-efficient fine-tuning methods such as LoRA and Adapter.

    7. Evaluation and Engineering Practice: Measuring Gains While Managing Risk

    1. Minimum Reproduction Checklist

    To make the example easier to run, confirm the following before you try to reproduce it:

    • PyTorch version: PyTorch 2.1+ is recommended.
    • Tokenizer alignment: each residue corresponds to one text token, and text_mask.sum() must equal the residue count.
    • Coordinate source: may come from PDB, mmCIF, experimental structures, or a structure-prediction service; use Å as the unit consistently.
    • Atom information: atom_names must be provided, ideally including at least N, CA, C, O, CB; if you need to analyze side chains, keep ND1, NE2, OD1, OE1, and so on.
    • Vocabulary information: you need aa_vocab and atom_vocab, with UNK reserved.
    • Minimum batch: first validate with a small protein of 20 to 100 residues; for large proteins, increase cutoff, the number of layers, and num_atom_slots.

    2. Evaluate in Layers

    Layer What to evaluate Reference metrics
    Structure awareness Residue contacts, interface residues, dihedral angles, backbone geometry Precision/recall, mean angular error
    Design reasoning Performance of candidate designs after independent structure prediction and energy evaluation Buried interface area, shape complementarity, predicted binding free energy, developability metrics
    Hallucination rate Conflict ratio between verifiable assertions and actual geometric computation Conflict rate
    System overhead Per-round inference latency, number of external tool calls Latency, call volume

    When evaluating whether it “rivals dedicated models,” a fair comparison is recommended:

    1. A pure language model in a “text + tool” combination.
    2. A pure geometry encoder model.
    3. A structure-aware reasoning model.

    Have all three use the same tasks and the same external verification tools, and compare in isolation the incremental gain from structure-aware reasoning.

    3. Common Questions: How to Do It, How to Choose, Common Mistakes

    How do you do structure-aware reasoning?

    First prepare sequence and structure data, then use an invariant encoder to extract residue-level geometric features, inject them into the language model through an adapter, and finally add geometry primitives such as distance, contacts, and dihedral angles to the reasoning chain.

    How do you decide whether to introduce a structure encoder?

    If the task involves residue contacts, interface identification, mutation impact, binding pockets, or antibody interface design, it is usually worth introducing one. If the task is only pure-text summarization, it may not be necessary.

    What are the common mistakes?

    • Concatenating coordinate text directly into the prompt, which causes a loss of invariance.
    • Keeping only Cα coordinates and losing side-chain and interface detail.
    • Treating model-generated geometric descriptions as fact without external verification.
    • Ignoring non-protein factors such as glycosylation, disulfide bonds, and inter-chain interactions.
    • Training samples that lack negatives, leading the model to be overconfident.

    How do you avoid geometric hallucinations?

    Turn key conclusions into computable assertions and verify them with distance matrices, contact maps, buriedness, and dedicated structure-prediction and energy-evaluation tools. Conflicting assertions should be marked as low-confidence or should trigger re-reasoning.

    4. Engineering Recommendations

    1. Freeze the language backbone and train only lightweight modules. This significantly reduces cost and limits catastrophic forgetting.
    2. Model non-protein parts explicitly. Antibody design often involves glycosylation, inter-chain disulfide bonds, and aggregation propensity, so you cannot look only at a single binding pocket.
    3. Cache structures and compute incrementally. Constant parts such as antigens can have their structure features cached, and only the design-variable regions need incremental encoding.
    4. Embed quality gates into the pipeline. Automated verification should be a necessary condition for advancing candidates, not an after-the-fact manual spot check.
    5. Continuously monitor distribution drift. After a structure-prediction model is updated, its output distribution may shift, so the adapter needs monitoring and recalibration.

    8. Capability Boundaries: Placing “Surpassing” in the Right Coordinate Frame

    Structure-aware reasoning is not meant to fully replace dedicated structure-prediction models, but to fill the gap in language models’ geometric reasoning.

    It is more valuable in the following three types of tasks:

    • Structure-aware interpretation: placing structure into a fuller reasoning context, rather than only outputting a single prediction result.
    • Multi-objective design reasoning: antibody design requires trade-offs among affinity, specificity, stability, immunogenicity, and developability.
    • Explainable research collaboration: a system that can explain “why it was designed this way” and which evidence supports which conclusion is easier for researchers to validate and adopt.

    At the same time, the limitations should be acknowledged:

    • Geometric intuition cannot replace physical computation. Binding free energy, conformational entropy, and explicit solvent effects still require dedicated simulation and experiments.
    • The longer the reasoning chain, the more easily errors accumulate. Each geometry primitive and verification step should be traceable.
    • Data coverage determines extrapolation ability. For binding modes rare in the training data, model performance may degrade noticeably.
    • Single-chain design is not the same as a complete molecule. Post-translational modifications, glycosylation, and immune effects still require dedicated models and experimental support.

    Compliance boundaries also need to be explicit:

    • Computational conclusions involving protein, antibody, and molecular design can serve only as research hypotheses and engineering aids, not as a direct basis for clinical, medical, or production use.
    • When using public databases, literature data, or internal data, confirm data authorization, license agreements, and scope of use, and avoid using restricted data for training or release.
    • Any scheme entering wet-lab, animal, or preclinical research must pass the appropriate ethics review, biosafety review, and experimental validation.
    • The design system should preserve the experiment lead’s decision-making authority over the final plan, and must not treat model output as an directly implementable experimental protocol.

    9. Conclusion

    When language models enter protein folding and antibody design, the real barrier is not language ability but how geometric information is conveyed.

    Textualizing coordinates sounds like a mere formatting issue, but in fact each step loses atom-level detail, and those details often determine whether binding can occur and whether a design is feasible.

    A deployable route can be summarized as follows:

    1. The structure encoder faithfully converts 3D information into features.
    2. The cross-modal adapter connects structure features into the language model’s hidden space.
    3. The structured chain of thought and geometry primitives ground reasoning in computable statements.
    4. External verification constrains hallucinations and provides verifiable conclusions.

    For development teams, the key is not to chase “surpassing” on a single metric, but to build a solid “perceive–reason–verify” loop that combines the flexibility of language models with the reliability of dedicated tools, so that every design hypothesis can be reviewed by a machine and tested by an experiment.