SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2401.03870 · AAAI · 2024

Gramformer: Learning Crowd Counting via Graph-Modulated Transformer

Hong, Deyu Meng, Hui Lin, Zhiheng Ma, Qinnan Shangguan

arXiv · PDF · Open in the Atlas

Code that ran

2 of 2 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 2 have no contract verdict; 0 failures of our instrument; 0 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/2401.03870.json · badge: /api/ran/2401.03870.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
LoraLinH/Gramformer community
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
GraphMultiheadAttention Ran
ran on a synthesized input
LoraLinH/Gramformer/models/graph_attention.py
code served (permissive licence) · get_code("3d90f84242a13ba8")
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
from torch import nn
import torch.nn.functional as F

class ScaledDotProductAttention(nn.Module):
    """ Scaled Dot-Product Attention """

    def __init__(self, temperature, attn_dropout=0.1):
        super().__init__()
        self.temperature = temperature
        self.dropout = nn.Dropout(attn_dropout)

    def forward(self, q, k, v, graph_pos=None, mask=None):
        attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
        if mask is not None:
            attn = attn.masked_fill(mask == 0, -1000000000.0)
        attno = self.dropout(F.softmax(attn, dim=-1))
        if graph_pos is not None:
            attn = attno * graph_pos.permute(2, 1, 0).unsqueeze(0)
        output = torch.matmul(attn, v)
        return (output, attno)

class GraphMultiheadAttention(nn.Module):
    """ Multi-Head Attention module """

    def __init__(self, d_model, n_head, dropout=0.1):
        super().__init__()
        self.n_head = n_head
        self.d_k = d_model // n_head
        self.d_v = d_model // n_head
        self.w_qs = nn.Linear(d_model, n_head * self.d_k, bias=False)
        self.w_ks = nn.Linear(d_model, n_head * self.d_k, bias=False)
        self.w_vs = nn.Linear(d_model, n_head * self.d_v, bias=False)
        self.fc = nn.Linear(n_head * self.d_v, d_model, bias=False)
        self.attention = ScaledDotProductAttention(temperature=self.d_k ** 0.5)
        self.dropout = nn.Dropout(dropout)
        self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)

    def forward(self, q, k, v, graph_pos=None, mask=None):
        q = q.permute(1, 0, 2)
        k = k.permute(1, 0, 2)
        v = v.permute(1, 0, 2)
        d_k, d_v, n_head = (self.d_k, self.d_v, self.n_head)
        sz_b, len_q, len_k, len_v = (q.size(0), q.size(1), k.size(1), v.size(1))
        residual = q
        q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
        k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
        v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
        q, k, v = (q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2))
        if mask is not None:
            mask = mask.unsqueeze(1)
        q, attn = self.attention(q, k, v, graph_pos=graph_pos, mask=mask)
        q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
        q = self.dropout(self.fc(q))
        q += residual
        q = self.layer_norm(q)
        q = q.permute(1, 0, 2)
        return (q, attn)


INIT_ARGS = {
    'd_model': 4,
    'n_head': 2,
    'dropout': 0.1,
}

ARGS = {
    'q': torch.randn(3, 2, 4),
    'k': torch.randn(3, 2, 4),
    'v': torch.randn(3, 2, 4),
    'graph_pos': None,
    'mask': None,
}

if __name__ == '__main__':
    model = GraphMultiheadAttention(**INIT_ARGS)
    output, attn = model(**ARGS)
    print("Output shape:", output.shape)
    print("Attention shape:", attn.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)
ScaledDotProductAttention Ran
ran on a synthesized input
LoraLinH/Gramformer/models/graph_attention.py
code served (permissive licence) · get_code("c3319cd59bc27548")
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
from torch import nn
import torch.nn.functional as F

class ScaledDotProductAttention(nn.Module):
    """ Scaled Dot-Product Attention """

    def __init__(self, temperature, attn_dropout=0.1):
        super().__init__()
        self.temperature = temperature
        self.dropout = nn.Dropout(attn_dropout)

    def forward(self, q, k, v, graph_pos=None, mask=None):
        attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
        if mask is not None:
            attn = attn.masked_fill(mask == 0, -1000000000.0)
        attno = self.dropout(F.softmax(attn, dim=-1))
        if graph_pos is not None:
            attn = attno * graph_pos.permute(2, 1, 0).unsqueeze(0)
        output = torch.matmul(attn, v)
        return (output, attno)


INIT_ARGS = {
    'temperature': 4.0,
    'attn_dropout': 0.1,
}

ARGS = {
    'q': torch.randn(2, 3, 5, 4),
    'k': torch.randn(2, 3, 6, 4),
    'v': torch.randn(2, 3, 6, 7),
    'graph_pos': None,
    'mask': None,
}

if __name__ == '__main__':
    model = ScaledDotProductAttention(**INIT_ARGS)
    output, attention = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Attention shape: {attention.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)

Also present in other papers' code

Of 2 samples lifted from this paper's linked repositories, 2 carry a function identity and 0 do not. Of the 2 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 2 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

Transformer has been popular in recent crowd counting work since it breaks the limited receptive field of traditional CNNs. However, since crowd images always contain a large number of similar patches, the self-attention mechanism in Transformer tends to find a homogenized solution where the attention maps of almost all patches are identical. In this paper, we address this problem by proposing Gramformer: a graph-modulated transformer to enhance the network by adjusting the attention and input node features respectively on the basis of two different types of graphs. Firstly, an attention graph is proposed to diverse attention maps to attend to complementary information. The graph is building upon the dissimilarities between patches, modulating the attention in an anti-similarity fashion. Secondly, a feature-based centrality encoding is proposed to discover the centrality positions or importance of nodes. We encode them with a proposed centrality indices scheme to modulate the node features and similarity relationships. Extensive experiments on four challenging crowd counting datasets have validated the competitiveness of the proposed method. Code is available at https://github.com/LoraLinH/Gramformer.

For agents

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

get_harvested_code_for_paper("2401.03870")
get_code_for_paper("2401.03870")
have("2401.03870")

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

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

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

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

Connect an agent — have() is free.