|
| 1 | +// @(#)root/tmva/sofie:$Id$ |
| 2 | +// Author: Stefan van Berkum |
| 3 | + |
| 4 | +/** |
| 5 | + * Header file for PyTorch Geometric models. |
| 6 | + * |
| 7 | + * Models are created by the user and parameters can then be loaded into each layer. |
| 8 | + * |
| 9 | + * IMPORTANT: Changes to the format (e.g., namespaces) may affect the emit |
| 10 | + * defined in RModel_TorchGNN.cxx (save). |
| 11 | +*/ |
| 12 | + |
| 13 | +#ifndef TMVA_SOFIE_RMODEL_TORCHGNN_H_ |
| 14 | +#define TMVA_SOFIE_RMODEL_TORCHGNN_H_ |
| 15 | + |
| 16 | +#include "TMVA/TorchGNN/modules/RModule.hxx" |
| 17 | +#include "TMVA/TorchGNN/modules/RModule_Input.hxx" |
| 18 | +#include <stdexcept> |
| 19 | +#include <iostream> |
| 20 | + |
| 21 | +namespace TMVA { |
| 22 | +namespace Experimental { |
| 23 | +namespace SOFIE { |
| 24 | + |
| 25 | +class RModel_TorchGNN { |
| 26 | + public: |
| 27 | + /** Model constructor without inputs. */ |
| 28 | + RModel_TorchGNN() {} |
| 29 | + |
| 30 | + /** |
| 31 | + * Model constructor with manual input names. |
| 32 | + * |
| 33 | + * @param input_names Vector of input names. |
| 34 | + * @param input_shapes Vector of input shapes. Each element may contain |
| 35 | + * at most one wildcard (-1). |
| 36 | + */ |
| 37 | + RModel_TorchGNN(std::vector<std::string> input_names, std::vector<std::vector<int>> input_shapes) { |
| 38 | + fInputs = input_names; |
| 39 | + fShapes = input_shapes; |
| 40 | + |
| 41 | + // Generate input layers. |
| 42 | + for (std::size_t i = 0; i < input_names.size(); i++) { |
| 43 | + // Check shape. |
| 44 | + if (std::any_of(input_shapes[i].begin(), input_shapes[i].end(), [](int j){return j == 0;})) { |
| 45 | + throw std::invalid_argument("Invalid input shape for input " + input_names[i] + ". Dimension cannot be zero."); |
| 46 | + } |
| 47 | + if (std::any_of(input_shapes[i].begin(), input_shapes[i].end(), [](int j){return j < -1;})) { |
| 48 | + throw std::invalid_argument("Invalid input shape for input " + input_names[i] + ". Shape cannot have negative entries (except for the wildcard dimension)."); |
| 49 | + } |
| 50 | + if (std::count(input_shapes[i].begin(), input_shapes[i].end(), -1) > 1) { |
| 51 | + throw std::invalid_argument("Invalid input shape for input " + input_names[i] + ". Shape may have at most one wildcard."); |
| 52 | + } |
| 53 | + AddModule(RModule_Input(input_shapes[i]), input_names[i]); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Add a module to the module list. |
| 59 | + * |
| 60 | + * @param module Module to add. |
| 61 | + * @param name Module name. Defaults to the module type with a count |
| 62 | + * value (e.g., GCNConv_1). |
| 63 | + */ |
| 64 | + template<typename T> |
| 65 | + void AddModule(T module, std::string name="") { |
| 66 | + std::string new_name = (name == "") ? std::string(module.GetOperation()) : name; |
| 67 | + if (fModuleCounts[new_name] > 0) { |
| 68 | + // Module exists, so add discriminator and increment count. |
| 69 | + new_name += "_" + std::to_string(fModuleCounts[new_name]); |
| 70 | + fModuleCounts[new_name]++; |
| 71 | + |
| 72 | + if (name != "") { |
| 73 | + // Issue warning. |
| 74 | + std::cout << "WARNING: Module with duplicate name \"" << name << "\" renamed to \"" << new_name << "\"." << std::endl; |
| 75 | + } |
| 76 | + } else { |
| 77 | + // First module of its kind. |
| 78 | + fModuleCounts[new_name] = 1; |
| 79 | + } |
| 80 | + module.SetName(new_name); |
| 81 | + |
| 82 | + // Initialize the module. |
| 83 | + module.Initialize(fModules, fModuleMap); |
| 84 | + |
| 85 | + // Add module to the module list. |
| 86 | + fModules.push_back(std::make_shared<T>(module)); |
| 87 | + fModuleMap[std::string(module.GetName())] = fModuleCount; |
| 88 | + fModuleCount++; |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Run the forward function. |
| 93 | + * |
| 94 | + * @param args Any number of input arguments. |
| 95 | + * @returns The output of the last layer. |
| 96 | + */ |
| 97 | + template<class... Types> |
| 98 | + std::vector<float> Forward(Types... args) { |
| 99 | + auto input = std::make_tuple(args...); |
| 100 | + |
| 101 | + // Instantiate input layers. |
| 102 | + int k = 0; |
| 103 | + std::apply( |
| 104 | + [&](auto&... in) { |
| 105 | + ((std::dynamic_pointer_cast<RModule_Input>(fModules[k++]) -> SetParams(in)), ...); |
| 106 | + }, input); |
| 107 | + |
| 108 | + // Loop through and execute modules. |
| 109 | + for (std::shared_ptr<RModule> module: fModules) { |
| 110 | + module -> Execute(); |
| 111 | + } |
| 112 | + |
| 113 | + // Return output of the last layer. |
| 114 | + const std::vector<float>& out_const = fModules.back() -> GetOutput(); |
| 115 | + std::vector<float> out = out_const; |
| 116 | + return out; |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Load parameters from PyTorch state dictionary for all modules. |
| 121 | + * |
| 122 | + * @param state_dict The state dictionary. |
| 123 | + */ |
| 124 | + void LoadParameters(std::map<std::string, std::vector<float>> state_dict) { |
| 125 | + for (std::shared_ptr<RModule> module: fModules) { |
| 126 | + module -> LoadParameters(state_dict); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Load saved parameters for all modules. |
| 132 | + */ |
| 133 | + void LoadParameters() { |
| 134 | + for (std::shared_ptr<RModule> module: fModules) { |
| 135 | + module -> LoadParameters(); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * Save the model as standalone inference code. |
| 141 | + * |
| 142 | + * @param path Path to save location. |
| 143 | + * @param name Model name. |
| 144 | + * @param overwrite True if any existing directory should be |
| 145 | + * overwritten. Defaults to false. |
| 146 | + */ |
| 147 | + void Save(std::string path, std::string name, bool overwrite=false); |
| 148 | + private: |
| 149 | + /** |
| 150 | + * Get a timestamp. |
| 151 | + * |
| 152 | + * @returns The timestamp in string format. |
| 153 | + */ |
| 154 | + static std::string GetTimestamp() { |
| 155 | + time_t rawtime; |
| 156 | + struct tm * timeinfo; |
| 157 | + char timestamp [80]; |
| 158 | + time(&rawtime); |
| 159 | + timeinfo = localtime(&rawtime); |
| 160 | + strftime(timestamp, 80, "Timestamp: %d-%m-%Y %T.", timeinfo); |
| 161 | + return timestamp; |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * Write the methods to create a self-contained package. |
| 166 | + * |
| 167 | + * @param dir Directory to save to. |
| 168 | + * @param name Model name. |
| 169 | + * @param timestamp Timestamp. |
| 170 | + */ |
| 171 | + void WriteMethods(std::string dir, std::string name, std::string timestamp); |
| 172 | + |
| 173 | + /** |
| 174 | + * Write the model to a file. |
| 175 | + * |
| 176 | + * @param dir Directory to save to. |
| 177 | + * @param name Model name. |
| 178 | + * @param timestamp Timestamp. |
| 179 | + */ |
| 180 | + void WriteModel(std::string dir, std::string name, std::string timestamp); |
| 181 | + |
| 182 | + /** |
| 183 | + * Write the CMakeLists file. |
| 184 | + * |
| 185 | + * @param dir Directory to save to. |
| 186 | + * @param name Model name. |
| 187 | + * @param timestamp Timestamp. |
| 188 | + */ |
| 189 | + void WriteCMakeLists(std::string dir, std::string name, std::string timestamp); |
| 190 | + |
| 191 | + std::vector<std::string> fInputs; // Vector of input names. |
| 192 | + std::vector<std::vector<int>> fShapes; // Vector of input shapes. |
| 193 | + std::map<std::string, int> fModuleCounts; // Map from module name to number of occurrences. |
| 194 | + std::vector<std::shared_ptr<RModule>> fModules; // Vector containing the modules. |
| 195 | + std::map<std::string, int> fModuleMap; // Map from module name to module index (in modules). |
| 196 | + int fModuleCount = 0; // Number of modules. |
| 197 | +}; |
| 198 | + |
| 199 | +} // SOFIE. |
| 200 | +} // Experimental. |
| 201 | +} // TMVA. |
| 202 | + |
| 203 | +#endif // TMVA_SOFIE_RMODEL_TORCHGNN_H_ |
0 commit comments