SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2607.23607 · 2026

MS-GPT: Rethinking MS/MS De Novo Structure Elucidation as Spectrum-Induced Posterior Querying of a Molecule-Language Model

Xiaokang Yang, Xin Zhao, Yaohui Jin, Yanyan Xu

arXiv · PDF · Open in the Atlas

Code that ran

4 of 5 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 4 have no contract verdict; 0 failures of our instrument; 1 no recorded run), measured 2026-11-23; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2607.23607.json · badge: /api/ran/2607.23607.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
VIKI623/MS-GPT community
Papers with Code archive
4 ran · 1 no recorded run
FunctionStatusWhere it lives
CrossAttentionConditioner Ran
ran on a synthesized input
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py
code served (permissive licence) · get_code("bf9ce3393e79bf14")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

# Import the classes
from typing import Optional, Tuple, Union

class SplitQKVMultiheadAttention(nn.Module):
    """nn.MultiheadAttention with Q/K/V as separate Linear submodules."""

    def __init__(self, embed_dim: int, num_heads: int, dropout: float=0.0, bias: bool=True):
        super().__init__()
        if embed_dim % num_heads != 0:
            raise ValueError(f'embed_dim {embed_dim} not divisible by num_heads {num_heads}')
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.head_dim = embed_dim // num_heads
        self.scale = self.head_dim ** (-0.5)
        self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
        self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
        self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
        self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
        self.attn_dropout = nn.Dropout(dropout)

    def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: Optional[torch.Tensor]=None, need_weights: bool=False) -> Tuple[torch.Tensor, None]:
        B, Lq, _ = query.shape
        Lk = key.shape[1]
        q = self.q_proj(query).view(B, Lq, self.num_heads, self.head_dim).transpose(1, 2)
        k = self.k_proj(key).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
        v = self.v_proj(value).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
        attn = torch.matmul(q * self.scale, k.transpose(-2, -1))
        if key_padding_mask is not None:
            attn = attn.masked_fill(key_padding_mask[:, None, None, :], float('-inf'))
        attn = attn.softmax(dim=-1)
        attn = self.attn_dropout(attn)
        out = torch.matmul(attn, v).transpose(1, 2).reshape(B, Lq, self.embed_dim)
        out = self.out_proj(out)
        return (out, None)

class CrossAttentionConditioner(nn.Module):
    """Cross-attention layer injected into GPT-2 blocks for FP/formula conditioning."""

    def __init__(self, d_model: int=768, num_heads: int=12, dropout: float=0.1):
        super().__init__()
        self.cross_attn = SplitQKVMultiheadAttention(embed_dim=d_model, num_heads=num_heads, dropout=dropout)
        self.norm = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(nn.Linear(d_model, d_model * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model * 4, d_model), nn.Dropout(dropout))
        self.norm2 = nn.LayerNorm(d_model)

    def forward(self, x: torch.Tensor, context: torch.Tensor, context_mask: Optional[torch.Tensor]=None) -> torch.Tensor:
        """
        Args:
            x: (batch, seq_len, d_model) - MLM hidden states
            context: (batch, ctx_len, d_model) - condition embeddings
            context_mask: (batch, ctx_len) - True=valid, False=padding
        """
        key_padding_mask = ~context_mask if context_mask is not None else None
        residual = x
        x = self.norm(x)
        x, _ = self.cross_attn(x, context, context, key_padding_mask=key_padding_mask)
        x = residual + x
        x = x + self.ffn(self.norm2(x))
        return x


# Setup code
INIT_ARGS = {
    'd_model': 4,
    'num_heads': 2,
    'dropout': 0.1,
}

ARGS = {
    'x': torch.randn(2, 3, 4),
    'context': torch.randn(2, 5, 4),
    'context_mask': torch.tensor([[True, True, True, True, False], [True, True, False, False, False]]),
}

# Construct and call
model = CrossAttentionConditioner(**INIT_ARGS)
output = model(**ARGS)
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
FingerprintEncoder Ran
ran on a synthesized input
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py
code served (permissive licence) · get_code("ed0edb0264d1759e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

INIT_ARGS = {
    'fp_bits': 64,
    'd_model': 16,
    'max_active_bits': 8,
    'num_layers': 2,
    'num_heads': 4,
    'dropout': 0.1,
}

ARGS = {
    'fingerprint': torch.randint(0, 2, (2, 64)).float(),
}

if __name__ == '__main__':
    from typing import Optional, Tuple, Union

    class FingerprintEncoder(nn.Module):
        """Encodes sparse Morgan fingerprint into dense sequence of embeddings."""

        def __init__(self, fp_bits: int=4096, d_model: int=768, max_active_bits: int=256, num_layers: int=2, num_heads: int=8, dropout: float=0.1):
            super().__init__()
            self.fp_bits = fp_bits
            self.max_active_bits = max_active_bits
            self.d_model = d_model
            self.bit_embedding = nn.Embedding(fp_bits, d_model)
            self.value_proj = nn.Linear(1, d_model)
            self.combine = nn.Linear(d_model * 2, d_model)
            encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=d_model * 4, dropout=dropout, activation='gelu', batch_first=True, norm_first=True)
            self.self_attn = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
            self.norm = nn.LayerNorm(d_model)

        def forward(self, fingerprint: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
            """
            Args:
                fingerprint: (batch, fp_bits) binary or soft fingerprint
            Returns:
                embeddings: (batch, seq_len, d_model) - active bit embeddings
                mask: (batch, seq_len) - padding mask (True = valid)
            """
            batch_size = fingerprint.shape[0]
            device = fingerprint.device
            embeddings_list = []
            masks = []
            for i in range(batch_size):
                active_idx = fingerprint[i].nonzero(as_tuple=True)[0]
                if len(active_idx) > self.max_active_bits:
                    active_idx = active_idx[:self.max_active_bits]
                n_active = len(active_idx)
                if n_active == 0:
                    active_idx = torch.zeros(1, dtype=torch.long, device=device)
                    n_active = 1
                bit_emb = self.bit_embedding(active_idx)
                val_emb = self.value_proj(fingerprint[i, active_idx].unsqueeze(-1))
                combined = self.combine(torch.cat([bit_emb, val_emb], dim=-1))
                pad_len = self.max_active_bits - n_active
                if pad_len > 0:
                    padding = torch.zeros(pad_len, self.d_model, device=device)
                    combined = torch.cat([combined, padding], dim=0)
                embeddings_list.append(combined)
                mask = torch.cat([torch.ones(n_active, device=device, dtype=torch.bool), torch.zeros(pad_len, device=device, dtype=torch.bool)]) if pad_len > 0 else torch.ones(n_active, device=device, dtype=torch.bool)
                masks.append(mask)
            embeddings = torch.stack(embeddings_list)
            mask = torch.stack(masks)
            src_key_padding_mask = ~mask
            embeddings = self.self_attn(embeddings, src_key_padding_mask=src_key_padding_mask)
            embeddings = self.norm(embeddings)
            return (embeddings, mask)

    model = FingerprintEncoder(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output embeddings shape: {output[0].shape}")
    print(f"Output mask shape: {output[1].shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
FormulaEncoder Ran
ran on a synthesized input
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py
code served (permissive licence) · get_code("52be847181a1ee5c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 14, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

class FormulaEncoder(nn.Module):
    """Encodes molecular formula (element counts) into embeddings."""
    ELEMENTS = ['C', 'H', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br', 'I', 'B', 'Si', 'Se', 'As']

    def __init__(self, d_model: int=768, max_count: int=200):
        super().__init__()
        self.n_elements = len(self.ELEMENTS)
        self.element_embedding = nn.Embedding(self.n_elements, d_model)
        self.count_proj = nn.Sequential(nn.Linear(1, d_model), nn.GELU(), nn.Linear(d_model, d_model))
        self.combine = nn.Linear(d_model * 2, d_model)
        self.norm = nn.LayerNorm(d_model)

    def forward(self, formula_vec: torch.Tensor) -> torch.Tensor:
        """
        Args:
            formula_vec: (batch, n_elements) element count vector
        Returns:
            (batch, n_elements, d_model) formula embeddings
        """
        batch_size = formula_vec.shape[0]
        device = formula_vec.device
        elem_idx = torch.arange(self.n_elements, device=device).unsqueeze(0).expand(batch_size, -1)
        elem_emb = self.element_embedding(elem_idx)
        count_emb = self.count_proj(formula_vec.unsqueeze(-1))
        combined = self.combine(torch.cat([elem_emb, count_emb], dim=-1))
        return self.norm(combined)


INIT_ARGS = {
    'd_model': 4,
    'max_count': 200,
}

ARGS = {
    'formula_vec': torch.randn(2, 14),
}

if __name__ == '__main__':
    encoder = FormulaEncoder(**INIT_ARGS)
    output = encoder(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: (2, 14, 4)")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 14, 4) — shape (2, 14, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
SplitQKVMultiheadAttention Ran
ran on a synthesized input
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py
code served (permissive licence) · get_code("40c0bf0afe9be616")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

INIT_ARGS = {
    'embed_dim': 8,
    'num_heads': 2,
    'dropout': 0.1,
    'bias': True,
}

ARGS = {
    'query': torch.randn(2, 3, 8),
    'key': torch.randn(2, 4, 8),
    'value': torch.randn(2, 4, 8),
    'key_padding_mask': None,
    'need_weights': False,
}

if __name__ == '__main__':
    from typing import Optional, Tuple, Union

    class SplitQKVMultiheadAttention(nn.Module):
        """nn.MultiheadAttention with Q/K/V as separate Linear submodules.

        Math is bit-identical to ``nn.MultiheadAttention(batch_first=True)`` so
        that released checkpoints can transfer through ``normalize_mlm_checkpoint_state_dict``
        without retraining. We expose q_proj / k_proj / v_proj as standalone
        nn.Linear modules so peft LoRA can target them directly (the original
        nn.MultiheadAttention bundles them in a single ``in_proj_weight``
        parameter, which peft cannot target).
        """

        def __init__(self, embed_dim: int, num_heads: int, dropout: float=0.0, bias: bool=True):
            super().__init__()
            if embed_dim % num_heads != 0:
                raise ValueError(f'embed_dim {embed_dim} not divisible by num_heads {num_heads}')
            self.embed_dim = embed_dim
            self.num_heads = num_heads
            self.head_dim = embed_dim // num_heads
            self.scale = self.head_dim ** (-0.5)
            self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
            self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
            self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
            self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
            self.attn_dropout = nn.Dropout(dropout)

        def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: Optional[torch.Tensor]=None, need_weights: bool=False) -> Tuple[torch.Tensor, None]:
            B, Lq, _ = query.shape
            Lk = key.shape[1]
            q = self.q_proj(query).view(B, Lq, self.num_heads, self.head_dim).transpose(1, 2)
            k = self.k_proj(key).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
            v = self.v_proj(value).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
            attn = torch.matmul(q * self.scale, k.transpose(-2, -1))
            if key_padding_mask is not None:
                attn = attn.masked_fill(key_padding_mask[:, None, None, :], float('-inf'))
            attn = attn.softmax(dim=-1)
            attn = self.attn_dropout(attn)
            out = torch.matmul(attn, v).transpose(1, 2).reshape(B, Lq, self.embed_dim)
            out = self.out_proj(out)
            return (out, None)

    model = SplitQKVMultiheadAttention(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output[0].shape}")
    print(f"Output weights: {output[1]}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
ConditionalMoleculeLanguageModel Not yet run
unverified (harvested, no recorded run)
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py
code served (permissive licence) · get_code("47b68d47b6b345db")
How it ran

no invocation recorded.

Also present in other papers' code

Of 5 samples lifted from this paper's linked repositories, 5 carry a function identity and 0 do not. Of the 5 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 5 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Molecular structure elucidation from tandem mass spectra (MS/MS) is a central inverse problem in analytical chemistry. Most existing approaches to MS/MS identification remain tied to reference libraries or predefined candidate sets, whereas de novo methods aim to generate structures directly from spectra. A common de novo route predicts a molecular fingerprint from the spectrum and then decodes structures from it, enabling decoder pretraining on large molecule-only corpora. However, this paradigm creates a training-inference mismatch: the decoder is trained on oracle fingerprints computed from molecules, but at inference it is queried with a noisy spectrum-induced fingerprint posterior that is typically collapsed to a single thresholded fingerprint. We introduce MS-GPT, which recasts fingerprint-mediated de novo elucidation as spectrum-induced posterior querying of a conditional molecule-language model. MS-GPT conditions a moleculelanguage model on fingerprints and formulas, then converts the spectrum-induced posterior into a band of fingerprint queries near the oracle-fingerprint manifold through active-bit density calibration. Candidates sampled across this band are pooled and ranked by generation-frequency consensus. A lightweight LoRA adapter further mitigates domain-specific posterior bias while preserving * Corresponding authors. the pretrained molecular prior. On NPLIB1 and MassSpecGym, MS-GPT sets a new state of the art, reaching Top-1/Top-10 exact-match accuracy of 29.8%/41.1% and 23.9%/28.7%, respectively. Candidatepool scaling shows that efficient autoregressive molecular generation continues to improve recall with a little additional inference cost. The source code and model checkpoints are available at https://github.com/VIKI623/MS-GPT. • Computing methodologies → Machine learning; • Applied computing → Chemistry.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2607.23607")
get_code_for_paper("2607.23607")
have("2607.23607")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2607.23607.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2607.23607.svg)](https://syntology.ai/paper/2607.23607)

Connect an agent — have() is free.