Repository navigation
[Dynamic shapes 6/n] Mark the dynamic dimensions of compiled predictions in one place #1375
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
aw471
wants to merge
5
commits into
main
Choose a base branch
from
compile-dynamic-shapes
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.
+189
−15
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5ee91d5
Skip automatic chunking in compiled code
aw471 9da709d
Mark the dynamic dimensions of compiled predictions in one place
aw471 5c0e2f9
Apply the compiled prediction wrapper to any declared dynamic shapes
aw471 66b7b58
Keep single-row queries as they are when callbacks are passed
aw471 901aa7d
Let callers compile predictions without dynamic shapes
aw471 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 |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Dynamic shapes of a compiled :meth:`~sdm.models.ICLModel.predict`.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Callable | ||
| from dataclasses import dataclass | ||
| from typing import TYPE_CHECKING, Any, TypeVar | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
| from sdm import TableTensor | ||
|
|
||
| if TYPE_CHECKING: | ||
| from sdm.models.base.icl import ICLModel | ||
|
|
||
| ModelT = TypeVar("ModelT", bound="ICLModel") | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class DynamicShapes: | ||
| r"""The dimensions that a compiled graph of a model keeps dynamic. | ||
|
|
||
| A model declares them with :func:`dynamic_shapes`, and | ||
| :func:`compile_predict` marks them. | ||
| """ | ||
|
|
||
| #: The dimensions of the query. Rows (``-2``) require that the model and | ||
| #: its recipe predict every query row independently of the other rows. | ||
| query: tuple[int, ...] = () | ||
|
|
||
|
|
||
| def dynamic_shapes(**dims: Any) -> Callable[[type[ModelT]], type[ModelT]]: | ||
| r"""Declare the :class:`DynamicShapes` of a model. | ||
|
|
||
| Args: | ||
| **dims: The fields of :class:`DynamicShapes`. | ||
| """ | ||
|
|
||
| def decorator(cls: type[ModelT]) -> type[ModelT]: | ||
| cls._dynamic_shapes = DynamicShapes(**dims) | ||
| return cls | ||
|
|
||
| return decorator | ||
|
|
||
|
|
||
| def compile_predict( | ||
| model: ICLModel, | ||
| dynamic_shapes: bool = True, | ||
| **kwargs: Any, | ||
| ) -> Callable[..., TableTensor]: | ||
| r"""Compile ``model.predict`` using :func:`torch.compile`. | ||
|
|
||
| One graph serves queries of any size along the :class:`DynamicShapes` | ||
| that ``model`` declares. Empty queries are predicted without the graph. | ||
|
|
||
| Args: | ||
| model: The model. | ||
| dynamic_shapes: If set to ``False``, no dimension is dynamic, for | ||
| callers whose queries always have the same shape. | ||
| **kwargs: Keyword arguments passed to :func:`torch.compile`. | ||
| ``isolate_recompiles`` defaults to ``True``, since all models | ||
| would otherwise share one recompile limit. | ||
| """ | ||
| kwargs = {"isolate_recompiles": True} | kwargs | ||
| compiled = torch.compile(model.predict, **kwargs) | ||
| shapes = model._dynamic_shapes if dynamic_shapes else DynamicShapes() | ||
| # Without dynamic shapes, none of the steps below are needed. | ||
| if shapes == DynamicShapes(): | ||
| return compiled | ||
|
|
||
| def predict( | ||
| x: Tensor | TableTensor, # [..., R, D] | ||
| *args: Any, | ||
| **kwargs: Any, | ||
| ) -> TableTensor: | ||
| rows = x.size(-2) | ||
| if rows == 0: | ||
| return model.predict(x, *args, **kwargs) | ||
| # A graph specializes on sizes of zero and one, so a single row is | ||
| # repeated if the rows are dynamic, unless callbacks see the rows. A | ||
| # contiguous copy has one memory layout for any view. | ||
| repeat = ( | ||
| rows == 1 and -2 in shapes.query and not kwargs.get("callbacks") | ||
| ) | ||
| x = ( | ||
| torch.cat([x, x], dim=-2) | ||
| if repeat | ||
| else x.clone(memory_format=torch.contiguous_format) | ||
| ) | ||
| _mark_dynamic(x, shapes.query) | ||
| out = compiled(x, *args, **kwargs) | ||
| return out[..., :1, :] if repeat else out | ||
|
|
||
| return predict | ||
|
|
||
|
|
||
| def _mark_dynamic(tensor: Tensor, dims: tuple[int, ...]) -> None: | ||
| for dim in dims: | ||
| dim %= tensor.dim() | ||
| if isinstance(tensor, TableTensor): | ||
| tensor._mark_dynamic(dim) | ||
| else: | ||
| torch._dynamo.mark_dynamic(tensor, dim) |
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
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
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
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.
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.
Mark the ID columns dynamic, not only the
ColumnarTensorwrapper.TableTensor._mark_dynamiccallstorch._dynamo.mark_dynamic(self, dim). For traceable wrapper subclasses, PyTorch propagates the mark only to inner tensors with the samedim()as the outer tensor.self._idpasses this test. Its columns have one less dimension, so they are skipped and stay static underdynamic=False.When a query has a non-empty ID block,
ColumnarTensor.__tensor_unflatten__builds the block withsize=outer_size[:-1].ColumnarTensor.__new__then compares each static column size with that symbolic size. This may specialize the marked row dimension. Underfullgraph=True, the marked dimension uses a non-warning constraint, so the compile may raise instead of reusing one graph for different row counts.Mark the row dimension of each ID column explicitly, so the ID columns share the row symbol with the outer tensor. Update the comment at line 976 so it does not state that the mark reaches every block.