Skip to content

Commit b9b0aff

Browse files
authored
Merge pull request #510 from NVIDIA/input_type
feat: Add support for providing input datatypes in TRTorch
2 parents 75e86e8 + f330a10 commit b9b0aff

File tree

76 files changed

+2705
-1276
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+2705
-1276
lines changed

README.md

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,13 @@ More Information / System Architecture:
1818
#include "trtorch/trtorch.h"
1919

2020
...
21-
auto compile_settings = trtorch::CompileSpec(dims);
21+
// Set input datatypes. Allowerd options torch::{kFloat, kHalf, kChar, kInt32, kBool}
22+
// Size of input_dtypes should match number of inputs to the network.
23+
// If input_dtypes is not set, default precision follows traditional PyT / TRT rules
24+
auto input = trtorch::CompileSpec::Input(dims, torch::kHalf)
25+
auto compile_settings = trtorch::CompileSpec({input});
2226
// FP16 execution
23-
compile_settings.op_precision = torch::kFloat;
27+
compile_settings.enabled_precisions = {torch::kHalf};
2428
// Compile module
2529
auto trt_mod = trtorch::CompileGraph(ts_mod, compile_settings);
2630
// Run like normal
@@ -36,14 +40,14 @@ import trtorch
3640
3741
...
3842
compile_settings = {
39-
"input_shapes": [
40-
{
41-
"min": [1, 3, 224, 224],
42-
"opt": [1, 3, 512, 512],
43-
"max": [1, 3, 1024, 1024]
44-
}, # For static size [1, 3, 224, 224]
45-
],
46-
"op_precision": torch.half # Run with FP16
43+
"inputs": [trtorch.Input(
44+
min_shape=[1, 3, 224, 224],
45+
opt_shape=[1, 3, 512, 512],
46+
max_shape=[1, 3, 1024, 1024]
47+
# For static size shape=[1, 3, 224, 224]
48+
dtype=torch.half, # Datatype of input tensor. Allowed options torch.(float|half|int8|int32|bool)
49+
)],
50+
"enabled_precision": {torch.half}, # Run with FP16
4751
}
4852
4953
trt_ts_module = trtorch.compile(torch_script_module, compile_settings)
@@ -54,9 +58,9 @@ torch.jit.save(trt_ts_module, "trt_torchscript_module.ts")
5458
```
5559

5660
> Notes on running in lower precisions:
57-
> - Set precision with compile_spec.op_precision
61+
> - Enabled lower precisions with compile_spec.enabled_precisions
5862
> - The module should be left in FP32 before compilation (FP16 can support half tensor models)
59-
> - In FP16 only input tensors should be converted to FP16, other precisions use FP32
63+
> - In FP16 only input tensors by default should be FP16, other precisions use FP32. This can be overrided by setting Input::dtype
6064
6165
## Platform Support
6266

core/compiler.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ torch::jit::script::Module CompileGraphWithFallback(const torch::jit::script::Mo
196196
LOG_INFO(*g << "(LoweringGraph)\n");
197197

198198
// segment the graph and convert segmented TensorRT block
199-
auto segmented_blocks = partitioning::Partition(g, convert_cfg.input_ranges, cfg.partition_info);
199+
auto segmented_blocks = partitioning::Partition(g, convert_cfg.inputs, cfg.partition_info);
200200
if (segmented_blocks.size() == 1 && segmented_blocks[0].target() == partitioning::SegmentedBlock::kTorch) {
201201
LOG_WARNING("Didn't generate any TensorRT engines, the compiler did nothing\n");
202202
return mod;
@@ -210,16 +210,16 @@ torch::jit::script::Module CompileGraphWithFallback(const torch::jit::script::Mo
210210
for (auto& seg_block : segmented_blocks) {
211211
std::string cur_block_target =
212212
seg_block.target() == partitioning::SegmentedBlock::kTensorRT ? "TensorRT" : "Torch";
213-
LOG_INFO(*seg_block.g() << "(MiniGraphIn" << cur_block_target << "Block)\n");
213+
LOG_INFO(*seg_block.g() << "(Sub Graph" << cur_block_target << "Block)\n");
214214
std::ostringstream trt_engine_id;
215215
trt_engine_id << reinterpret_cast<const int*>(&seg_block);
216216
if (seg_block.target() == partitioning::SegmentedBlock::kTensorRT) {
217-
std::vector<ir::InputRange> input_ranges;
217+
std::vector<ir::Input> inputs;
218218
for (auto& shape : seg_block.in_shape()) {
219-
input_ranges.push_back(ir::InputRange(shape));
219+
inputs.push_back(ir::Input(shape));
220220
}
221221
// update the input ranges for each segments
222-
convert_cfg.input_ranges = input_ranges;
222+
convert_cfg.inputs = inputs;
223223
auto engine = conversion::ConvertBlockToEngine(seg_block.block(), convert_cfg, named_params);
224224
auto temp_g = std::make_shared<torch::jit::Graph>();
225225
auto device_spec = convert_cfg.engine_settings.device;

core/compiler.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ namespace trtorch {
1212
namespace core {
1313

1414
struct CompileSpec {
15-
CompileSpec(std::vector<ir::InputRange> input_ranges) : convert_info(std::move(input_ranges)) {}
15+
CompileSpec(std::vector<ir::Input> inputs) : convert_info(std::move(inputs)) {}
1616
conversion::ConversionInfo convert_info;
1717
partitioning::PartitionInfo partition_info;
1818
};

core/conversion/conversion.cpp

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,7 @@ void AddLayer(ConversionCtx* ctx, const torch::jit::Node* n) {
125125
<< "please report this error to https://www.github.com/NVIDIA/TRTorch/issues");
126126
}
127127

128-
void AddInputs(
129-
ConversionCtx* ctx,
130-
at::ArrayRef<const torch::jit::Value*> inputs,
131-
std::vector<ir::InputRange>& input_dims) {
128+
void AddInputs(ConversionCtx* ctx, at::ArrayRef<const torch::jit::Value*> inputs, std::vector<ir::Input>& input_specs) {
132129
std::vector<const torch::jit::Value*> input_tensors;
133130
for (auto in : inputs) {
134131
// Disregarding inputs that are not tensors
@@ -142,29 +139,40 @@ void AddInputs(
142139
}
143140
}
144141

142+
std::stringstream ss;
143+
ss << "Input Dimension Specs: [\n";
144+
for (auto i : input_specs) {
145+
ss << " " << i << ",";
146+
}
147+
ss << ']';
148+
LOG_DEBUG(ctx->logger, ss.str());
149+
145150
TRTORCH_CHECK(
146-
input_tensors.size() == input_dims.size(),
151+
input_tensors.size() == input_specs.size(),
147152
"Expected dimension specifications for all input tensors"
148-
<< ", but found " << input_tensors.size() << " input tensors and " << input_dims.size()
153+
<< ", but found " << input_tensors.size() << " input tensors and " << input_specs.size()
149154
<< " dimension specs (conversion.AddInputs)");
150155

151156
auto profile = ctx->builder->createOptimizationProfile();
152157

153158
for (size_t i = 0; i < input_tensors.size(); i++) {
154159
auto in = input_tensors[i];
155-
auto dims = input_dims[i];
160+
auto spec = input_specs[i];
156161
std::string name = std::string("input_") + std::to_string(ctx->num_inputs);
157162
LOG_INFO(
158-
ctx->logger, "Adding Input " << in->debugName() << " named " << name << " in engine (conversion.AddInputs)");
159-
LOG_DEBUG(ctx->logger, "Input shape set to " << dims.input_shape);
160-
auto trt_in = ctx->net->addInput(name.c_str(), ctx->input_type, dims.input_shape);
163+
ctx->logger,
164+
"Adding Input " << in->debugName() << " (named: " << name << "): " << spec
165+
<< " in engine (conversion.AddInputs)");
166+
167+
auto trt_in = ctx->net->addInput(name.c_str(), spec.dtype, spec.input_shape);
161168
TRTORCH_CHECK(trt_in, "Failed to add input node: " << in->debugName() << " (conversion.AddInputs)");
169+
trt_in->setAllowedFormats(1U << static_cast<int>(spec.format));
162170

163-
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kMIN, dims.min);
164-
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kOPT, dims.opt);
165-
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kMAX, dims.max);
171+
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kMIN, spec.min);
172+
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kOPT, spec.opt);
173+
profile->setDimensions(trt_in->getName(), nvinfer1::OptProfileSelector::kMAX, spec.max);
166174

167-
if (dims.input_is_dynamic) {
175+
if (spec.input_is_dynamic) {
168176
ctx->input_is_dynamic = true;
169177
}
170178

@@ -178,7 +186,7 @@ void AddInputs(
178186

179187
ctx->cfg->addOptimizationProfile(profile);
180188
#if NV_TENSORRT_MAJOR > 7 || (NV_TENSORRT_MAJOR == 7 && NV_TENSORRT_MINOR >= 1)
181-
if (ctx->op_precision == nvinfer1::DataType::kINT8) {
189+
if (ctx->enabled_precisions.find(nvinfer1::DataType::kINT8) != ctx->enabled_precisions.end()) {
182190
ctx->cfg->setCalibrationProfile(profile);
183191
}
184192
#endif
@@ -350,7 +358,7 @@ void ConvertBlockToNetDef(
350358

351359
auto inputs = b->inputs();
352360
AddParamsToCtxValueMap(ctx, static_params);
353-
AddInputs(ctx, inputs, build_info.input_ranges);
361+
AddInputs(ctx, inputs, build_info.inputs);
354362

355363
auto nodes = b->nodes();
356364

core/conversion/conversion.h

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,9 @@ namespace core {
1212
namespace conversion {
1313

1414
struct ConversionInfo {
15-
std::vector<ir::InputRange> input_ranges;
15+
std::vector<ir::Input> inputs;
1616
BuilderSettings engine_settings;
17-
ConversionInfo(std::vector<ir::InputRange> input_ranges)
18-
: input_ranges(std::move(input_ranges)), engine_settings(BuilderSettings()) {}
17+
ConversionInfo(std::vector<ir::Input> inputs) : inputs(std::move(inputs)), engine_settings(BuilderSettings()) {}
1918
};
2019

2120
// TODO: REMOVE GRAPH AND PARAMS AND MOVE FULLY TO INLINED CONSTANTS

core/conversion/conversionctx/ConversionCtx.cpp

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,11 @@ namespace conversion {
1010
// clang-format off
1111
std::ostream& operator<<(std::ostream& os, const BuilderSettings& s) {
1212
os << "Settings requested for TensorRT engine:" \
13-
<< "\n Operating Precision: " << s.op_precision \
14-
<< "\n TF32 Floating Point Computation Enabled: " << !s.disable_tf32 \
13+
<< "\n Enabled Precisions: ";
14+
for (auto p = s.enabled_precisions.begin(); p != s.enabled_precisions.end(); ++p) {
15+
os << *p << ' ';
16+
}
17+
os << "\n TF32 Floating Point Computation Enabled: " << !s.disable_tf32 \
1518
<< "\n Truncate Long and Double: " << s.truncate_long_and_double \
1619
<< "\n Make Refittable Engine: " << s.refit \
1720
<< "\n Debuggable Engine: " << s.debug \
@@ -57,30 +60,31 @@ ConversionCtx::ConversionCtx(BuilderSettings build_settings)
5760
LOG_DEBUG(build_settings);
5861
cfg = builder->createBuilderConfig();
5962

60-
switch (settings.op_precision) {
61-
case nvinfer1::DataType::kHALF:
62-
TRTORCH_CHECK(builder->platformHasFastFp16(), "Requested inference in FP16 but platform does not support FP16");
63-
cfg->setFlag(nvinfer1::BuilderFlag::kFP16);
64-
input_type = nvinfer1::DataType::kHALF;
65-
break;
66-
case nvinfer1::DataType::kINT8:
67-
TRTORCH_CHECK(builder->platformHasFastInt8(), "Requested inference in INT8 but platform does not support INT8");
68-
cfg->setFlag(nvinfer1::BuilderFlag::kINT8);
69-
if (!settings.strict_types) {
63+
for (auto p = settings.enabled_precisions.begin(); p != settings.enabled_precisions.end(); ++p) {
64+
switch (*p) {
65+
case nvinfer1::DataType::kHALF:
66+
TRTORCH_CHECK(builder->platformHasFastFp16(), "Requested inference in FP16 but platform does not support FP16");
7067
cfg->setFlag(nvinfer1::BuilderFlag::kFP16);
71-
}
72-
input_type = nvinfer1::DataType::kFLOAT;
73-
TRTORCH_CHECK(
74-
settings.calibrator != nullptr,
75-
"Requested inference in INT8 but no calibrator provided, set the ptq_calibrator field in the CompileSpec struct with your calibrator");
76-
cfg->setInt8Calibrator(settings.calibrator);
77-
break;
78-
case nvinfer1::DataType::kFLOAT:
79-
default:
80-
input_type = nvinfer1::DataType::kFLOAT;
81-
break;
68+
break;
69+
case nvinfer1::DataType::kINT8:
70+
TRTORCH_CHECK(builder->platformHasFastInt8(), "Requested inference in INT8 but platform does not support INT8");
71+
cfg->setFlag(nvinfer1::BuilderFlag::kINT8);
72+
TRTORCH_CHECK(
73+
settings.calibrator != nullptr,
74+
"Requested inference in INT8 but no calibrator provided, set the ptq_calibrator field in the CompileSpec struct with your calibrator");
75+
cfg->setInt8Calibrator(settings.calibrator);
76+
break;
77+
case nvinfer1::DataType::kFLOAT:
78+
break;
79+
case nvinfer1::DataType::kINT32:
80+
case nvinfer1::DataType::kBOOL:
81+
default:
82+
TRTORCH_THROW_ERROR(
83+
"Requested kernel precision that is unsupported: " << *p << " options are float, half, int8");
84+
}
8285
}
83-
op_precision = settings.op_precision;
86+
87+
enabled_precisions = settings.enabled_precisions;
8488

8589
if (settings.disable_tf32) {
8690
cfg->clearFlag(nvinfer1::BuilderFlag::kTF32);
@@ -118,7 +122,9 @@ ConversionCtx::ConversionCtx(BuilderSettings build_settings)
118122
static_cast<int>(settings.device.dla_core) < nbDLACores,
119123
"Configured DLA Core ID: " << settings.device.dla_core
120124
<< " not available. Total number of available DLA Cores: " << nbDLACores);
121-
TRTORCH_CHECK(settings.op_precision != nvinfer1::DataType::kFLOAT, "DLA supports only fp16 or int8 precision");
125+
TRTORCH_CHECK(
126+
settings.enabled_precisions.find(nvinfer1::DataType::kFLOAT) == settings.enabled_precisions.end(),
127+
"DLA supports only fp16 or int8 precision");
122128
cfg->setDLACore(settings.device.dla_core);
123129
}
124130
}

core/conversion/conversionctx/ConversionCtx.h

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#include <map>
44
#include <memory>
5+
#include <set>
56
#include <unordered_map>
67

78
#include "NvInfer.h"
@@ -23,7 +24,8 @@ struct Device {
2324
};
2425

2526
struct BuilderSettings {
26-
nvinfer1::DataType op_precision = nvinfer1::DataType::kFLOAT;
27+
std::set<nvinfer1::DataType> enabled_precisions = {nvinfer1::DataType::kFLOAT};
28+
std::vector<nvinfer1::DataType> input_dtypes;
2729
bool disable_tf32 = false;
2830
bool refit = false;
2931
bool debug = false;
@@ -57,8 +59,7 @@ struct ConversionCtx {
5759
nvinfer1::IBuilder* builder;
5860
nvinfer1::INetworkDefinition* net;
5961
nvinfer1::IBuilderConfig* cfg;
60-
nvinfer1::DataType input_type;
61-
nvinfer1::DataType op_precision;
62+
std::set<nvinfer1::DataType> enabled_precisions;
6263
BuilderSettings settings;
6364
util::logging::TRTorchLogger logger;
6465
// Pointers to data that needs to remain alive until conversion is done

core/conversion/converters/impl/activation.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ auto acthardtanh TRTORCH_UNUSED =
177177
std::string pluginName = "CustomGeluPluginDynamic";
178178
nvinfer1::PluginFieldCollection fc;
179179
std::vector<nvinfer1::PluginField> f;
180-
int type_id = ctx->settings.op_precision == nvinfer1::DataType::kFLOAT
180+
// REVIEW is this right?
181+
int type_id = ctx->settings.enabled_precisions.find(nvinfer1::DataType::kHALF) ==
182+
ctx->settings.enabled_precisions.end()
181183
? 0
182184
: 1; // Integer encoding the DataType (0: FP32, 1: FP16)
183185
f.emplace_back(nvinfer1::PluginField("type_id", &type_id, nvinfer1::PluginFieldType::kINT32, 1));

core/ir/BUILD

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ cc_library(
1313
"ir.h"
1414
],
1515
srcs = [
16-
"InputRange.cpp",
16+
"Input.cpp"
1717
],
1818
deps = [
1919
"@tensorrt//:nvinfer",

0 commit comments

Comments
 (0)