-
Notifications
You must be signed in to change notification settings - Fork 545
/
ImporterContext.hpp
392 lines (361 loc) · 12.4 KB
/
ImporterContext.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "NvOnnxParser.h"
#include "ShapedWeights.hpp"
#include "Status.hpp"
#include "TensorOrWeights.hpp"
#include "onnxErrorRecorder.hpp"
#include "WeightsContext.hpp"
#include <fstream>
#include <functional>
#include <list>
#include <onnx/onnx_pb.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace onnx2trt
{
template <typename T>
using StringMap = std::unordered_map<std::string, T>;
class ErrorRecorderWrapper
{
public:
ErrorRecorderWrapper(nvinfer1::INetworkDefinition* network, nvinfer1::ILogger* logger)
: mNetwork(network)
, mLogger(logger)
{
if (mNetwork)
{
mUserErrorRecorder = mNetwork->getErrorRecorder();
mOnnxErrorRecorder = ONNXParserErrorRecorder::create(logger, mUserErrorRecorder);
if (mOnnxErrorRecorder)
{
if (mUserErrorRecorder)
{
mUserErrorRecorder->incRefCount();
}
mNetwork->setErrorRecorder(mOnnxErrorRecorder);
}
}
}
~ErrorRecorderWrapper()
{
if (mNetwork && mOnnxErrorRecorder)
{
if (mUserErrorRecorder)
{
mNetwork->setErrorRecorder(mUserErrorRecorder);
mUserErrorRecorder->decRefCount();
}
ONNXParserErrorRecorder::destroy(mOnnxErrorRecorder);
}
}
bool hasError() const
{
return mOnnxErrorRecorder != nullptr && mOnnxErrorRecorder->getNbErrors() != 0;
}
//! Return recorder used by hasError().
nvinfer1::IErrorRecorder* getErrorRecorder() const
{
return mOnnxErrorRecorder ? mOnnxErrorRecorder : nullptr;
}
private:
nvinfer1::INetworkDefinition* mNetwork{nullptr};
nvinfer1::ILogger* mLogger{nullptr};
ONNXParserErrorRecorder* mOnnxErrorRecorder{nullptr};
nvinfer1::IErrorRecorder* mUserErrorRecorder{nullptr};
};
class ImporterContext
{
nvinfer1::INetworkDefinition* mNetwork;
nvinfer1::ILogger* mLogger;
//! WeightsContext object to hold ownership of ONNX weights and any temporary weights created by the Parser.
WeightsContext mWeightsContext;
StringMap<int64_t> mOpsets;
//! All tensors in the graph mapped to their names.
StringMap<TensorOrWeights> mTensors;
StringMap<nvinfer1::TensorLocation> mTensorLocations;
StringMap<float> mTensorRangeMins;
StringMap<float> mTensorRangeMaxes;
StringMap<nvinfer1::DataType> mLayerPrecisions;
//! Set to keep track of how many times a tensor name shows up, to avoid duplicate naming in TRT.
std::set<std::string> mTensorNames;
//! Set to keep track of how many times a tensor name shows up, to avoid duplicate naming in TRT.
std::set<std::string> mLayerNames;
//! An increasing suffix counter used to uniquify layer names.
int64_t mSuffixCounter{0};
//! Set to keep track of how many times a batch norm weight name shows up,
//! to avoid duplicate naming in TRT.
std::set<std::string> mBatchNormWeightNames;
//! An increasing suffix counter used to uniquify batch norm weight names.
int64_t mBatchNormWeightSuffixCounter{0};
//! Set to hold output tensor names of layers that produce shape tensor outputs but do not
//! natively support them.
std::unordered_set<std::string> mUnsupportedShapeTensors;
//! Container to map subgraph tensors to their original outer graph names.
StringMap<std::string> mLoopTensors;
//! Error recorder to control TRT errors.
std::unique_ptr<ErrorRecorderWrapper> mErrorWrapper;
StringMap<nvinfer1::IConstantLayer*> mConstantLayers;
bool mConvertINT64Logged{false};
bool mConvertINT64OutOfBoundsLogged{false};
bool mConvertDoubleLogged{false};
bool mConvertDoubleOutOfBoundsLogged{false};
//! OnnxParserFlags specified by the parser.
nvonnxparser::OnnxParserFlags mOnnxParserFlags;
StringMap<std::vector<nvinfer1::ITensor const*>> mNodeNameToTensor;
//! Logical library names for VC plugin libraries. This gets translated to library paths
//! when getUsedVCPluginLibraries() is called.
std::set<std::string> mLogicalVCPluginLibraries;
//! Stack of names defined by nested ONNX graphs, with information about how to
//! restore their associated values when popping back to the surrounding scope.
//!
//! The stack is empty when processing the top-level ONNX graph.
//! back() corresponds to the innermost ONNX graph being processed.
//!
//! For each entry {name, {bool, TensorOrWeights}}:
//!
//! * If the bool is true, the name was newly introduced by the scope.
//!
//! * If the bool is false, the name shadows a name in a surrounding scope,
//! and TensorOrWeights was the name's value before being shadowed.
//!
std::vector<StringMap<std::pair<bool, TensorOrWeights>>> mBaseNameScopeStack;
//! Map holding FunctionProtos
StringMap<::ONNX_NAMESPACE::FunctionProto> mLocalFunctions;
//! Data type to keep track of a local function in mLocalFunctionStack.
//! It is a tuple of three elements: (1) function name (2) node name and (3) function attributes.
struct LocalFunctionMetadata
{
std::string functionName;
std::string nodeName;
StringMap<::ONNX_NAMESPACE::AttributeProto const*> attrs;
};
//! Vector to hold current local function names and attributes
std::vector<LocalFunctionMetadata> mLocalFunctionStack;
//! Vector to hold the local function names at each error
std::vector<std::vector<std::string>> mLocalFunctionErrors;
//! Vector to hold expected graph outputs
std::vector<::ONNX_NAMESPACE::ValueInfoProto> mGraphOutputNames;
public:
ImporterContext(nvinfer1::INetworkDefinition* network, nvinfer1::ILogger* logger)
: mNetwork(network)
, mLogger(logger)
, mWeightsContext(WeightsContext(logger))
, mErrorWrapper(std::make_unique<ErrorRecorderWrapper>(mNetwork, logger))
{
}
nvinfer1::INetworkDefinition* network()
{
assert(mNetwork != nullptr);
return mNetwork;
}
WeightsContext& getWeightsContext()
{
return mWeightsContext;
}
StringMap<TensorOrWeights>& tensors()
{
return mTensors;
}
StringMap<nvinfer1::TensorLocation>& tensorLocations()
{
return mTensorLocations;
}
StringMap<float>& tensorRangeMins()
{
return mTensorRangeMins;
}
StringMap<float>& tensorRangeMaxes()
{
return mTensorRangeMaxes;
}
StringMap<nvinfer1::DataType>& layerPrecisions()
{
return mLayerPrecisions;
}
std::unordered_set<std::string>& unsupportedShapeTensors()
{
return mUnsupportedShapeTensors;
}
StringMap<std::string>& loopTensors()
{
return mLoopTensors;
}
// Pass file location down to WeightsContext as all external weight handling logic is done in that class.
void setOnnxFileLocation(std::string location)
{
mWeightsContext.setOnnxFileLocation(location);
}
void pushBaseNameScope();
void popBaseNameScope();
// This actually handles weights as well, but is named this way to be consistent with the tensors()
void registerTensor(TensorOrWeights tensor, std::string const& basename, bool const checkUniqueName = false);
void registerLayer(nvinfer1::ILayer* layer, std::string const& basename, ::ONNX_NAMESPACE::NodeProto const* node);
void registerLayer(nvinfer1::ILayer* layer, ::ONNX_NAMESPACE::NodeProto const& node);
nvinfer1::ILogger& logger()
{
return *mLogger;
}
// Register an unique name for the created weights
ShapedWeights createNamedTempWeights(ShapedWeights::DataType type, nvinfer1::Dims shape, bool batchNormNode = false)
{
if (batchNormNode)
{
return mWeightsContext.createNamedTempWeights(
type, shape, mBatchNormWeightNames, mBatchNormWeightSuffixCounter, /*batchNormNode=*/true);
}
return mWeightsContext.createNamedTempWeights(type, shape, mTensorNames, mSuffixCounter);
}
void clearOpsets()
{
mOpsets.clear();
}
void addOpset(std::string domain, int64_t version)
{
mOpsets.emplace(domain, version);
}
int64_t getOpsetVersion(const char* domain = "") const
{
if (mOpsets.empty())
{
return 1;
}
else if (mOpsets.size() == 1)
{
return mOpsets.begin()->second;
}
else if (mOpsets.count(domain))
{
return mOpsets.at(domain);
}
else
{
domain = "ai.onnx";
assert(mOpsets.count(domain));
return mOpsets.at(domain);
}
}
bool hasError() const noexcept
{
return mErrorWrapper != nullptr && mErrorWrapper->hasError();
}
nvinfer1::IErrorRecorder* getErrorRecorder() const noexcept
{
return mErrorWrapper ? mErrorWrapper->getErrorRecorder() : nullptr;
}
nvinfer1::IConstantLayer* getConstantLayer(const char* name) const
{
if (name == nullptr)
{
return nullptr;
}
auto const iter = mConstantLayers.find(name);
if (iter == mConstantLayers.end())
{
return nullptr;
}
return iter->second;
}
void setFlags(nvonnxparser::OnnxParserFlags const& onnxParserFlags)
{
mOnnxParserFlags = onnxParserFlags;
}
nvonnxparser::OnnxParserFlags getFlags() const
{
return mOnnxParserFlags;
}
virtual void addUsedVCPluginLibrary(
::ONNX_NAMESPACE::NodeProto const& node, char const* pluginName, char const* pluginLib);
virtual std::vector<std::string> getUsedVCPluginLibraries();
bool isConvertINT64Logged()
{
return mConvertINT64Logged;
}
void setConvertINT64Logged(bool logged)
{
mConvertINT64Logged = logged;
}
bool isConvertINT64OutOfBoundsLogged()
{
return mConvertINT64OutOfBoundsLogged;
}
void setConvertINT64OutOfBoundsLogged(bool logged)
{
mConvertINT64OutOfBoundsLogged = logged;
}
bool isConvertDoubleLogged()
{
return mConvertDoubleLogged;
}
void setConvertDoubleLogged(bool logged)
{
mConvertDoubleLogged = logged;
}
bool isConvertDoubleOutOfBoundsLogged()
{
return mConvertDoubleOutOfBoundsLogged;
}
void setConvertDoubleOutOfBoundsLogged(bool logged)
{
mConvertDoubleOutOfBoundsLogged = logged;
}
StringMap<::ONNX_NAMESPACE::FunctionProto>& localFunctions()
{
return mLocalFunctions;
}
std::vector<LocalFunctionMetadata>& localFunctionStack()
{
return mLocalFunctionStack;
}
std::vector<std::vector<std::string>>& localFunctionErrors()
{
return mLocalFunctionErrors;
}
std::vector<::ONNX_NAMESPACE::ValueInfoProto>& getGraphOutputNames()
{
return mGraphOutputNames;
}
nvinfer1::ITensor const* findLayerOutputTensor(std::string name, int64_t i)
{
auto it = mNodeNameToTensor.find(name);
if (it == mNodeNameToTensor.end())
{
return nullptr;
}
auto tensors = it->second;
return i < static_cast<int64_t>(tensors.size()) ? tensors.at(i) : nullptr;
}
void addLayerOutputTensors(std::string name, std::vector<TensorOrWeights> const& outputs)
{
if (mNodeNameToTensor.find(name) != mNodeNameToTensor.end())
{
auto* ctx = this; // For logging
LOG_WARNING(
"A node named " << name
<< " already exists, the output tensors of this new instance will not be queryable.");
return;
}
for (auto const& output : outputs)
{
if (output.is_tensor())
{
mNodeNameToTensor[name].push_back(static_cast<nvinfer1::ITensor const*>(&(output.tensor())));
}
}
}
size_t getNestedDepth()
{
return mBaseNameScopeStack.size();
}
};
typedef std::vector<TensorOrWeights> NodeOutputs;
typedef std::function<NodeOutputs(ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t const nodeIdx,
std::vector<TensorOrWeights>& inputs)>
NodeImporter;
typedef std::function<void(
ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<Status>& errors, size_t const nodeIndex)>
OpStaticErrorChecker;
} // namespace onnx2trt