Skip to content

Commit 9503673

Browse files
committed
replacing named_dims with shared_dims
1 parent 5c564c2 commit 9503673

3 files changed

Lines changed: 40 additions & 40 deletions

File tree

py/torch_tensorrt/_Input.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class _ShapeMode(Enum):
5151
torch_tensor: torch.Tensor = None
5252
name: str = ""
5353
is_shape_tensor: bool = False
54-
name_dims: Dict[int, str] = (
54+
shared_dims: Dict[int, str] = (
5555
{}
5656
) #: Optional {axis_index: name} for dynamic axes. The same name across inputs is exported as one shared ``torch.export.Dim`` (e.g. a batch axis shared by ``input_ids`` and ``attention_mask``).
5757

@@ -165,19 +165,19 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
165165
"if you try to run inference with empty tensor inputs."
166166
)
167167

168-
if "name_dims" in kwargs and kwargs["name_dims"]:
169-
self.name_dims = Input._parse_name_dims(
170-
kwargs["name_dims"], self.shape
168+
if "shared_dims" in kwargs and kwargs["shared_dims"]:
169+
self.shared_dims = Input._parse_shared_dims(
170+
kwargs["shared_dims"], self.shape
171171
)
172172

173173
else:
174174
raise ValueError(
175175
f"Unexpected number of positional arguments for class Input \n Found {len(args)} arguments, expected either zero or a single positional arguments"
176176
)
177177

178-
if kwargs.get("name_dims") and self.shape_mode != Input._ShapeMode.DYNAMIC:
178+
if kwargs.get("shared_dims") and self.shape_mode != Input._ShapeMode.DYNAMIC:
179179
raise ValueError(
180-
"name_dims is only valid for dynamic inputs (min_shape/opt_shape/max_shape); "
180+
"shared_dims is only valid for dynamic inputs (min_shape/opt_shape/max_shape); "
181181
"it has no meaning for a statically shaped Input."
182182
)
183183

@@ -276,29 +276,29 @@ def equivalent_spec(a: Input, b: Input) -> bool:
276276
return all(checks)
277277

278278
@staticmethod
279-
def _parse_name_dims(
280-
name_dims: Any, shape: Dict[str, Tuple[int, ...]]
279+
def _parse_shared_dims(
280+
shared_dims: Any, shape: Dict[str, Tuple[int, ...]]
281281
) -> Dict[int, str]:
282-
"""Validate and normalize the ``name_dims`` mapping ({axis: name}).
282+
"""Validate and normalize the ``shared_dims`` mapping ({axis: name}).
283283
284284
Each named axis must be a valid index into the shape and must be
285285
genuinely dynamic (``min != max``); a static axis cannot vary, so naming
286286
it for cross-input sharing is a user error.
287287
"""
288-
if not isinstance(name_dims, dict):
288+
if not isinstance(shared_dims, dict):
289289
raise TypeError(
290-
f"name_dims must be a dict of {{axis_index: name}}, got {type(name_dims)}"
290+
f"shared_dims must be a dict of {{axis_index: name}}, got {type(shared_dims)}"
291291
)
292292
rank = len(shape["min_shape"])
293293
parsed: Dict[int, str] = {}
294-
for axis, dim_name in name_dims.items():
294+
for axis, dim_name in shared_dims.items():
295295
if not isinstance(axis, int) or not (0 <= axis < rank):
296296
raise ValueError(
297-
f"name_dims key {axis!r} is not a valid axis index for an input of rank {rank}"
297+
f"shared_dims key {axis!r} is not a valid axis index for an input of rank {rank}"
298298
)
299299
if not isinstance(dim_name, str) or not dim_name:
300300
raise ValueError(
301-
f"name_dims value for axis {axis} must be a non-empty string, got {dim_name!r}"
301+
f"shared_dims value for axis {axis} must be a non-empty string, got {dim_name!r}"
302302
)
303303
if shape["min_shape"][axis] == shape["max_shape"][axis]:
304304
raise ValueError(

py/torch_tensorrt/dynamo/_tracer.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def trace(
7373
device = to_torch_device(kwargs.get("device", default_device()))
7474
torch_arg_inputs = get_torch_inputs(arg_inputs, device)
7575
torch_kwarg_inputs = get_torch_inputs(kwarg_inputs, device)
76-
# Build dynamic shapes from the Input objects. Inputs carrying name_dims
76+
# Build dynamic shapes from the Input objects. Inputs carrying shared_dims
7777
# share a Dim across inputs via the registry; the rest get an independent
7878
# per-input Dim.
7979
dim_registry = build_dim_registry(arg_inputs, kwarg_inputs)
@@ -108,7 +108,7 @@ def _collect_inputs(obj: Any) -> list[Input]:
108108

109109

110110
def build_dim_registry(arg_inputs: Any, kwarg_inputs: Any) -> dict[str, Any]:
111-
"""Build a ``{name: torch.export.Dim}`` registry from Input.name_dims.
111+
"""Build a ``{name: torch.export.Dim}`` registry from Input.shared_dims.
112112
113113
The same name appearing on multiple inputs yields a single shared ``Dim``
114114
instance, so ``torch.export`` treats those axes as one symbol. Conflicting
@@ -117,13 +117,13 @@ def build_dim_registry(arg_inputs: Any, kwarg_inputs: Any) -> dict[str, Any]:
117117
registry: dict[str, Any] = {}
118118
bounds: dict[str, tuple[int, int]] = {}
119119
for inp in _collect_inputs(arg_inputs) + _collect_inputs(kwarg_inputs):
120-
name_dims = getattr(inp, "name_dims", None)
121-
if not name_dims or inp.shape_mode != Input._ShapeMode.DYNAMIC:
120+
shared_dims = getattr(inp, "shared_dims", None)
121+
if not shared_dims or inp.shape_mode != Input._ShapeMode.DYNAMIC:
122122
continue
123123
assert isinstance(inp.shape, dict)
124124
min_shape = inp.shape["min_shape"]
125125
max_shape = inp.shape["max_shape"]
126-
for axis, dim_name in name_dims.items():
126+
for axis, dim_name in shared_dims.items():
127127
lo, hi = int(min_shape[axis]), int(max_shape[axis])
128128
if dim_name in bounds:
129129
if bounds[dim_name] != (lo, hi):
@@ -184,15 +184,15 @@ def get_dynamic_shapes(
184184
min_shape = input.shape["min_shape"]
185185
opt_shape = input.shape["opt_shape"]
186186
max_shape = input.shape["max_shape"]
187-
name_dims = getattr(input, "name_dims", None) or {}
187+
shared_dims = getattr(input, "shared_dims", None) or {}
188188
assert len(min_shape) == len(opt_shape) == len(max_shape)
189189
for dim in range(len(min_shape)):
190190
if min_shape[dim] == opt_shape[dim] == max_shape[dim]:
191191
continue
192-
elif dim_registry is not None and dim in name_dims:
192+
elif dim_registry is not None and dim in shared_dims:
193193
# Named axis: reuse the shared Dim so axes with the same
194194
# name across inputs become a single exported symbol.
195-
dynamic_dims[dim] = dim_registry[name_dims[dim]]
195+
dynamic_dims[dim] = dim_registry[shared_dims[dim]]
196196
else:
197197
dynamic_dims[dim] = Dim(
198198
input.name + "_" + str(dim),

tests/py/dynamo/models/test_shared_dynamic_dim.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# type: ignore
22
"""
3-
Tests for sharing a dynamic dimension across inputs via ``Input(name_dims=...)``.
3+
Tests for sharing a dynamic dimension across inputs via ``Input(shared_dims=...)``.
44
55
Background: when a model takes multiple inputs whose dynamic axes must be
66
**equal at runtime** (e.g. HF encoders with ``input_ids`` / ``attention_mask``
@@ -9,7 +9,7 @@
99
constraint check for any forward() that broadcasts across those axes (here:
1010
``embed(input_ids) * mask.unsqueeze(-1)``), raising ``ConstraintViolationError``.
1111
12-
``Input(name_dims={axis: name})`` lets the caller tag a dynamic axis with a
12+
``Input(shared_dims={axis: name})`` lets the caller tag a dynamic axis with a
1313
name; the same name across inputs is exported as a single shared ``Dim``. All
1414
the dynamic-shape intent lives on the ``Input`` objects -- no separate
1515
``dynamic_shapes`` argument and no ``torch.export`` knowledge required at the
@@ -54,14 +54,14 @@ def _named_input(name: str, seq: int = 16, batch_min: int = 1, batch_max: int =
5454
max_shape=(batch_max, seq),
5555
dtype=torch.int64,
5656
name=name,
57-
name_dims={0: "B"},
57+
shared_dims={0: "B"},
5858
)
5959

6060

6161
@pytest.mark.unit
6262
@pytest.mark.critical
63-
def test_name_dims_shared_batch_kwarg_inputs():
64-
"""Shared batch axis declared via ``Input(name_dims={0: "B"})`` on both
63+
def test_shared_dims_shared_batch_kwarg_inputs():
64+
"""Shared batch axis declared via ``Input(shared_dims={0: "B"})`` on both
6565
kwarg inputs -- same name => one exported symbol; engine matches eager."""
6666
model = _SharedBatchEncoder().eval().cuda()
6767

@@ -91,12 +91,12 @@ def test_name_dims_shared_batch_kwarg_inputs():
9191
cos_sim = cosine_similarity(ref, out)
9292
assertions.assertTrue(
9393
cos_sim > COSINE_THRESHOLD,
94-
f"name_dims shared batch (kwargs) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
94+
f"shared_dims shared batch (kwargs) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
9595
)
9696

9797

9898
@pytest.mark.unit
99-
def test_name_dims_shared_batch_positional_inputs():
99+
def test_shared_dims_shared_batch_positional_inputs():
100100
"""Same feature with positional ``inputs=[...]`` instead of kwargs."""
101101
model = _SharedBatchEncoder().eval().cuda()
102102

@@ -125,12 +125,12 @@ def test_name_dims_shared_batch_positional_inputs():
125125
cos_sim = cosine_similarity(ref, out)
126126
assertions.assertTrue(
127127
cos_sim > COSINE_THRESHOLD,
128-
f"name_dims shared batch (positional) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
128+
f"shared_dims shared batch (positional) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
129129
)
130130

131131

132132
@pytest.mark.unit
133-
def test_name_dims_shared_batch_mixed_args_and_kwargs():
133+
def test_shared_dims_shared_batch_mixed_args_and_kwargs():
134134
"""input_ids passed positionally, attention_mask as a kwarg; both share "B"."""
135135
model = _SharedBatchEncoder().eval().cuda()
136136

@@ -155,12 +155,12 @@ def test_name_dims_shared_batch_mixed_args_and_kwargs():
155155
cos_sim = cosine_similarity(ref, out)
156156
assertions.assertTrue(
157157
cos_sim > COSINE_THRESHOLD,
158-
f"name_dims shared batch (mixed) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
158+
f"shared_dims shared batch (mixed) out-of-tolerance at bs={bs}: cos_sim={cos_sim}",
159159
)
160160

161161

162162
@pytest.mark.unit
163-
def test_name_dims_conflicting_ranges_raises():
163+
def test_shared_dims_conflicting_ranges_raises():
164164
"""Same name with different (min, max) across inputs is a user error."""
165165
from torch_tensorrt.dynamo._tracer import build_dim_registry
166166

@@ -172,23 +172,23 @@ def test_name_dims_conflicting_ranges_raises():
172172
max_shape=(4, seq),
173173
dtype=torch.int64,
174174
name="input_ids",
175-
name_dims={0: "B"},
175+
shared_dims={0: "B"},
176176
),
177177
"attention_mask": torchtrt.Input(
178178
min_shape=(1, seq),
179179
opt_shape=(8, seq),
180180
max_shape=(8, seq),
181181
dtype=torch.int64,
182182
name="attention_mask",
183-
name_dims={0: "B"},
183+
shared_dims={0: "B"},
184184
),
185185
}
186186
with assertions.assertRaises(ValueError):
187187
build_dim_registry((), inputs)
188188

189189

190190
@pytest.mark.unit
191-
def test_name_dims_rejected_on_static_axis():
191+
def test_shared_dims_rejected_on_static_axis():
192192
"""Naming a static axis (min == max) is rejected at Input construction."""
193193
with assertions.assertRaises(ValueError):
194194
torchtrt.Input(
@@ -197,12 +197,12 @@ def test_name_dims_rejected_on_static_axis():
197197
max_shape=(1, 16),
198198
dtype=torch.int64,
199199
name="x",
200-
name_dims={0: "B"},
200+
shared_dims={0: "B"},
201201
)
202202

203203

204204
@pytest.mark.unit
205-
def test_name_dims_rejected_on_out_of_range_axis():
205+
def test_shared_dims_rejected_on_out_of_range_axis():
206206
"""An axis index outside the input's rank is rejected at construction."""
207207
with assertions.assertRaises(ValueError):
208208
torchtrt.Input(
@@ -211,13 +211,13 @@ def test_name_dims_rejected_on_out_of_range_axis():
211211
max_shape=(4, 16),
212212
dtype=torch.int64,
213213
name="x",
214-
name_dims={5: "B"}, # rank is 2; axis 5 does not exist
214+
shared_dims={5: "B"}, # rank is 2; axis 5 does not exist
215215
)
216216

217217

218218
@pytest.mark.unit
219219
def test_default_path_unchanged_for_static_inputs():
220-
"""Sanity check: a fully static input with no name_dims is unchanged."""
220+
"""Sanity check: a fully static input with no shared_dims is unchanged."""
221221

222222
class StaticModel(nn.Module):
223223
def __init__(self):

0 commit comments

Comments
 (0)