Skip to content

Support calling custom method names on PyTorch module #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -176,6 +176,20 @@ key: "ENABLE_CACHE_CLEANING"
}
```

* `MODULE_METHOD_NAME`: String flag to specify which method on the PyTorch model is being called.
Default value is `forward`.

The section of model config file specifying this parameter will look like:

```
parameters: {
key: "MODULE_METHOD_NAME"
value: {
string_value:"custom_method"
}
}
```

* Additional Optimizations: Three additional boolean parameters are available to disable
certain Torch optimizations that can sometimes cause latency regressions in models with
complex execution modes and dynamic shapes. If not specified, all are enabled by default.
65 changes: 58 additions & 7 deletions src/libtorch.cc
Original file line number Diff line number Diff line change
@@ -56,6 +56,9 @@
#include <cuda_runtime_api.h>
#endif // TRITON_ENABLE_GPU

// Default forward method to call on PyTorch modules
const std::string DEFAULT_MODULE_METHOD_NAME = "forward";

//
// PyTorch C++ (LibTorch) Backend that implements the TRITONBACKEND API.
//
@@ -105,6 +108,7 @@ class ModelState : public BackendModel {
{
return model_outputs_;
}
const std::string& ModuleMethodName() { return module_method_name_; }

private:
ModelState(TRITONBACKEND_Model* triton_model);
@@ -147,6 +151,10 @@ class ModelState : public BackendModel {
// is specified both in the output section and state section, it indicates
// that the backend must return the output state to the client too.
std::map<std::string, std::pair<int64_t, int64_t>> model_outputs_;

// Method to call on PyTorch Module.
// Defaults to DEFAULT_MODULE_METHOD_NAME.
std::string module_method_name_;
};

TRITONSERVER_Error*
@@ -224,7 +232,8 @@ ModelState::ModelState(TRITONBACKEND_Model* triton_model)
enable_inference_mode_(true), enable_cache_cleaning_(false),
enable_weight_sharing_(false), enable_tensor_fuser_pair_({false, true}),
enable_jit_profiling_pair_({false, true}),
enable_jit_executor_pair_({false, true})
enable_jit_executor_pair_({false, true}),
module_method_name_(DEFAULT_MODULE_METHOD_NAME)
{
}

@@ -465,6 +474,30 @@ ModelState::ParseParameters()
" for model instance '" + Name() + "'")
.c_str());
}

// If 'MODULE_METHOD_NAME' is not present in 'parameters' then
// 'module_method_name_' is set to 'DEFAULT_MODULE_METHOD_NAME' ('forward').
std::string module_method_name = DEFAULT_MODULE_METHOD_NAME;
err = GetParameterValue(params, "MODULE_METHOD_NAME", &module_method_name);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("module_method_name is not specified") +
" for model instance '" + Name() + "'")
.c_str());
TRITONSERVER_ErrorDelete(err);
}
} else {
module_method_name_ = module_method_name;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("module_method_name is ") + module_method_name_ +
" for model instance '" + Name() + "'")
.c_str());
}
}

return nullptr;
@@ -886,7 +919,19 @@ ModelInstanceState::ValidateInputs(const size_t expected_input_cnt)
// configuration specifies only those.
std::vector<std::string> allowed_inputs;

const torch::jit::Method& method = torch_model_->get_method("forward");
// First check if method exists in the model and throw an error if absent
const auto methodNameToExecute = model_state_->ModuleMethodName();
const auto optionalMethodHandle = torch_model_->find_method(methodNameToExecute);
if (!optionalMethodHandle.has_value()) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("unable to find method '") +
methodNameToExecute + "' in model '" + model_path_ + "'")
.c_str());
}

// Get the method schema and validate the inputs
const torch::jit::Method& method = optionalMethodHandle.value();
const auto& schema = method.function().getSchema();
const std::vector<c10::Argument>& arguments = schema.arguments();

@@ -1529,18 +1574,24 @@ ModelInstanceState::Execute(
torch::NoGradGuard no_grad;

// If input is a dictionary, prepare dictionary from 'input_tensors'.
std::string module_method_name = model_state_->ModuleMethodName();
std::vector<c10::IValue> inputs;
if (is_dict_input_) {
torch::Dict<std::string, torch::Tensor> input_dict;
c10::Dict<std::string, at::Tensor> dict;
for (auto& input_index : input_index_map_) {
torch::jit::IValue ival = (*input_tensors)[input_index.second];
input_dict.insert(input_index.first, ival.toTensor());
dict.insert(input_index.first, ival.toTensor());
}
std::vector<torch::jit::IValue> input_dict_ivalue = {input_dict};
model_outputs_ = torch_model_->forward(input_dict_ivalue);
inputs.push_back(dict);
} else {
model_outputs_ = torch_model_->forward(*input_tensors);
for (auto& input_tensor : *input_tensors) {
inputs.push_back(input_tensor.toTensor());
}
}

// Actually run the method on the model.
model_outputs_ = torch_model_->get_method(module_method_name)(inputs);

if (model_outputs_.isTuple()) {
auto model_outputs_tuple = model_outputs_.toTuple();
size_t op_index = 0;