-
Notifications
You must be signed in to change notification settings - Fork 62
Add support where torchscript model outputs a dictionary of tensors #174
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
Draft
chdhr-harshal
wants to merge
3
commits into
triton-inference-server:main
Choose a base branch
from
chdhr-harshal:hc-support-dict-output
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| name: "dict_model" | ||
| platform: "pytorch_libtorch" | ||
| max_batch_size: 8 | ||
|
|
||
| input [ | ||
| { | ||
| name: "INPUT__0" | ||
| data_type: TYPE_FP32 | ||
| dims: [ 10 ] | ||
| } | ||
| ] | ||
|
|
||
| output [ | ||
| { | ||
| name: "logits" | ||
| data_type: TYPE_FP32 | ||
| dims: [ 20 ] | ||
| }, | ||
| { | ||
| name: "embeddings" | ||
| data_type: TYPE_FP32 | ||
| dims: [ 5 ] | ||
| } | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,6 +52,7 @@ ModelInstanceState::ModelInstanceState( | |
| ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance) | ||
| : BackendModelInstance(model_state, triton_model_instance), | ||
| model_state_(model_state), device_(torch::kCPU), is_dict_input_(false), | ||
| dict_output_validated_(false), | ||
| device_cnt_(0) | ||
| { | ||
| if (Kind() == TRITONSERVER_INSTANCEGROUPKIND_GPU) { | ||
|
|
@@ -149,6 +150,47 @@ ModelInstanceState::ModelInstanceState( | |
| THROW_IF_BACKEND_INSTANCE_ERROR(ValidateOutputs()); | ||
| } | ||
|
|
||
| TRITONSERVER_Error* | ||
| ModelInstanceState::ValidateAndCacheDictOutput( | ||
| const c10::Dict<c10::IValue, c10::IValue>& dict_output) | ||
| { | ||
| if (dict_output_validated_.load(std::memory_order_acquire)) { | ||
| return nullptr; | ||
| } | ||
| std::lock_guard<std::mutex> lock(dict_validation_mutex_); | ||
| if (dict_output_validated_.load(std::memory_order_acquire)) { | ||
| return nullptr; | ||
| } | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Need to use double checking with mutex to make validation threadsafe. |
||
| if (dict_output.size() == 0) { | ||
| return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, "Empty dict"); | ||
| } | ||
| std::vector<std::string> temp_keys; | ||
| std::unordered_map<std::string, size_t> temp_index; | ||
| size_t idx = 0; | ||
| for (auto it = dict_output.begin(); it != dict_output.end(); ++it) { | ||
| std::string key = it->key().toStringRef(); | ||
| if (!it->value().isTensor()) { | ||
| return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, "Not tensor"); | ||
| } | ||
| temp_keys.push_back(key); | ||
| temp_index[key] = idx++; | ||
| } | ||
| std::vector<std::string> missing; | ||
| for (auto& output : model_state_->ModelOutputs()) { | ||
| if (temp_index.find(output.first) == temp_index.end()) { | ||
| missing.push_back(output.first); | ||
| } | ||
| } | ||
| if (!missing.empty()) { | ||
| return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, "Missing keys"); | ||
| } | ||
| output_dict_keys_ = std::move(temp_keys); | ||
| output_dict_key_to_index_ = std::move(temp_index); | ||
| dict_output_validated_.store(true, std::memory_order_release); | ||
| return nullptr; | ||
| } | ||
|
|
||
|
|
||
| ModelInstanceState::~ModelInstanceState() | ||
| { | ||
| torch_model_.reset(); | ||
|
|
@@ -345,6 +387,18 @@ ModelInstanceState::Execute( | |
| list_output.elementType()->str() + "]"); | ||
| } | ||
| output_tensors->push_back(model_outputs_); | ||
| } else if (model_outputs_.isGenericDict()) { | ||
| auto dict_output = model_outputs_.toGenericDict(); | ||
| if (!dict_output_validated_.load(std::memory_order_acquire)) { | ||
| TRITONSERVER_Error* err = ValidateAndCacheDictOutput(dict_output); | ||
| if (err != nullptr) { | ||
| SendErrorForResponses(responses, request_count, err); | ||
| return; | ||
| } | ||
| } | ||
| for (const auto& key : output_dict_keys_) { | ||
| output_tensors->push_back(dict_output.at(key)); | ||
| } | ||
| } else { | ||
| throw std::invalid_argument( | ||
| "output must be of type Tensor, List[str] or Tuple containing one of " | ||
|
|
@@ -872,7 +926,14 @@ ModelInstanceState::ReadOutputTensors( | |
| // The serialized string buffer must be valid until output copies are done | ||
| std::vector<std::unique_ptr<std::string>> string_buffer; | ||
| for (auto& output : model_state_->ModelOutputs()) { | ||
| // Use dict key mapping if available | ||
| int op_index = output_index_map_[output.first]; | ||
| if (dict_output_validated_.load(std::memory_order_acquire)) { | ||
| auto it = output_dict_key_to_index_.find(output.first); | ||
| if (it != output_dict_key_to_index_.end()) { | ||
| op_index = it->second; | ||
| } | ||
| } | ||
| auto name = output.first; | ||
| auto output_tensor_pair = output.second; | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # test_client.py | ||
| import tritonclient.http as httpclient | ||
| import numpy as np | ||
|
|
||
| # Create client | ||
| client = httpclient.InferenceServerClient(url="localhost:8000") | ||
|
|
||
| # Prepare input | ||
| input_data = np.random.randn(5, 10).astype(np.float32) | ||
| inputs = [httpclient.InferInput("INPUT__0", input_data.shape, "FP32")] | ||
| inputs[0].set_data_from_numpy(input_data) | ||
|
|
||
| # Request outputs by dict key names | ||
| outputs = [ | ||
| httpclient.InferRequestedOutput("logits"), | ||
| httpclient.InferRequestedOutput("embeddings") | ||
| ] | ||
|
|
||
| # Infer | ||
| results = client.infer("dict_model", inputs, outputs=outputs) | ||
|
|
||
| # Check output names | ||
| print("Output names:", results.get_response()) | ||
| print("Logits shape:", results.as_numpy("logits").shape) | ||
| print("Embeddings shape:", results.as_numpy("embeddings").shape) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # test_model.py | ||
| import torch | ||
| import torch.nn as nn | ||
|
|
||
| class DictOutputModel(nn.Module): | ||
| def __init__(self): | ||
| super().__init__() | ||
| self.fc1 = nn.Linear(10, 50) | ||
| self.fc2 = nn.Linear(50, 20) | ||
| self.fc3 = nn.Linear(50, 5) | ||
|
|
||
| def forward(self, x): | ||
| features = self.fc1(x) | ||
| logits = self.fc2(features) | ||
| embeddings = self.fc3(features) | ||
|
|
||
| # Return dictionary | ||
| return { | ||
| "logits": logits, | ||
| "embeddings": embeddings | ||
| } | ||
|
|
||
| # Create and save model | ||
| model = DictOutputModel() | ||
| model.eval() | ||
|
|
||
| # Trace with example input | ||
| example_input = torch.randn(1, 10) | ||
| traced_model = torch.jit.trace(model, example_input, strict=False) | ||
|
|
||
| # Save | ||
| torch.jit.save(traced_model, "model.pt") | ||
| print("Model saved!") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removing this temporarily because I don't have GPU on my personal machine.