-
Notifications
You must be signed in to change notification settings - Fork 18
#343: Support collections of tensors in args/kwargs for compile #701
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
akhilg-nv
wants to merge
5
commits into
main
Choose a base branch
from
dev-akhilg-230-collections-compile
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.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
48b5d7d
#230: Support collections of tensors in args/kwargs for compile
akhilg-nv 87ecff6
improve tests, review fixes
akhilg-nv e924c8b
Cache inputinfo structure at compile time, improve test coverage
akhilg-nv 923cec5
Update serialization and deserialization
akhilg-nv 4831cf1
fix missing tensor in stack info for shape mismatch
akhilg-nv 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
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 | ||||
|---|---|---|---|---|---|---|
|
|
@@ -46,6 +46,7 @@ def __init__( | |||||
| arg_names, | ||||||
| return_single_tensor_as_sequence: bool, | ||||||
| input_infos: Dict[str, Union[InputInfo, DimensionInputInfo]], | ||||||
| leaf_names_by_arg: Dict[str, Sequence[str]], | ||||||
| ): | ||||||
| self._executable = executable | ||||||
|
|
||||||
|
|
@@ -78,6 +79,8 @@ def __init__( | |||||
| Stores metadata, like shapes and data types, for each input to the executable. | ||||||
| """ | ||||||
|
|
||||||
| self._leaf_names_by_arg = leaf_names_by_arg | ||||||
|
|
||||||
| def __str__(self) -> str: | ||||||
| params = [ | ||||||
| f"{name}: {str_from_type_annotation(param.annotation)}" | ||||||
|
|
@@ -195,20 +198,67 @@ def add(a, b): | |||||
| ], | ||||||
| ) | ||||||
|
|
||||||
| # Build a name->tensor map using precomputed leaf names to avoid unnecessary recursion | ||||||
| input_info_names = list(self.input_infos.keys()) | ||||||
| name_to_tensor: Dict[str, Tensor] = {} | ||||||
|
|
||||||
| def extract_recursive(value, name_prefix, allowed_names): | ||||||
| if name_prefix in allowed_names: | ||||||
| name_to_tensor[name_prefix] = value | ||||||
| return | ||||||
| if isinstance(value, dict): | ||||||
| for key, item in value.items(): | ||||||
| nested_name = f"{name_prefix}.{key}" | ||||||
| extract_recursive(item, nested_name, allowed_names) | ||||||
| elif isinstance(value, (list, tuple)): | ||||||
| for idx, item in enumerate(value): | ||||||
| nested_name = f"{name_prefix}[{idx}]" | ||||||
| extract_recursive(item, nested_name, allowed_names) | ||||||
| else: | ||||||
| return | ||||||
|
|
||||||
| for name_idx, tensor in enumerate(input_tensors): | ||||||
| arg_name = self._arg_names[name_idx] | ||||||
| # Fast path: direct leaf input | ||||||
| if arg_name in self.input_infos: | ||||||
| name_to_tensor[arg_name] = tensor | ||||||
| continue | ||||||
| # If this arg has no compiled leaves beneath it, skip any recursion | ||||||
| allowed = self._leaf_names_by_arg.get(arg_name) | ||||||
| if not allowed: | ||||||
| continue | ||||||
| extract_recursive(tensor, arg_name, set(allowed)) | ||||||
| try: | ||||||
| flattened_tensors = [name_to_tensor[name] for name in input_info_names] | ||||||
| except KeyError as missing: | ||||||
| raise_error( | ||||||
| f"Missing runtime tensor for input `{missing.args[0]}`.", | ||||||
| [ | ||||||
| "Ensure your provided containers include tensors for all compiled inputs.", | ||||||
|
Collaborator
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.
Suggested change
|
||||||
| f"Expected inputs: {input_info_names}", | ||||||
| ], | ||||||
| ) | ||||||
| expected_devices = ["gpu" if isinstance(info, InputInfo) else "cpu" for info in self.input_infos.values()] | ||||||
| for tensor, expected_device, arg_name in zip(input_tensors, expected_devices, self._arg_names): | ||||||
|
|
||||||
| # Validate flattened tensors against input_infos | ||||||
| if len(flattened_tensors) != len(expected_devices): | ||||||
| raise_error( | ||||||
| f"Mismatch between number of flattened tensors ({len(flattened_tensors)}) and expected inputs ({len(expected_devices)})." | ||||||
| ) | ||||||
|
|
||||||
| for tensor, expected_device, info_name in zip(flattened_tensors, expected_devices, self.input_infos.keys()): | ||||||
| producer = tensor.trace_tensor.producer | ||||||
| if not isinstance(producer, Constant): | ||||||
| raise_error(f"Tensor `{arg_name}` is not evaluated.", ["Hint: Try calling `.eval()` on the tensor."]) | ||||||
| raise_error(f"Tensor `{info_name}` is not evaluated.", ["Hint: Try calling `.eval()` on the tensor."]) | ||||||
| if tensor.device.kind != expected_device: | ||||||
| raise_error( | ||||||
| "Unexpected tensor device.", | ||||||
| [ | ||||||
| f"For tensor: `{arg_name}`, expected to be on device: {expected_device} but got: {tensor.device.kind}.\n", | ||||||
| f"For tensor: `{info_name}`, expected to be on device: {expected_device} but got: {tensor.device.kind}.\n", | ||||||
| ], | ||||||
| ) | ||||||
|
|
||||||
| input_memrefs = [inp.trace_tensor.producer.data for inp in input_tensors] | ||||||
| input_memrefs = [inp.trace_tensor.producer.data for inp in flattened_tensors] | ||||||
| try: | ||||||
| output_memrefs = self._session.execute_function( | ||||||
| "main", in_args=input_memrefs, stream=self.stream._active_cuda_stream, client=self._runtime_client | ||||||
|
|
@@ -222,7 +272,7 @@ def add(a, b): | |||||
| expected_input_dtypes = [ | ||||||
| info.dtype if isinstance(info, InputInfo) else int32 for info in self.input_infos.values() | ||||||
| ] | ||||||
| for tensor, dtype, arg_name in zip(input_tensors, expected_input_dtypes, self._arg_names): | ||||||
| for tensor, dtype, arg_name in zip(flattened_tensors, expected_input_dtypes, self.input_infos.keys()): | ||||||
| if tensor.dtype != dtype: | ||||||
| raise_error( | ||||||
| f"Unexpected tensor data type.", | ||||||
|
|
@@ -237,7 +287,9 @@ def add(a, b): | |||||
| expected_input_shapes = [ | ||||||
| info.shape_bounds if isinstance(info, InputInfo) else tuple() for info in self.input_infos.values() | ||||||
| ] | ||||||
| for tensor, expected_bounds, arg_name in zip(input_tensors, expected_input_shapes, self._arg_names): | ||||||
| for tensor, expected_bounds, arg_name in zip( | ||||||
| flattened_tensors, expected_input_shapes, self.input_infos.keys() | ||||||
| ): | ||||||
| shape = tensor.shape | ||||||
|
|
||||||
| if len(shape) != len(expected_bounds.min): | ||||||
|
|
@@ -346,6 +398,7 @@ def encode_executable(executable): | |||||
| "executable": base64.b64encode(executable._executable.serialize()).decode(), | ||||||
| "_return_single_tensor_as_sequence": executable._return_single_tensor_as_sequence, | ||||||
| "input_infos": executable.input_infos, | ||||||
| "leaf_names_by_arg": executable._leaf_names_by_arg, | ||||||
| } | ||||||
|
|
||||||
|
|
||||||
|
|
@@ -357,4 +410,5 @@ def decode_executable(executable_dict): | |||||
| executable_dict["arg_names"], | ||||||
| return_single_tensor_as_sequence=executable_dict["_return_single_tensor_as_sequence"], | ||||||
| input_infos=executable_dict["input_infos"], | ||||||
| leaf_names_by_arg=executable_dict.get("leaf_names_by_arg"), | ||||||
| ) | ||||||
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
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.
We should actually know how to access the tensors within each collection at compile-time. I'm wondering if we can just build accessor lambas which will provide a fast way to directly access the right values. When we compile, we could create a mapping of trace input names to functions that will retrieve the necessary argument from the raw inputs - basically, we'd use it like so:
At compile time, we'd want to recursively build up this accessor map (probably just by adding an extra return value that's a dictionary of accessor functions). The most efficient way would probably be to build strings like:
"inp['key_1'][5]['key_2'][3]"and then
evalthem into callables (the alternative would be to return a recursive chain of lambdas, but the string approach avoids recursive calls).This way we can remove all the name parsing logic and avoid looping over the collection inputs entirely.