Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_SOFIE_GNN.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_ml
3## \notebook -nodraw
4##
5## Tutorial showing inference of a Graph Neural Network with SOFIE.
6##
7## A graph network model following DeepMind's Encode-Process-Decode architecture
8## (see arXiv:1806.01261) is defined in PyTorch and exported to ONNX. The ONNX
9## models are then parsed with the SOFIE ONNX parser, C++ inference code is
10## generated and compiled, and its output is validated against PyTorch.
11##
12## \macro_code
13##
14## \author
15
16import time
17
18import numpy as np
19import ROOT
20import torch
21import torch.nn as nn
22
23# defining graph properties
24num_nodes = 5
25num_edges = 20
26snd = np.array([1, 2, 3, 4, 2, 3, 4, 3, 4, 4, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3], dtype="int64")
27rec = np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 1, 2, 3, 4, 2, 3, 4, 3, 4, 4], dtype="int64")
28node_size = 4
29edge_size = 4
30global_size = 1
31LATENT_SIZE = 100
32NUM_LAYERS = 4
33processing_steps = 5
34numevts = 40
35
38
39
40# method for returning dictionary of graph data
41def get_graph_data_dict(num_nodes, num_edges, NODE_FEATURE_SIZE=2, EDGE_FEATURE_SIZE=2, GLOBAL_FEATURE_SIZE=1):
42 return {
43 "globals": 10 * np.random.rand(1, GLOBAL_FEATURE_SIZE).astype(np.float32) - 5.0,
44 "nodes": 10 * np.random.rand(num_nodes, NODE_FEATURE_SIZE).astype(np.float32) - 5.0,
45 "edges": 10 * np.random.rand(num_edges, EDGE_FEATURE_SIZE).astype(np.float32) - 5.0,
46 "senders": snd,
47 "receivers": rec,
48 }
49
50
51# method to instantiate an MLP model to be added in the GNN
52# (a stack of Linear+ReLU layers, with a final LayerNorm for the core network)
53def make_mlp_model(num_inputs, with_layer_norm=False):
54 layers = []
55 for _ in range(NUM_LAYERS):
56 layers += [nn.Linear(num_inputs, LATENT_SIZE), nn.ReLU()]
57 num_inputs = LATENT_SIZE
58 if with_layer_norm:
59 layers.append(nn.LayerNorm(LATENT_SIZE))
60 return nn.Sequential(*layers)
61
62
63# module applying independent MLPs to the node, edge and global features
65 def __init__(self, num_node_inputs, num_edge_inputs, num_global_inputs):
66 super().__init__()
67 self.node_fn = make_mlp_model(num_node_inputs)
68 self.edge_fn = make_mlp_model(num_edge_inputs)
69 self.global_fn = make_mlp_model(num_global_inputs)
70
71 def forward(self, node_data, edge_data, global_data):
72 return self.node_fn(node_data), self.edge_fn(edge_data), self.global_fn(global_data)
73
74
75# module implementing a full graph-network block (see arXiv:1806.01261):
76# - edge update from [edge, receiver node, sender node, global]
77# - node update from [sum of received edges, node, global]
78# - global update from [sum of edges, sum of nodes, global]
80 def __init__(self, num_node_inputs, num_edge_inputs, num_global_inputs):
81 super().__init__()
82 self.edge_fn = make_mlp_model(num_edge_inputs + 2 * num_node_inputs + num_global_inputs, True)
83 self.node_fn = make_mlp_model(LATENT_SIZE + num_node_inputs + num_global_inputs, True)
84 self.global_fn = make_mlp_model(2 * LATENT_SIZE + num_global_inputs, True)
85
86 def forward(self, node_data, edge_data, global_data, receivers, senders):
87 n_nodes = node_data.shape[0]
88 n_edges = edge_data.shape[0]
89 edge_input = torch.cat(
90 [edge_data, node_data[receivers], node_data[senders], global_data.expand(n_edges, -1)], dim=1
91 )
92 edge_output = self.edge_fn(edge_input)
93 # aggregate the updated edge data per receiving node
94 received_edges = torch.zeros(n_nodes, edge_output.shape[1]).scatter_add(
95 0, receivers.unsqueeze(1).expand(n_edges, edge_output.shape[1]), edge_output
96 )
97 node_input = torch.cat([received_edges, node_data, global_data.expand(n_nodes, -1)], dim=1)
98 node_output = self.node_fn(node_input)
99 global_input = torch.cat(
100 [edge_output.sum(0, keepdim=True), node_output.sum(0, keepdim=True), global_data], dim=1
101 )
102 global_output = self.global_fn(global_input)
103 return node_output, edge_output, global_output
104
105
106# defining a Encode-Process-Decode module for LHCb toy model
108 def __init__(self):
109 super().__init__()
110 self._encoder = MLPGraphIndependent(node_size, edge_size, global_size)
111 self._core = MLPGraphNetwork(2 * LATENT_SIZE, 2 * LATENT_SIZE, 2 * LATENT_SIZE)
112 self._decoder = MLPGraphIndependent(LATENT_SIZE, LATENT_SIZE, LATENT_SIZE)
113 self._output_transform = MLPGraphIndependent(LATENT_SIZE, LATENT_SIZE, LATENT_SIZE)
114
115 def forward(self, node_data, edge_data, global_data, receivers, senders, num_processing_steps):
116 latent = self._encoder(node_data, edge_data, global_data)
117 latent0 = latent
118 output_ops = []
119 for _ in range(num_processing_steps):
120 core_input = tuple(torch.cat([a, b], dim=1) for a, b in zip(latent0, latent))
121 latent = self._core(*core_input, receivers, senders)
122 decoded_op = self._decoder(*latent)
123 output_ops.append(self._output_transform(*decoded_op))
124 return output_ops
125
126
127# Instantiating EncodeProcessDecode Model
128ep_model = EncodeProcessDecode()
130
131# Export the four component models to ONNX
132sample_indices = (torch.from_numpy(rec), torch.from_numpy(snd))
133
134
135def export_component(component, name, num_features):
136 sample_input = (
137 torch.zeros(num_nodes, num_features[0]),
138 torch.zeros(num_edges, num_features[1]),
139 torch.zeros(1, num_features[2]),
140 )
141 input_names = ["node_data", "edge_data", "global_data"]
142 if isinstance(component, MLPGraphNetwork):
143 sample_input += sample_indices
144 input_names += ["receivers", "senders"]
146 component,
147 sample_input,
148 name + ".onnx",
149 input_names=input_names,
150 output_names=["node_output", "edge_output", "global_output"],
151 dynamo=True,
152 )
153
154
155export_component(ep_model._encoder, "gnn_encoder", (node_size, edge_size, global_size))
156export_component(ep_model._core, "gnn_core", (2 * LATENT_SIZE,) * 3)
157export_component(ep_model._decoder, "gnn_decoder", (LATENT_SIZE,) * 3)
158export_component(ep_model._output_transform, "gnn_output_transform", (LATENT_SIZE,) * 3)
159
160# Parse the ONNX models with SOFIE and generate the C++ inference code
162for name in ["gnn_encoder", "gnn_core", "gnn_decoder", "gnn_output_transform"]:
163 model = parser.Parse(name + ".onnx")
166
167# Compile now the generated C++ code from SOFIE
168gen_code = """#pragma cling optimize(2)
169#include "gnn_encoder.hxx"
170#include "gnn_core.hxx"
171#include "gnn_decoder.hxx"
172#include "gnn_output_transform.hxx"
173"""
175
176
177# Build SOFIE GNN Model and run inference
178class SofieGNN:
179 def __init__(self):
180 self.encoder_session = ROOT.TMVA_SOFIE_gnn_encoder.Session()
181 self.core_session = ROOT.TMVA_SOFIE_gnn_core.Session()
182 self.decoder_session = ROOT.TMVA_SOFIE_gnn_decoder.Session()
183 self.output_transform_session = ROOT.TMVA_SOFIE_gnn_output_transform.Session()
184
185 @staticmethod
186 def _as_arrays(result, num_nodes, num_edges):
187 # a session returns the flat node, edge and global output tensors
188 return (
189 np.asarray(result[0], dtype=np.float32).reshape(num_nodes, -1),
190 np.asarray(result[1], dtype=np.float32).reshape(num_edges, -1),
191 np.asarray(result[2], dtype=np.float32).reshape(1, -1),
192 )
193
194 def infer(self, graphData):
195 n_nodes = len(graphData["nodes"])
196 n_edges = len(graphData["edges"])
197
198 def c(x):
199 return np.ascontiguousarray(x, dtype=np.float32)
200
201 receivers = np.ascontiguousarray(graphData["receivers"], dtype=np.int64)
202 senders = np.ascontiguousarray(graphData["senders"], dtype=np.int64)
203
204 latent = self._as_arrays(
205 self.encoder_session.infer(c(graphData["nodes"]), c(graphData["edges"]), c(graphData["globals"])),
206 n_nodes, n_edges,
207 )
208 latent0 = latent
209 output_ops = []
210 for _ in range(processing_steps):
211 core_input = tuple(np.concatenate([a, b], axis=1) for a, b in zip(latent0, latent))
212 latent = self._as_arrays(
213 self.core_session.infer(c(core_input[0]), c(core_input[1]), c(core_input[2]), receivers, senders),
214 n_nodes, n_edges,
215 )
216 decoded = self._as_arrays(
217 self.decoder_session.infer(c(latent[0]), c(latent[1]), c(latent[2])), n_nodes, n_edges
218 )
220 self._as_arrays(
221 self.output_transform_session.infer(c(decoded[0]), c(decoded[1]), c(decoded[2])),
222 n_nodes, n_edges,
223 )
224 )
225 return output_ops
226
227
228# Test both GNN on some simulated events
229dataSet = [get_graph_data_dict(num_nodes, num_edges, node_size, edge_size, global_size) for i in range(numevts)]
230
231
232# Function to run the PyTorch model
233def RunGNet(graphData):
234 return ep_model(
235 torch.from_numpy(graphData["nodes"]),
236 torch.from_numpy(graphData["edges"]),
237 torch.from_numpy(graphData["globals"]),
238 torch.from_numpy(graphData["receivers"]),
239 torch.from_numpy(graphData["senders"]),
240 processing_steps,
241 )
242
243
244start = time.time()
245hG = ROOT.TH1D("hG", "Result from PyTorch", 20, 1, 0)
246torchOutput = []
247for i in range(numevts):
248 out = RunGNet(dataSet[i])
249 torchOutput.append([[t.numpy() for t in step] for step in out])
250 hG.Fill(np.mean(torchOutput[-1][1][2]))
251
252end = time.time()
253print("elapsed time for ", numevts, "events = ", end - start)
254
255# running SOFIE-GNN
256hS = ROOT.TH1D("hS", "Result from SOFIE", 20, 1, 0)
257start0 = time.time()
258gnn = SofieGNN()
259start = time.time()
260print("time to create SOFIE GNN class", start - start0)
261sofieOutput = []
262for i in range(numevts):
263 out = gnn.infer(dataSet[i])
265 hS.Fill(np.mean(out[1][2]))
266
267end = time.time()
268print("elapsed time for ", numevts, "events = ", end - start)
269
270c0 = ROOT.TCanvas()
271c0.Divide(1, 2)
272c1 = c0.cd(1)
273c1.Divide(2, 1)
274c1.cd(1)
275hG.Draw()
276c1.cd(2)
277hS.Draw()
278
279hDn = ROOT.TH1D("hDn", "Difference for node data", 40, 1, 0)
280hDe = ROOT.TH1D("hDe", "Difference for edge data", 40, 1, 0)
281hDg = ROOT.TH1D("hDg", "Difference for global data", 40, 1, 0)
282# compute differences between SOFIE and PyTorch
283maxDifference = 0.0
284for i in range(numevts):
285 for hist, j in [(hDn, 0), (hDe, 1), (hDg, 2)]:
286 difference = sofieOutput[i][1][j] - torchOutput[i][1][j]
287 for value in difference.flatten():
288 hist.Fill(value)
289 maxDifference = max(maxDifference, np.abs(difference).max())
290
291print("maximum difference between SOFIE and PyTorch = ", maxDifference)
292if maxDifference > 1e-4:
293 raise RuntimeError("SOFIE and PyTorch outputs disagree")
294
295c2 = c0.cd(2)
296c2.Divide(3, 1)
297c2.cd(1)
298hDn.Draw()
299c2.cd(2)
300hDe.Draw()
301c2.cd(3)
302hDg.Draw()
303
304c0.Draw()
#define c(i)
Definition RSha256.hxx:101
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len