Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_SOFIE_PyTorch.py
Go to the documentation of this file.
1### \file
2### \ingroup tutorial_ml
3### \notebook -nodraw
4### This macro provides a simple example for the parsing of PyTorch .pt file
5### into RModel object and further generating the .hxx header files for inference.
6###
7### \macro_code
8### \macro_output
9### \author Sanjiban Sengupta
10
11import sys
12
13import ROOT
14import torch
15import torch.nn as nn
16
18
19# Python and C++ write to separate stdout buffers; flush both on every line so
20# that the Python prints and the RModel printouts appear in order
21sys.stdout.reconfigure(line_buffering=True)
22ROOT.gInterpreter.ProcessLine("std::cout << std::unitbuf;")
23
24# ------------------------------------------------------------------------------
25# Step 1: Create, train and save a simple PyTorch model
26# ------------------------------------------------------------------------------
27
28model = nn.Sequential(
29 nn.Linear(32, 16),
30 nn.ReLU(),
31 nn.Linear(16, 8),
32 nn.ReLU(),
33)
34
35criterion = nn.MSELoss()
36optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
37
38x = torch.randn(2, 32)
39y = torch.randn(2, 8)
40
41for i in range(500):
42 y_pred = model(x)
43 loss = criterion(y_pred, y)
47
49m = torch.jit.script(model)
50torch.jit.save(m, "PyTorchModel.pt")
51
52# ------------------------------------------------------------------------------
53# Step 2: Parse the saved PyTorch .pt file with TMVA::SOFIE
54# ------------------------------------------------------------------------------
55
56# Parsing a PyTorch model requires the shape and data-type of input tensor
57# Data-type of input tensor defaults to Float if not specified
58input_shapes = ROOT.std.vector["std::vector<std::size_t>"]()
60
61# Parsing the saved PyTorch .pt file into RModel object
62model = SOFIE.PyTorch.Parse("PyTorchModel.pt", input_shapes)
63
64# Generating inference code
66model.OutputGenerated("PyTorchModel.hxx")
67
68# Printing required input tensors
69print("\n")
71
72# Printing initialized tensors (weights)
73print("\n")
75
76# Printing intermediate tensors
77print("\n")
79
80# Checking if tensor already exist in model
81tensor_exists = bool(model.CheckIfTensorAlreadyExist("0weight"))
82print(f'\n\nTensor "0weight" already exist: {str(tensor_exists).lower()}\n')
83
84tensor_shape = model.GetTensorShape("0weight")
85print('Shape of tensor "0weight": ' + ",".join(str(dim) for dim in tensor_shape) + ",")
86
87tensor_type = model.GetTensorType("0weight")
88print(f'\nData type of tensor "0weight": {SOFIE.ConvertTypeToString(tensor_type)}')
89
90# Printing generated inference code
91print()
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.