SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2605.20188 · 2026

GraphDiffMed: Knowledge-Constrained Differential Attention with Pharmacological Graph Priors for Medication Recommendation

Krati Saxena, Tomohiro Shibata

arXiv · PDF · Open in the Atlas

Code that ran

9 of 11 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 9 have no contract verdict; 0 failures of our instrument; 2 no recorded run), measured 2026-11-22; 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/2605.20188.json · badge: /api/ran/2605.20188.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
saxenakrati09/GraphDiffMed community
Papers with Code archive
9 ran · 2 no recorded run
FunctionStatusWhere it lives
CausalWeight Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("67284335dd496e60")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 networkx as nx

import torch
import torch.nn as nn

class LearnableMaskLayer(nn.Module):

    def __init__(self, emb_dim):
        super(LearnableMaskLayer, self).__init__()
        self.mask_weights = nn.Parameter(torch.ones(emb_dim))

    def forward(self, x):
        return x * self.mask_weights

class CausalWeight(nn.Module):

    def __init__(self, emb_dim, device):
        super(CausalWeight, self).__init__()
        self.device = device
        self.list_weights = nn.ModuleList([LearnableMaskLayer(emb_dim) for _ in range(4)])

    def forward(self, x, causal_graph):
        echelon = self.node_classify(causal_graph)
        x1 = torch.zeros_like(x)
        for i, node_list in enumerate(echelon):
            for node in node_list:
                x1[0, node, :] += self.list_weights[i](x[0, node, :])
        return x1

    def node_classify(self, causal_graph):
        """初始化四个类别的列表 从因到果
        0无入度有出度 因节点
        1无入度无出度 孤儿节点
        2有入度有出度 中间节点
        3有入度无出度 果节点"""
        echelon = [[], [], [], []]
        for node in causal_graph.nodes():
            in_degree = causal_graph.in_degree(node)
            out_degree = causal_graph.out_degree(node)
            if in_degree == 0 and out_degree == 0:
                echelon[1].append(node)
            elif in_degree > 0 and out_degree == 0:
                echelon[3].append(node)
            elif in_degree == 0 and out_degree > 0:
                echelon[0].append(node)
            else:
                echelon[2].append(node)
        return echelon


# Create a simple causal graph for testing
causal_graph = nx.DiGraph()
causal_graph.add_nodes_from([0, 1, 2, 3])
causal_graph.add_edges_from([(0, 1), (1, 2), (2, 3)])

INIT_ARGS = {
    'emb_dim': 4,
    'device': 'cpu'
}

ARGS = {
    'x': torch.randn(1, 4, 4),
    'causal_graph': causal_graph
}

if __name__ == '__main__':
    model = CausalWeight(**INIT_ARGS)
    output = model(**ARGS)
    print("Output shape:", output.shape)
    print("Output:", output)
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
networkx, 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
CausaltyReview Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("afb1d92aa3fc5b88")
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 2, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 MockCasualGraph:
    """Mock casual graph that returns threshold effects and causal effects."""
    
    def __init__(self):
        self.effects = {}
    
    def get_threshold_effect(self, threshold, source_type, target_type):
        """Return a mock threshold effect value."""
        return threshold * 0.5
    
    def get_effect(self, source_id, target_id, source_type, target_type):
        """Return a mock causal effect between source and target."""
        key = (source_id, target_id, source_type, target_type)
        if key not in self.effects:
            self.effects[key] = torch.rand(1).item() * 0.8
        return self.effects[key]


class CausaltyReview(nn.Module):

    def __init__(self, casual_graph, num_diag, num_proc, num_med):
        super(CausaltyReview, self).__init__()
        self.num_med = num_med
        self.c1 = casual_graph
        diag_med_high = casual_graph.get_threshold_effect(0.97, 'Diag', 'Med')
        diag_med_low = casual_graph.get_threshold_effect(0.9, 'Diag', 'Med')
        proc_med_high = casual_graph.get_threshold_effect(0.97, 'Proc', 'Med')
        proc_med_low = casual_graph.get_threshold_effect(0.9, 'Proc', 'Med')
        self.c1_high_limit = nn.Parameter(torch.tensor([diag_med_high, proc_med_high]))
        self.c1_low_limit = nn.Parameter(torch.tensor([diag_med_low, proc_med_low]))
        self.c1_minus_weight = nn.Parameter(torch.tensor(0.01))
        self.c1_plus_weight = nn.Parameter(torch.tensor(0.01))

    def forward(self, pre_prob, diags, procs):
        reviewed_prob = pre_prob.clone()
        for m in range(self.num_med):
            max_cdm = 0.0
            max_cpm = 0.0
            for d in diags:
                cdm = self.c1.get_effect(d, m, 'Diag', 'Med')
                max_cdm = max(max_cdm, cdm)
            for p in procs:
                cpm = self.c1.get_effect(p, m, 'Proc', 'Med')
                max_cpm = max(max_cpm, cpm)
            if max_cdm < self.c1_low_limit[0] and max_cpm < self.c1_low_limit[1]:
                reviewed_prob[0, m] -= self.c1_minus_weight
            elif max_cdm > self.c1_high_limit[0] or max_cpm > self.c1_high_limit[1]:
                reviewed_prob[0, m] += self.c1_plus_weight
        return reviewed_prob


casual_graph = MockCasualGraph()

INIT_ARGS = {
    'casual_graph': casual_graph,
    'num_diag': 3,
    'num_proc': 2,
    'num_med': 4,
}

ARGS = {
    'pre_prob': torch.rand(1, 4),
    'diags': [0, 1, 2],
    'procs': [0, 1],
}

model = CausaltyReview(**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 2, dtype family float — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
DiffCrossAttention_intervisit Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("9d3f60142b8ee979")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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

# Device setup
device = torch.device('cpu')

# INIT_ARGS: parameters for __init__
INIT_ARGS = {
    'emb_dim': 4,
    'num_heads': 2,
    'device': device,
    'dropout': 0.3,
    'batch_first': True,
    'lambda_graph': 0.1,
}

# ARGS: parameters for forward()
# Batch size: 2, Query length: 3, Key/Value length: 5, Embedding dim: 4
ARGS = {
    'query': torch.randn(2, 3, 4),
    'key': torch.randn(2, 5, 4),
    'value': torch.randn(2, 5, 4),
    'graph_bias': torch.randn(3, 5),
}

# Construct and call
if __name__ == '__main__':
    model = nn.Module()
    model.__class__ = type('DiffCrossAttention_intervisit', (nn.Module,), {
        '__init__': DiffCrossAttention_intervisit.__init__,
        'forward': DiffCrossAttention_intervisit.forward,
        '_shape': DiffCrossAttention_intervisit._shape,
    })
    
    # Import the class properly
    import sys
    sys.path.insert(0, '.')
    
    from torch import nn
    import torch.nn.functional as F
    
    class DiffCrossAttention_intervisit(nn.Module):
        def __init__(self, emb_dim, num_heads, device, dropout=0.3, batch_first=True, lambda_graph=0.1):
            super(DiffCrossAttention_intervisit, self).__init__()
            assert num_heads % 2 == 0, 'num_heads must be even for Diff-Attn V2 pairing'
            self.emb_dim = emb_dim
            self.num_heads = num_heads
            self.head_dim = emb_dim // num_heads
            self.device = device
            self.dropout = dropout
            self.batch_first = batch_first
            self.lambda_graph = lambda_graph
            self.query_proj = nn.Linear(emb_dim, emb_dim * 2)
            self.key_proj = nn.Linear(emb_dim, emb_dim)
            self.value_proj = nn.Linear(emb_dim, emb_dim)
            self.lambda_proj = nn.Linear(emb_dim, num_heads)
            self.out_proj = nn.Linear(emb_dim, emb_dim)
            self.dropout_layer = nn.Dropout(dropout)

        def _shape(self, x, B, T, H):
            return x.view(B, T, H, self.head_dim).transpose(1, 2)

        def forward(self, query, key, value, graph_bias=None):
            B, Tq, _ = query.size()
            _, Tk, _ = key.size()
            q = self.query_proj(query)
            k = self.key_proj(key)
            v = self.value_proj(value)
            q = self._shape(q, B, Tq, self.num_heads * 2)
            k = self._shape(k, B, Tk, self.num_heads)
            v = self._shape(v, B, Tk, self.num_heads)
            k = k.repeat_interleave(2, dim=1)
            v = v.repeat_interleave(2, dim=1)
            attn_scores = torch.matmul(q, k.transpose(-2, -1)) / self.head_dim ** 0.5
            if graph_bias is not None:
                if not torch.is_tensor(graph_bias):
                    graph_bias = torch.tensor(graph_bias, device=attn_scores.device, dtype=attn_scores.dtype)
                else:
                    graph_bias = graph_bias.to(device=attn_scores.device, dtype=attn_scores.dtype)
                if graph_bias.dim() == 0:
                    graph_bias = graph_bias.view(1, 1, 1, 1)
                elif graph_bias.dim() == 2:
                    graph_bias = graph_bias.unsqueeze(0).unsqueeze(0)
                elif graph_bias.dim() == 3:
                    graph_bias = graph_bias.unsqueeze(1)
                elif graph_bias.dim() != 4:
                    raise ValueError(f'graph_bias must have 0, 2, 3, or 4 dims, got {graph_bias.dim()}')
                if graph_bias.size(-2) not in (1, Tq) or graph_bias.size(-1) not in (1, Tk):
                    raise ValueError(f'graph_bias last dims must be broadcastable to ({Tq}, {Tk}), got ({graph_bias.size(-2)}, {graph_bias.size(-1)})')
                attn_scores = attn_scores + self.lambda_graph * graph_bias
            attn_weights = F.softmax(attn_scores, dim=-1)
            context = torch.matmul(attn_weights, v)
            attn1 = context[:, 0::2, :, :]
            attn2 = context[:, 1::2, :, :]
            lambda_val = self.lambda_proj(query)
            lambda_val = torch.sigmoid(lambda_val)
            lambda_val = lambda_val.permute(0, 2, 1).unsqueeze(-1)
            diff_context = attn1 - lambda_val * attn2
            diff_context = diff_context.transpose(1, 2).contiguous().view(B, Tq, self.emb_dim)
            output = self.out_proj(self.dropout_layer(diff_context))
            return output
    
    model = DiffCrossAttention_intervisit(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
DiffCrossAttention_intravisit Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("77a2f0191eea09fe")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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

# Device setup
device = torch.device('cpu')

# INIT_ARGS: all parameters for __init__
INIT_ARGS = {
    'emb_dim': 4,
    'num_heads': 2,
    'device': device,
    'dropout': 0.3,
    'batch_first': True,
    'lambda_graph': 0.1,
}

# ARGS: all parameters for forward()
ARGS = {
    'query': torch.randn(2, 3, 4),  # (batch=2, seq_len=3, emb_dim=4)
    'key': torch.randn(2, 5, 4),    # (batch=2, seq_len=5, emb_dim=4)
    'value': torch.randn(2, 5, 4),  # (batch=2, seq_len=5, emb_dim=4)
    'graph_bias': torch.randn(3, 5),  # (Tq=3, Tk=5)
}

# Construct and call
if __name__ == '__main__':
    from torch import nn
    import torch.nn.functional as F
    
    class DiffCrossAttention_intravisit(nn.Module):

        def __init__(self, emb_dim, num_heads, device, dropout=0.3, batch_first=True, lambda_graph=0.1):
            super(DiffCrossAttention_intravisit, self).__init__()
            assert num_heads % 2 == 0, 'num_heads must be even for Diff-Attn V2 pairing'
            self.emb_dim = emb_dim
            self.num_heads = num_heads
            self.head_dim = emb_dim // num_heads
            self.device = device
            self.dropout = dropout
            self.batch_first = batch_first
            self.lambda_graph = lambda_graph
            self.query_proj = nn.Linear(emb_dim, emb_dim * 2)
            self.key_proj = nn.Linear(emb_dim, emb_dim)
            self.value_proj = nn.Linear(emb_dim, emb_dim)
            self.lambda_proj = nn.Linear(emb_dim, num_heads)
            self.out_proj = nn.Linear(emb_dim, emb_dim)
            self.dropout_layer = nn.Dropout(dropout)

        def _shape(self, x, B, T, H):
            return x.view(B, T, H, self.head_dim).transpose(1, 2)

        def forward(self, query, key, value, graph_bias=None):
            B, Tq, _ = query.size()
            _, Tk, _ = key.size()
            q = self.query_proj(query)
            k = self.key_proj(key)
            v = self.value_proj(value)
            q = self._shape(q, B, Tq, self.num_heads * 2)
            k = self._shape(k, B, Tk, self.num_heads)
            v = self._shape(v, B, Tk, self.num_heads)
            k = k.repeat_interleave(2, dim=1)
            v = v.repeat_interleave(2, dim=1)
            attn_scores = torch.matmul(q, k.transpose(-2, -1)) / self.head_dim ** 0.5
            if graph_bias is not None:
                if not torch.is_tensor(graph_bias):
                    graph_bias = torch.tensor(graph_bias, device=attn_scores.device, dtype=attn_scores.dtype)
                else:
                    graph_bias = graph_bias.to(device=attn_scores.device, dtype=attn_scores.dtype)
                if graph_bias.dim() == 0:
                    graph_bias = graph_bias.view(1, 1, 1, 1)
                elif graph_bias.dim() == 2:
                    graph_bias = graph_bias.unsqueeze(0).unsqueeze(0)
                elif graph_bias.dim() == 3:
                    graph_bias = graph_bias.unsqueeze(1)
                elif graph_bias.dim() != 4:
                    raise ValueError(f'graph_bias must have 0, 2, 3, or 4 dims, got {graph_bias.dim()}')
                if graph_bias.size(-2) not in (1, Tq) or graph_bias.size(-1) not in (1, Tk):
                    raise ValueError(f'graph_bias last dims must be broadcastable to ({Tq}, {Tk}), got ({graph_bias.size(-2)}, {graph_bias.size(-1)})')
                attn_scores = attn_scores + self.lambda_graph * graph_bias
            attn_weights = F.softmax(attn_scores, dim=-1)
            context = torch.matmul(attn_weights, v)
            attn1 = context[:, 0::2, :, :]
            attn2 = context[:, 1::2, :, :]
            lambda_val = self.lambda_proj(query)
            lambda_val = torch.sigmoid(lambda_val)
            lambda_val = lambda_val.permute(0, 2, 1).unsqueeze(-1)
            diff_context = attn1 - lambda_val * attn2
            diff_context = diff_context.transpose(1, 2).contiguous().view(B, Tq, self.emb_dim)
            output = self.out_proj(self.dropout_layer(diff_context))
            return output

    model = DiffCrossAttention_intravisit(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
GIN Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("d8f6a1a2a70d8225")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 numpy as np
from torch_geometric.nn import GINConv

INIT_ARGS = {
    'input_dim': 4,
    'hidden_dim': 8
}

# Construct input tensors
x = torch.randn(2, 4)  # batch of 2 nodes, feature dim 4
edge_index = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)  # bidirectional edge between nodes 0 and 1
weights = torch.randn(2)  # weights for each node

ARGS = {
    'x': x,
    'edge_index': edge_index,
    'weights': weights
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch, torch_geometric — 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
LearnableMaskLayer Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("7de52f5a0a3cadde")
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 2, dtype family float, shape (2, 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 LearnableMaskLayer(nn.Module):

    def __init__(self, emb_dim):
        super(LearnableMaskLayer, self).__init__()
        self.mask_weights = nn.Parameter(torch.ones(emb_dim))

    def forward(self, x):
        return x * self.mask_weights


INIT_ARGS = {
    'emb_dim': 4
}

ARGS = {
    'x': torch.randn(2, 4)
}

if __name__ == '__main__':
    layer = LearnableMaskLayer(**INIT_ARGS)
    output = layer(**ARGS)
    print(output)
    print(output.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 Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 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)
SelfAttention Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("cbc1e928132dfbcd")
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

INIT_ARGS = {
    'emb_dim': 4,
    'num_heads': 2,
    'device': 'cpu',
    'dropout': 0.3,
    'batch_first': True,
}

ARGS = {
    'query': torch.randn(2, 3, 4),
    'key': torch.randn(2, 3, 4),
    'value': torch.randn(2, 3, 4),
}

if __name__ == '__main__':
    model = nn.SelfAttention(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
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)
hetero_effect_graph Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("0f66203962c9e5dd")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 numpy as np
from torch_geometric.nn import RGCNConv

# INIT_ARGS for hetero_effect_graph.__init__
INIT_ARGS = {
    'in_channels': 8,
    'out_channels': 6,
    'device': torch.device('cpu'),
    'levels': 5
}

# ARGS for hetero_effect_graph.forward
# emb_entity: (1, num_entities, in_channels)
# emb_mole: (1, num_moles, in_channels)
# entity_mole_weights: (num_entities, num_moles) - weights between 0 and 1

num_entities = 4
num_moles = 3
in_channels = 8

emb_entity = torch.randn(1, num_entities, in_channels)
emb_mole = torch.randn(1, num_moles, in_channels)
entity_mole_weights = np.random.rand(num_entities, num_moles)

ARGS = {
    'emb_entity': emb_entity,
    'emb_mole': emb_mole,
    'entity_mole_weights': entity_mole_weights
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch, torch_geometric — 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
homo_relation_graph Ran
ran on a synthesized input
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("c6a867bdc540ec2b")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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
from torch_geometric.data import Data
import networkx as nx

INIT_ARGS = {
    'emb_dim': 4,
    'device': 'cpu'
}

# Create a small causal graph with 6 nodes demonstrating all 4 node types
graph = nx.DiGraph()
graph.add_edges_from([
    (0, 2),  # source node (0) -> intermediate (2)
    (0, 3),  # source node (0) -> intermediate (3)
    (1, 2),  # source node (1) -> intermediate (2)
    (2, 4),  # intermediate (2) -> sink (4)
    (3, 5)   # intermediate (3) -> sink (5)
])
# Node 6 is an orphan node (no edges)

# Create node features: batch_size=2, num_nodes=6, emb_dim=4
node_features = torch.randn(2, 6, 4)

ARGS = {
    'graph': graph,
    'node_features': node_features
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
networkx, torch, torch_geometric — 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
GraphDiffMed Not yet run
unverified (harvested, no recorded run)
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("e8606ace6a79e2e6")
How it ran

no invocation recorded.

encode_text Not yet run
unverified (harvested, no recorded run)
saxenakrati09/GraphDiffMed/src/modules/GraphDiffMed.py
code served (permissive licence) · get_code("6fe5cfad897a3bfd")
How it ran

no invocation recorded.

Also present in other papers' code

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

Repositories linked to this paper

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

Abstract

Recommending safe and effective medication combinations from electronic health records (EHRs) is a core clinical AI problem, yet it remains difficult because patient trajectories are long, noisy, and clinically heterogeneous. Existing methods typically excel at either temporal modeling across visits or pharmacological knowledge integration (e.g., drug-drug interactions, DDIs), but rarely achieve both while robustly suppressing noise. We present GraphDiffMed, a knowledge-constrained medication recommendation framework built on dual-scale Differential Attention v2. Differential attention is applied at both intra-visit and inter-visit levels to filter spurious signals within encounters and across longitudinal history, while pharmacological constraints are incorporated during learning. Experiments on MIMIC-III and ablation studies show that this design consistently improves recommendation quality and ranking over strong baselines while achieving a more favorable safety performance balance. We further find that the strongest-performing configuration uses only demographic auxiliary features under our experimental setting. Overall, GraphDiffMed demonstrates that combining noise-aware attention with pharmacological constraints yields more reliable and clinically meaningful medication recommendation. We open-source our code at https://github.com/saxenakrati09/GraphDiffMed.

For agents

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

get_harvested_code_for_paper("2605.20188")
get_code_for_paper("2605.20188")
have("2605.20188")

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

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

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

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

Connect an agent — have() is free.