Heterogeneous, temporal and program graphs
Model typed and temporal graphs, inspect gated program-graph networks, and evaluate vulnerability and event predictions with leakage-aware protocols.
After this lesson you can
- Describe heterogeneous schemas, metapaths and type-specific message passing.
- Apply temporal cutoffs and memory updates without future leakage.
- Explain gated graph networks and approximations in program graphs.
- Evaluate vulnerability detection with appropriate splits and baselines.
- Interpret measured temporal and code-graph experiments and their limitations.
Before you start
Types, schemas and paths
A transaction network can contain people, accounts, devices and operations. A program can contain functions, instructions, variables and calls. Treating all those objects as identical nodes erases differences affecting the questions and messages we want to exchange.
If relates authors to papers and papers to conferences, counts walks from author to paper and back to author, and counts walks through a conference. A high entry can result from very active authors or conferences; the count is not normalized similarity. Walks can return to the starting author and count the same pair multiple times through different papers.
Metapath choice expresses a hypothesis: sharing a paper is not the same as publishing at the same conference or addressing the same topic. An omitted path can contain useful information and an overly frequent one can produce trivial associations. metapath2vec constructs type-constrained random walks and learns co-occurrence embeddings; it does not automatically update those embeddings when the graph changes.
In the example, Ada and Beto share a paper, but have two walks through conferences and four through topics. Those figures count combinations of papers and do not mean two distinct shared conferences or four distinct topics exist. If the task needs distinct entities, intermediaries must be deduplicated; if it needs proximity weights, define normalization and prevent a very large conference dominating comparison. The matrix audits that choice; it is not a friendship label.
Messages and attention by type
A heterogeneous layer can have a function for each relation , and sum results by destination type :
Person and paper features can have different dimensions, so they are first projected into a compatible space. If all functions are linear and nodes share dimension, the operation relates to R-GCN; shared bases reduce parameters at the cost of restricting possible matrices. Sharing one matrix across all edges is a stronger assumption and can lose their type meanings.
In PyG, HeteroData stores tensors and edges by type; HeteroConv applies specific modules and aggregates by destination. to_hetero generates per-relation copies from a compatible homogeneous model, but does not itself decide which inverse edges exist or how to handle types without messages. Schema and direction must be checked before training.
HAN combines attention among neighbors reachable under a metapath with semantic attention among representations of different metapaths. HGT uses type- and relation-dependent projections and parameters when computing attention and messages. Both can learn different weights, but attention does not prove causality. Building dense metapaths or attending large neighborhoods consumes memory; a simpler layer and comparison with a comparable budget are necessary baselines.
For a destination node, an attention head compares a query projected from its type with keys projected from neighbors, accounting for relation type. After normalizing logits over admitted candidates it combines values transformed by those same categories. Changing the neighbor set also changes the normalization denominator: a high weight may indicate alternatives were missing, not that the edge is essential. Relation functions and new types also require a policy for parameters unseen during training.
Three ways to apply heterogeneous layers in PyG
The local example creates two types with different input dimensions and explicit inverse edges. It compares output shapes of HeteroConv, to_hetero and HGTConv; parameters are initialized separately and values should not match. In HGT each type is projected to a common dimension before attention. This cell has no training or metrics.
import torch
from torch import nn
from torch_geometric.data import HeteroData
from torch_geometric.nn import HeteroConv,SAGEConv,to_hetero,HGTConv
torch.manual_seed(12)
data=HeteroData()
data['autor'].x=torch.tensor([[1.,0.,.2],[0.,1.,.4]])
data['articulo'].x=torch.tensor([[1.,0.,0.,.1],[0.,1.,0.,.2],[0.,0.,1.,.3]])
data['autor','escribe','articulo'].edge_index=torch.tensor([[0,0,1],[0,1,2]])
data['articulo','escrito_por','autor'].edge_index=data['autor','escribe','articulo'].edge_index.flip(0)
conv=HeteroConv({
('autor','escribe','articulo'):SAGEConv((-1,-1),8),
('articulo','escrito_por','autor'):SAGEConv((-1,-1),8),
},aggr='sum')
out=conv(data.x_dict,data.edge_index_dict)
print('HeteroConv:',{key:tuple(value.shape) for key,value in out.items()})
class Base(nn.Module):
def __init__(self): super().__init__(); self.conv=SAGEConv((-1,-1),8)
def forward(self,x,edge_index): return self.conv(x,edge_index).relu()
converted=to_hetero(Base(),data.metadata(),aggr='sum')
auto=converted(data.x_dict,data.edge_index_dict)
print('to_hetero:',{key:tuple(value.shape) for key,value in auto.items()})
project=nn.ModuleDict({'autor':nn.Linear(3,8),'articulo':nn.Linear(4,8)})
hgt=HGTConv(8,8,data.metadata(),heads=2)
z=hgt({k:project[k](v) for k,v in data.x_dict.items()},data.edge_index_dict)
print('HGTConv:',{key:tuple(value.shape) for key,value in z.items()})
assert all(out[k].shape==auto[k].shape==z[k].shape for k in data.node_types)npm run lab and open the connection link.Continuous time and memory
An event represents an interaction at a time and may bring features observed when it occurs. For prediction at , admissible neighbors must come from events strictly earlier than . If several events share a timestamp and have no reliable internal order, score them with the same prior state and update the entire group afterward. Ordering them arbitrarily can reveal one simultaneous event to another.
A temporal graph network in the TGN family maintains memory per node. When an event arrives a function builds messages from prior memories, elapsed time and features; aggregation resolves multiple messages and a cell updates memory. The predictor must run before incorporating the event being predicted. Memory is model state, not a true label or necessarily an explanation.
The temporal cutoff also affects feature construction, negative sampling and state updates during validation and test. Online evaluation can incorporate validation events already observed before test, provided that policy is declared. Resetting memory at each split answers a different question. If different timestamps are grouped in a batch and updated at the end, predictions miss some earlier events in the same batch: this is a conservative approximation, not an exact event-by-event traversal.
To retrieve the most recent neighbors of a node, first filter by and only then sort by time. If clock resolution is seconds, two events with the same timestamp can have unknown physical order: using file order as if it were a temporal measurement introduces an additional assumption. Negative sampling must also state which universe of destinations was eligible at that time and whether it may include links appearing later.
When memory parameters are trained, state calculated with old parameters does not represent exactly the same history under final parameters. Reproducible evaluation can reset state and replay the permitted history with the trained model. For an application unable to retain full history, memory expiration or truncation policy must be the same in evaluation and deployment. In both cases copying a snapshot that already contains test events at validation start would break the cutoff.
A first-seen node presents a cold-start case: its memory can start at zero, but the system still needs to encode its type and available features. A memory table with one position per known node does not itself handle new identities in a service; state must be assigned and the model checked to accept their features. Evaluation must also say whether repeated edges are allowed as candidates and whether the task predicts a new interaction or first appearance of a pair.
The Temporal Graph Benchmark publishes splits, negatives and evaluators for temporal tasks. MRR on a test prefix with official negatives is a reproducible check of that prefix, but is not the full-dataset score. A TGN is not automatically a point process: conditional intensity requires an additional probabilistic definition of times and events.
Programs as graphs and GGNN
An abstract syntax tree (AST) represents language constructs. A control-flow graph describes possible transfers between instructions; a data-flow graph connects definitions and uses under the chosen analysis. Calls, aliases, loops and exceptional paths make them difficult to construct correctly. Connecting statements by textual order or identifiers by name can be a useful approximation, but is not a complete CFG or data-flow analysis.
A gated graph neural network (GGNN) aggregates messages and updates each state with a GRU-like cell. Gates can retain information across steps without guaranteeing recovery of an arbitrarily long dependency. Typed edges can have different transformations; readout can focus on a node or summarize the entire function.
In a simple variant, and . The update gate mixes the previous state with a new candidate, while the reset gate participates in constructing that candidate. Specific formulas and bias positions vary across implementations. Using a gate does not make the representation an execution trace or prove the model follows a relevant path.
Here the synthetic label asks exclusively whether the pointer can be null and the displayed guard is missing. It excludes aliases, concurrency and other preconditions. The head trained on the final step; applying it to earlier states is for inspection, not causal explanation. Removing the control edge changes information available to the read node, but an ablation score depends on how the model was trained.
Program graphs can combine AST, control, data and calls. Devign uses code graphs to classify functions; other representations and classifiers involve different tradeoffs. A graph from an erroneous or truncated parser may omit the relevant instruction. Before comparing models, measure how many examples were discarded or truncated and whether those choices change between splits.
In the illustrated function, a guard returning on a null pointer separates that branch from the later read. A textual-order edge between statements does not by itself represent that branch. For use-after-free, freeing and use must be linked to the correct object, including potential aliases; for an SQL query, data must be traced from sources to sensitive operations. A detector based only on identical names can fail when a variable is copied or renamed.
Evaluation resembling intended use
Vulnerability detection is sensitive to duplicates, near clones, shared projects and uncertain labels. Randomly splitting related functions can allow memorizing project-specific patterns. A project-based test asks a harder transfer question, but does not itself eliminate cross-project clones, temporal differences or label errors. Chakraborty et al. document duplication, distribution and artifact problems; a clean test needs its construction described.
Accuracy alone is insufficient when vulnerabilities are rare. Precision, recall and area under the precision-recall curve help interpret errors; selected threshold and prevalence matter. A bag-of-tokens baseline trained only on training data reveals what can be achieved without graph structure. A false negative may leave a problem unreviewed and a false positive consumes analysis time; neither is explained by an aggregate score.
A normalized-code hash detects only equality under the chosen normalization. It does not necessarily discover renamed equivalent functions, copies with small edits or related patch families. Grouping commits prevents splitting functions from one change across training and validation, but does not prove two commits from one project are independent. Compare with a baseline receiving similar input and record whether one model saw more code lines than another.
Labels inherited from security changes do not always identify each function’s specific mechanism. A positive function may share a commit with the fix and an unmarked function may contain an as-yet unknown problem. Thus comparison should retain label definitions and allow individual examples to be reviewed. A mean precision increase on a small sample can depend on composition; it is not a measured incident reduction on another project.
Lab from scratch
Preparation includes an independent copy of the preceding lesson’s message-passing module, with SHA-256 722eb1df61bde98ee9a7770777bd4ab4646c8094144f4165d9e979f468252587. The cell implements type-specific transformations and an explicit GRU update, groups simultaneous events before updating memory and checks equivariance under permutation. This GRU variant applies reset to state before its transformation; PyTorch uses another algebraic arrangement of that term.
Python graphs are built with ast: tree edges, lexical order between statements and successive occurrences of the same name. The latter two are approximations and do not calculate real control paths or reaching definitions. The GGNN has fixed random weights and only its linear head is trained on eight synthetic functions; two similar synthetic functions are held out for test. The label asks exclusively whether input None can reach p[0] without the specified guard. The score is not an evaluation of real vulnerabilities.
import ast
from collections import defaultdict
import numpy as np
rng=np.random.default_rng(17); d=8
W=rng.normal(0,.15,(3,d,d))
def hetero(x,edge_index,edge_type):
src,dst=edge_index
messages=np.einsum('ei,eij->ej',x[src],W[edge_type])
return scatter_sum(messages,dst,len(x))
params={name:rng.normal(0,.12,(d,d)) for name in ('Wr','Ur','Wz','Uz','Wn','Un')}
def sigmoid(x): return 1/(1+np.exp(-np.clip(x,-30,30)))
def gru(message,state):
r=sigmoid(message@params['Wr']+state@params['Ur'])
z=sigmoid(message@params['Wz']+state@params['Uz'])
candidate=np.tanh(message@params['Wn']+(r*state)@params['Un'])
return (1-z)*candidate+z*state
def ggnn(x,edges,types,steps=3):
h=x.copy()
for _ in range(steps): h=gru(hetero(h,edges,types),h)
return h
def temporal_neighbors(events,node,t,k):
if k<0: raise ValueError('k debe ser no negativo')
candidates=[(i,e) for i,e in enumerate(events) if e[2]<t and node in e[:2]]
candidates.sort(key=lambda pair:(-pair[1][2],pair[0]))
return [e for _,e in candidates[:k]]
def temporal_memory(events):
memory=np.zeros((4,d)); last=np.zeros(4)
ordered=sorted(events,key=lambda e:e[2]); start=0
while start<len(ordered):
end=start+1
while end<len(ordered) and ordered[end][2]==ordered[start][2]: end+=1
before=memory.copy(); messages=defaultdict(list)
for u,v,t in ordered[start:end]:
messages[u].append(.5*(before[u]+before[v])+np.full(d,(t-last[u])*.1))
messages[v].append(.5*(before[v]+before[u])+np.full(d,(t-last[v])*.1))
for node,items in messages.items():
memory[node]=gru(np.mean(items,axis=0),before[node]); last[node]=ordered[start][2]
start=end
return memory
events=[(0,1,1),(0,2,2),(0,3,2),(1,2,3)]
assert temporal_neighbors(events,0,2,5)==[(0,1,1)]
assert np.allclose(temporal_memory(events),temporal_memory([events[0],events[2],events[1],events[3]]))
print('vecinos anteriores estrictos:',temporal_neighbors(events,0,2,5))
print('eventos simultáneos son invariantes al orden:',True)
KINDS=[ast.FunctionDef,ast.If,ast.Return,ast.Compare,ast.Constant,ast.Subscript,ast.Name]
def program_graph(code):
tree=ast.parse(code); nodes=list(ast.walk(tree)); ids={id(node):i for i,node in enumerate(nodes)}
x=np.zeros((len(nodes),d))
for i,node in enumerate(nodes):
kind=next((j for j,cls in enumerate(KINDS) if isinstance(node,cls)),7); x[i,kind]=1
edge=[]
for node in nodes:
for child in ast.iter_child_nodes(node): edge.append((ids[id(node)],ids[id(child)],0))
# Orden léxico de sentencias: aproximación, no CFG completo.
statements=sorted((getattr(node,'lineno',0),getattr(node,'col_offset',0),i) for i,node in enumerate(nodes) if isinstance(node,ast.stmt))
for (_,_,a),(_,_,b) in zip(statements,statements[1:]): edge.append((a,b,1))
# Igualdad léxica de nombres: no calcula definiciones alcanzables ni alias.
names=defaultdict(list)
for i,node in enumerate(nodes):
if isinstance(node,ast.Name): names[node.id].append((node.lineno,node.col_offset,i))
for group in names.values():
group.sort()
for (_,_,a),(_,_,b) in zip(group,group[1:]): edge.append((a,b,2))
e=np.array([(u,v) for u,v,_ in edge],dtype=int).reshape(-1,2).T
types=np.array([r for _,_,r in edge],dtype=int)
return x,e,types
def example(index,guard):
# La etiqueta solo pregunta por una entrada None y una guarda explícita.
prefix=f'def f{index}(p):\n'
return prefix+(' if p is None:\n return 0\n' if guard else '')+' return p[0]\n'
examples=[(example(i,i%2==0),int(i%2!=0)) for i in range(10)]
embeddings=[]
for code,label in examples:
x,e,t=program_graph(code); h=ggnn(x,e,t); embeddings.append(h.mean(axis=0))
X=np.stack(embeddings); y=np.array([label for _,label in examples]); train=np.arange(8); test=np.arange(8,10)
weights=np.zeros(d); bias=0.
for _ in range(500):
p=sigmoid(X[train]@weights+bias); delta=(p-y[train])/len(train)
weights-=.5*(X[train].T@delta); bias-=.5*delta.sum()
print('clasificador sintético, exactitud en 2 funciones de test:',float(np.mean((sigmoid(X[test]@weights+bias)>=.5)==y[test])))
x,e,t=program_graph(examples[0][0]); permutation=rng.permutation(len(x)); inverse=np.argsort(permutation)
assert np.allclose(hetero(x[permutation],inverse[e],t),hetero(x,e,t)[permutation])
print('capa heterogénea equivariante al reordenar nodos:',True)Reproduce the function figure
The following local cell trains the figure’s exact model on four synthetic cases and saves per-step scores and norms for three edge variants. There is no test split for that viewer. The deliberately simple size and design allow propagation inspection, not measurement of real vulnerability detection.
import json
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(2); torch.manual_seed(29)
d=6
class ToyGGNN(nn.Module):
def __init__(self):
super().__init__(); self.input=nn.Linear(6,d); self.relation=nn.Parameter(torch.randn(3,d,d)*.1)
self.gru=nn.GRUCell(d,d); self.head=nn.Linear(d,1)
def forward(self,features,edge_index,edge_type,return_all=False):
state=torch.tanh(self.input(features)); steps=[state]
for _ in range(3):
src,dst=edge_index
msg=torch.einsum('ei,eij->ej',state[src],self.relation[edge_type])
agg=torch.zeros_like(state).index_add(0,dst,msg)
state=self.gru(agg,state); steps.append(state)
scores=[self.head(s[2::4]).flatten() for s in steps]
return (scores,steps) if return_all else scores[-1]
def graph(nullable,guard):
x=torch.tensor([[1,nullable,0,0,0,0], [0,0,1,guard,0,0], [0,0,0,0,1,0], [0,0,0,0,0,1]],dtype=torch.float)
e=torch.tensor([[0,1,2],[2,2,3]],dtype=torch.long); types=torch.tensor([0,1,2])
return x,e,types
features=[]; edges=[]; types=[]; labels=[]
for k,(nullable,guard) in enumerate([(0,0),(0,1),(1,0),(1,1)]):
x,e,t=graph(nullable,guard); features.append(x); edges.append(e+4*k); types.append(t); labels.append(float(nullable and not guard))
features=torch.cat(features); edges=torch.cat(edges,dim=1); types=torch.cat(types); labels=torch.tensor(labels)
model=ToyGGNN(); opt=torch.optim.Adam(model.parameters(),lr=.02)
for epoch in range(400):
loss=F.binary_cross_entropy_with_logits(model(features,edges,types),labels)
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
train_prob=torch.sigmoid(model(features,edges,types)).tolist()
outputs={}
for nullable,guard in [(0,0),(0,1),(1,0),(1,1)]:
x,e,t=graph(nullable,guard)
for mode in ('all','no_data','no_control'):
keep=torch.ones(len(t),dtype=torch.bool)
if mode=='no_data': keep &= t!=0
if mode=='no_control': keep &= t!=1
scores,states=model(x,e[:,keep],t[keep],return_all=True)
outputs[f'{nullable}{guard}-{mode}']={'prob':[float(torch.sigmoid(v).item()) for v in scores],
'norms':[[float(v) for v in torch.linalg.vector_norm(state,dim=1)] for state in states]}
print('train probability',train_prob,'loss',float(loss.detach()))
Path('toy_ggnn.json').write_text(json.dumps(outputs,indent=2),encoding='utf8')npm run lab and open the connection link.Local experiment on Devign functions
The cell obtains the function file from the Devign publication, checks its SHA-256 and works with the two published projects: FFmpeg and QEMU. It groups code after whitespace normalization, removes groups with contradictory labels, discards groups shared across projects and retains one function per group. Whitespace normalization can group different texts, for example within literals; it also does not detect near clones. This is one limited deduplication, not a certification of independence.
In the file of 27 318 records, this run’s audit excluded 152 records from contradictory groups and three additional duplicates; it found no normalized duplicates across projects. Training and validation split FFmpeg commits; QEMU is reserved entirely for test. With only two projects, validation is not a third independent project. Labels come from the corpus and may be imperfect; class zero should not be interpreted as proof of safety.
The Tree-sitter C parser discards functions with syntax errors and truncates to 96 AST nodes. Lexical statement order and consecutive occurrences of an identifier are approximations, not a full CFG or data-flow analysis. A GGNN with relation matrices and an HGT with types syntax and identifier are trained; a TF-IDF and logistic regression baseline uses full text. Inputs have unequal budgets: the baseline sees full text and graphs may be truncated. A fixed 0.5 threshold is used and hyperparameters are not selected on validation.
In a three-epoch CUDA run, 256 train, 64 validation and 64 test functions were selected; 67, 13 and 20 respectively were discarded for parsing errors and 206, 49 and 33 of those selected were truncated. Test has 30 positive labels. Precision-recall average precision was 0.5394 for tokens, 0.5873 for GGNN and 0.5317 for HGT; at threshold 0.5 precision/recall pairs were 0.5833/0.2333, 0.6364/0.2333 and 0/0. These figures come from one sample and seed, not conclusive results or production estimates. Validation is reserved but not used to select parameters.
You need PyTorch, PyG, NumPy, scikit-learn and tree-sitter==0.25.2 with tree-sitter-c==0.24.1; first download is about 61 MB. DEVIGN_TRAIN, DEVIGN_EVAL and DEVIGN_EPOCHS can enlarge the experiment; changing them changes cost and does not eliminate label or representation limitations.
from pathlib import Path
import hashlib, urllib.request
url='https://drive.google.com/uc?export=download&id=1x6hoF7G-tSYxg8AFybggypLZgMGDNHfF'
req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0'})
data=urllib.request.urlopen(req,timeout=180).read()
path=Path('dataset/devign/function.json'); path.parent.mkdir(parents=True,exist_ok=True)
assert hashlib.sha256(data).hexdigest()=='0a3b2d561dc6280e53795886ede727d0045c016d083905ba3e9ce384a7eab246'
path.write_bytes(data)
print('Devign function.json bytes:',len(data),'sha256:',hashlib.sha256(data).hexdigest())
import hashlib,json,re
from collections import Counter,defaultdict
from pathlib import Path
from sklearn.model_selection import GroupShuffleSplit
path=Path('dataset/devign/function.json')
assert hashlib.sha256(path.read_bytes()).hexdigest()=='0a3b2d561dc6280e53795886ede727d0045c016d083905ba3e9ce384a7eab246'
items=json.loads(path.read_text(encoding='utf8')); grouped=defaultdict(list)
for x in items:
normalized=re.sub(r'\s+',' ',x['func']).strip()
grouped[hashlib.sha256(normalized.encode()).hexdigest()].append(x)
clean=[]; conflicts=cross=duplicate=0
for group in grouped.values():
if len({x['target'] for x in group})>1: conflicts+=len(group); continue
if len({x['project'].lower() for x in group})>1: cross+=len(group); continue
duplicate+=len(group)-1
clean.append(sorted(group,key=lambda x:(x['project'],x['commit_id']))[0])
train_project=[x for x in clean if x['project'].lower()=='ffmpeg']
test=[x for x in clean if x['project'].lower()=='qemu']
splits=GroupShuffleSplit(n_splits=1,test_size=.2,random_state=29)
train_idx,val_idx=next(splits.split(train_project,groups=[x['commit_id'] for x in train_project]))
train=[train_project[i] for i in train_idx]; valid=[train_project[i] for i in val_idx]
assert not ({x['commit_id'] for x in train}&{x['commit_id'] for x in valid})
print('raw',len(items),'conflictos excluidos',conflicts,'compartidos entre proyectos excluidos',cross,'duplicados adicionales excluidos',duplicate)
for name,subset in [('train FFmpeg',train),('val FFmpeg',valid),('test QEMU',test)]:
print(name,'funciones',len(subset),'labels',dict(Counter(x['target'] for x in subset)),'commits',len({x['commit_id'] for x in subset}))
from collections import deque
import hashlib
import numpy as np
import torch
from torch_geometric.data import Data,HeteroData
from tree_sitter import Language,Parser
import tree_sitter_c
PARSER=Parser(Language(tree_sitter_c.language()))
TYPES=('syntax','identifier')
SCHEMA=[('syntax','ast','syntax'),('syntax','ast','identifier'),
('syntax','ast_inv','syntax'),('identifier','ast_inv','syntax'),
('syntax','seq','syntax'),('identifier','same','identifier')]
RELATIONS={'ast':0,'ast_inv':1,'seq':2,'same':3}
def hashed_feature(node,source):
out=np.zeros(18,dtype=np.float32)
out[0 if node.type!='identifier' else 1]=1
parts=['node:'+node.type]
if node.type=='identifier': parts.append('id:'+source[node.start_byte:node.end_byte].decode('utf8',errors='replace'))
for part in parts:
digest=hashlib.blake2b(part.encode('utf8'),digest_size=8).digest()
j=int.from_bytes(digest[:4],'little')%16; sign=1 if digest[4]&1 else -1
out[2+j]+=sign
return out
def graph_from_c(code,label,max_nodes=96):
source=code.encode('utf8'); root=PARSER.parse(source).root_node
if root.has_error: return None,'parse_error'
nodes=[]; queue=deque([root])
while queue and len(nodes)<max_nodes:
node=queue.popleft(); nodes.append(node); queue.extend(node.named_children)
truncated=bool(queue)
if len(nodes)<2: return None,'too_small'
index={node.id:i for i,node in enumerate(nodes)}
kinds=['identifier' if node.type=='identifier' else 'syntax' for node in nodes]
if 'identifier' not in kinds: return None,'no_identifier'
edge=[]
for i,node in enumerate(nodes):
for child in node.named_children:
if child.id in index:
j=index[child.id]; edge.append((i,j,'ast')); edge.append((j,i,'ast_inv'))
# Adyacencia léxica de sentencias, no un CFG semántico completo.
statements=sorted((node.start_byte,i) for i,node in enumerate(nodes)
if node.type.endswith('_statement') or node.type=='declaration')
for (_,u),(_,v) in zip(statements,statements[1:]): edge.append((u,v,'seq'))
# Ocurrencias sucesivas del mismo identificador, no análisis de definiciones alcanzables.
groups={}
for node,i in sorted(((node,i) for i,node in enumerate(nodes) if node.type=='identifier'),key=lambda p:p[0].start_byte):
token=source[node.start_byte:node.end_byte]
if token in groups: edge.append((groups[token],i,'same'))
groups[token]=i
x=np.stack([hashed_feature(node,source) for node in nodes])
e=np.array([[u,v] for u,v,_ in edge],dtype=np.int64).reshape(-1,2).T
edge_types=np.array([RELATIONS[r] for _,_,r in edge],dtype=np.int64)
homo=Data(x=torch.tensor(x),edge_index=torch.tensor(e),edge_type=torch.tensor(edge_types),y=torch.tensor([label],dtype=torch.long))
hetero=HeteroData(); local={}; counts={kind:0 for kind in TYPES}
for i,kind in enumerate(kinds): local[i]=counts[kind]; counts[kind]+=1
for kind in TYPES: hetero[kind].x=torch.tensor(x[[i for i,k in enumerate(kinds) if k==kind]])
for key in SCHEMA:
src,rel,dst=key
pairs=[(local[u],local[v]) for u,v,r in edge if r==rel and kinds[u]==src and kinds[v]==dst]
hetero[key].edge_index=torch.tensor(np.asarray(pairs,dtype=np.int64).reshape(-1,2).T)
hetero.y=torch.tensor([label],dtype=torch.long)
return (homo,hetero,truncated),None
import json, os, time
from collections import Counter
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score,precision_score,recall_score
from torch_geometric.loader import DataLoader
from torch_geometric.nn import HGTConv,global_mean_pool
torch.set_num_threads(2); torch.manual_seed(31)
rng=np.random.default_rng(31)
size=int(os.environ.get('DEVIGN_TRAIN','256')); eval_size=int(os.environ.get('DEVIGN_EVAL','64'))
epochs=int(os.environ.get('DEVIGN_EPOCHS','3')); device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def select(rows,limit,name):
selected=[]; rejected=Counter(); truncated=0
for ix in rng.permutation(len(rows)):
row=rows[ix]; result,error=graph_from_c(row['func'],row['target'])
if error: rejected[error]+=1; continue
homo,hetero,cut=result; truncated+=int(cut); selected.append((row,homo,hetero))
if len(selected)==limit: break
labels=Counter(row['target'] for row,_,_ in selected)
print(name,'seleccionados',len(selected),'clases',dict(labels),'rechazos',dict(rejected),'truncados',truncated,flush=True)
if len(labels)<2 or len(selected)<limit: raise RuntimeError('muestra insuficiente o con una sola clase')
return selected
train_s=select(train,size,'train FFmpeg'); valid_s=select(valid,eval_size,'valid FFmpeg'); test_s=select(test,eval_size,'test QEMU')
def metrics(y,p):
pred=np.asarray(p)>=.5
return {'auprc':float(average_precision_score(y,p)),
'precision':float(precision_score(y,pred,zero_division=0)),
'recall':float(recall_score(y,pred,zero_division=0))}
ytrain=np.array([r['target'] for r,_,_ in train_s]); ytest=np.array([r['target'] for r,_,_ in test_s])
vector=TfidfVectorizer(max_features=4000,token_pattern=r'[A-Za-z_]\w+|\d+',lowercase=False)
xtrain=vector.fit_transform([r['func'] for r,_,_ in train_s]); xtest=vector.transform([r['func'] for r,_,_ in test_s])
baseline=LogisticRegression(max_iter=300,random_state=31).fit(xtrain,ytrain)
results=[{'model':'bolsa de tokens',**metrics(ytest,baseline.predict_proba(xtest)[:,1])}]
class GGNN(nn.Module):
def __init__(self):
super().__init__(); self.input=nn.Linear(18,32); self.weights=nn.Parameter(torch.randn(4,32,32)*.05)
self.gru=nn.GRUCell(32,32); self.head=nn.Linear(32,1)
def forward(self,g):
h=torch.tanh(self.input(g.x)); src,dst=g.edge_index
for _ in range(3):
msg=torch.einsum('ei,eij->ej',h[src],self.weights[g.edge_type])
agg=torch.zeros_like(h).index_add(0,dst,msg); h=self.gru(agg,h)
return self.head(global_mean_pool(h,g.batch)).flatten()
class HGT(nn.Module):
def __init__(self):
super().__init__(); self.input=nn.ModuleDict({kind:nn.Linear(18,32) for kind in TYPES})
self.conv=HGTConv(32,32,metadata=(list(TYPES),SCHEMA),heads=2)
self.head=nn.Linear(64,1)
def forward(self,g):
x={kind:F.relu(self.input[kind](g[kind].x)) for kind in TYPES}
updated=self.conv(x,g.edge_index_dict)
pooled=[global_mean_pool(F.relu(updated.get(kind,x[kind])),g[kind].batch,size=g.num_graphs) for kind in TYPES]
return self.head(torch.cat(pooled,dim=1)).flatten()
for name,model,kind in [('GGNN',GGNN(),1),('HGT',HGT(),2)]:
model=model.to(device); optimizer=torch.optim.Adam(model.parameters(),lr=.003)
loader=DataLoader([x[kind] for x in train_s],batch_size=16,shuffle=True)
start=time.perf_counter()
for epoch in range(epochs):
model.train()
for batch in loader:
batch=batch.to(device); logits=model(batch); labels=batch.y.float().view(-1)
loss=F.binary_cross_entropy_with_logits(logits,labels)
optimizer.zero_grad(); loss.backward(); optimizer.step()
model.eval(); y=[]; p=[]
with torch.no_grad():
for batch in DataLoader([x[kind] for x in test_s],batch_size=16,shuffle=False):
batch=batch.to(device); y.extend(batch.y.cpu().view(-1).tolist()); p.extend(torch.sigmoid(model(batch)).cpu().tolist())
row={'model':name,**metrics(y,p),'seconds':round(time.perf_counter()-start,2),'device':str(device)}
results.append(row); print(json.dumps(row),flush=True)
del model,optimizer
if device.type=='cuda': torch.cuda.empty_cache()
print(json.dumps(results,indent=2),flush=True)
Path('dataset/devign/devign_results.json').write_text(json.dumps(results,indent=2),encoding='utf8')npm run lab and open the connection link.TGN on the Temporal Graph Benchmark
The following experiment uses tgbl-wiki version 2, a temporal editing network, and TGB’s published negatives. The verified official file has SHA-256 1b6c756b4dc0bac9d1f97218467949472daf5b1eebe497f38721493682fdd130; about 41 MB are downloaded and extraction requires approximately 1 GB more. Dataset version 2 contains 157 474 events and 9227 nodes: 110 232 training, 23 621 validation and 23 621 test events. In this download split time boundaries do not share timestamps; ties occur within them.
TGN memory and a link head train on the first 2048 training events, one epoch and uniform destination negatives that may include true facts. After training, memory is reset and rebuilt with all training events; then a validation prefix is evaluated, remaining validation events incorporated and a test prefix evaluated. Events with the same timestamp are scored together before updating memory. To accelerate rebuilding, batches can include up to 1024 events at different times and update at the end: some earlier interactions inside the batch are omitted, but the future is not observed. This is a conservative approximation, not the complete TGN implementation with neighbor sampling.
In a CUDA run 64 validation and 64 test events were evaluated, with 999 official negatives per event. The TGB evaluator returned MRR 0.02422 and 0.03547 respectively. Results are prefixes, one seed and short training; they are not official full-benchmark scores. The program groups ties, uses package negatives and evaluator, and records their quantities. TGN_TRAIN_EVENTS and TGN_EVAL_EVENTS enlarge prefixes; TGN_REPLAY_EVENTS=0 rebuilds full history and a positive value limits it for debugging, changing available information.
Install PyTorch, PyG and py-tgb==2.3.0 locally. That version internally prepends its package directory to the path parameter, so the cell adjusts that variable only in the process to save data in the chosen directory. Negatives load from verified official dataset package files; because they are pickle files they must come from that trusted source.
from pathlib import Path
import hashlib, urllib.request
url='https://object-arbutus.alliancecan.ca/swift/v1/14c95234f6cd4a21a47deafe20cce2a7/tgb/tgbl-wiki-v2.zip'
data=urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':'OryonLearn'}),timeout=180).read()
path=Path('dataset/oryon-tgb-wiki-v2/tgbl-wiki-v2.zip'); path.parent.mkdir(parents=True,exist_ok=True)
assert hashlib.sha256(data).hexdigest()=='1b6c756b4dc0bac9d1f97218467949472daf5b1eebe497f38721493682fdd130'
path.write_bytes(data)
print('tgbl-wiki-v2 bytes:',len(data),'sha256:',hashlib.sha256(data).hexdigest())
import hashlib, zipfile
from pathlib import Path
import numpy as np
import tgb.linkproppred.dataset as dataset_module
from tgb.linkproppred.dataset_pyg import PyGLinkPropPredDataset
archive=Path('dataset/oryon-tgb-wiki-v2/tgbl-wiki-v2.zip')
assert hashlib.sha256(archive.read_bytes()).hexdigest()=='1b6c756b4dc0bac9d1f97218467949472daf5b1eebe497f38721493682fdd130'
root=Path('dataset/oryon-tgb-wiki-v2').resolve()
destination=(root/'tgbl_wiki').resolve(); destination.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(archive) as z:
for member in z.infolist(): (destination/member.filename).resolve().relative_to(destination)
z.extractall(destination)
dataset_module.PROJ_DIR='' # 2.3.0 concatena PROJ_DIR con root incluso si root es absoluto
dataset=PyGLinkPropPredDataset(name='tgbl-wiki',root=str(root),download=False)
data=dataset.get_TemporalData()
print('eventos',len(data.src),'nodos',dataset.num_nodes,'features',data.msg.shape,
'splits',int(dataset.train_mask.sum()),int(dataset.val_mask.sum()),int(dataset.test_mask.sum()))
for name,mask in [('train',dataset.train_mask),('val',dataset.val_mask),('test',dataset.test_mask)]:
t=data.t[mask].numpy(); print(name,'t mínimo',int(t.min()),'máximo',int(t.max()),'empates consecutivos',int(np.sum(t[1:]==t[:-1])))
import json, os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.nn import TGNMemory
from torch_geometric.nn.models.tgn import IdentityMessage,MeanAggregator
import tgb.linkproppred.dataset as dataset_module
from tgb.linkproppred.dataset_pyg import PyGLinkPropPredDataset
from tgb.linkproppred.evaluate import Evaluator
torch.set_num_threads(2); torch.manual_seed(37)
dataset_module.PROJ_DIR=''
root=os.environ.get('TGB_ROOT',str(Path('dataset/oryon-tgb-wiki-v2').resolve()))
dataset=PyGLinkPropPredDataset(name='tgbl-wiki',root=root,download=False)
data=dataset.get_TemporalData(); assert bool(torch.all(data.t[1:]>=data.t[:-1]))
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
memory=TGNMemory(dataset.num_nodes,data.msg.size(-1),16,8,IdentityMessage(data.msg.size(-1),16,8),MeanAggregator()).to(device)
head=nn.Sequential(nn.Linear(32,32),nn.ReLU(),nn.Linear(32,1)).to(device)
opt=torch.optim.Adam(list(memory.parameters())+list(head.parameters()),lr=.001)
assoc=torch.empty(dataset.num_nodes,dtype=torch.long,device=device)
train_idx=dataset.train_mask.nonzero().view(-1).numpy(); val_idx=dataset.val_mask.nonzero().view(-1).numpy(); test_idx=dataset.test_mask.nonzero().view(-1).numpy()
def batches(indices,limit):
# No parte eventos simultáneos: una predicción solo ve lotes anteriores.
times=data.t[indices].numpy(); begin=0
while begin<len(indices):
end=min(begin+limit,len(indices))
while end<len(indices) and times[end]==times[end-1]: end+=1
yield indices[begin:end]
begin=end
def prefix_complete(indices,limit):
if limit<1: raise ValueError('El límite debe ser positivo')
end=min(limit,len(indices))
while end<len(indices) and data.t[indices[end]]==data.t[indices[end-1]]: end+=1
return indices[:end],indices[end:]
def event_batch(indices):
i=torch.tensor(indices,dtype=torch.long)
return data.src[i].to(device),data.dst[i].to(device),data.t[i].to(device),data.msg[i].to(device)
destinations=torch.unique(data.dst[torch.tensor(train_idx)]).to(device)
prefix,_=prefix_complete(train_idx,int(os.environ.get('TGN_TRAIN_EVENTS','2048')))
start=time.perf_counter(); memory.train(); memory.reset_state(); head.train()
for ids in batches(prefix,128):
src,dst,t,msg=event_batch(ids)
negative=destinations[torch.randint(len(destinations),(len(dst),),device=device)]
n_id=torch.cat([src,dst,negative]).unique(); z,_=memory(n_id); assoc[n_id]=torch.arange(len(n_id),device=device)
pos=head(torch.cat([z[assoc[src]],z[assoc[dst]]],dim=1)).view(-1)
neg=head(torch.cat([z[assoc[src]],z[assoc[negative]]],dim=1)).view(-1)
loss=F.softplus(-pos).mean()+F.softplus(neg).mean()
opt.zero_grad(); memory.update_state(src,dst,t,msg); loss.backward(); opt.step(); memory.detach()
# Reconstruye memoria con los parámetros ya entrenados: no reutiliza estados obsoletos.
memory.eval(); head.eval(); memory.reset_state()
replay_limit=int(os.environ.get('TGN_REPLAY_EVENTS','0')) # 0: todo el historial
train_replay=train_idx if replay_limit==0 else prefix_complete(train_idx,replay_limit)[0]
val_replay_count=0
with torch.no_grad():
for ids in batches(train_replay,1024):
src,dst,t,msg=event_batch(ids); memory.update_state(src,dst,t,msg)
evaluator=Evaluator(name='tgbl-wiki')
results={}
for split,indices in [('val',val_idx),('test',test_idx)]:
if split=='val': dataset.load_val_ns()
else: dataset.load_test_ns()
chosen,remaining=prefix_complete(indices,int(os.environ.get('TGN_EVAL_EVENTS','64')))
reciprocal=[]; negative_counts=[]
with torch.no_grad():
# Solo eventos con igual timestamp se evalúan juntos; no se ven entre sí.
for ids in batches(chosen,1):
src,dst,t,msg=event_batch(ids)
negative_lists=dataset.negative_sampler.query_batch(src,dst,t,split_mode=split)
for j,negatives in enumerate(negative_lists):
neg=torch.tensor(negatives,dtype=torch.long,device=device)
n_id=torch.cat([src[j:j+1],dst[j:j+1],neg]).unique()
z,_=memory(n_id); assoc[n_id]=torch.arange(len(n_id),device=device)
source=z[assoc[src[j]]].expand(len(neg)+1,-1)
targets=z[assoc[torch.cat([dst[j:j+1],neg])]]
scores=head(torch.cat([source,targets],dim=1)).view(-1)
result=evaluator.eval({'y_pred_pos':scores[:1], 'y_pred_neg':scores[1:].reshape(1,-1), 'eval_metric':['mrr']})
reciprocal.append(float(result['mrr'])); negative_counts.append(len(negatives))
memory.update_state(src,dst,t,msg)
if split=='val':
replay_rest=remaining if replay_limit==0 or len(remaining)==0 else prefix_complete(remaining,min(replay_limit,len(remaining)))[0]
val_replay_count=len(chosen)+len(replay_rest)
for ids in batches(replay_rest,1024):
src,dst,t,msg=event_batch(ids); memory.update_state(src,dst,t,msg)
results[split]={'events':len(chosen),'mrr':float(np.mean(reciprocal)),
'neg_min':min(negative_counts),'neg_max':max(negative_counts)}
print(split,results[split],flush=True)
if device.type=='cuda': torch.cuda.synchronize()
results['scope']={'train_prefix_events':len(prefix),'train_replayed':len(train_replay),
'val_replayed':val_replay_count,'device':str(device),'seconds':round(time.perf_counter()-start,2)}
print(results['scope'],flush=True)
Path('dataset/oryon-tgb-wiki-v2/tgn_results.json').write_text(json.dumps(results,indent=2),encoding='utf8')npm run lab and open the connection link.Exercises
Step 1 of 3. What happens to each edge's type?
def temporal_neighbors(events, node, t, k):
pass