pyrefly-shape-extensions 1.3.0.dev1__tar.gz → 1.3.0.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: pyrefly-shape-extensions
3
- Version: 1.3.0.dev1
3
+ Version: 1.3.0.dev3
4
4
  Summary: Shape typing primitives and DSL for Pyrefly tensor shape tracking
5
5
  Project-URL: homepage, https://pyrefly.org
6
6
  Project-URL: documentation, https://pyrefly.org/en/docs/
@@ -8,7 +8,7 @@ description = "Shape typing primitives and DSL for Pyrefly tensor shape tracking
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.12"
10
10
  license = { file = "LICENSE" }
11
- version = "1.3.0.dev1"
11
+ version = "1.3.0.dev3"
12
12
  keywords = ["typechecker", "typechecking", "shapes", "tensor", "pyrefly"]
13
13
  classifiers = [
14
14
  "Development Status :: 4 - Beta",
@@ -15,6 +15,23 @@ don't crash when evaluated by Python.
15
15
  import typing
16
16
  from dataclasses import dataclass
17
17
 
18
+ __all__ = [
19
+ "D",
20
+ "Elements",
21
+ "Int",
22
+ "IntTuple",
23
+ "IntVar",
24
+ "ProxyMethod",
25
+ "SymbolicArithExpr",
26
+ "TypeVarTuple",
27
+ "assert_shape",
28
+ "broadcast",
29
+ "defines_assert_shape",
30
+ "shaped_array",
31
+ "type_shape_dsl_function",
32
+ "uses_shape_dsl",
33
+ ]
34
+
18
35
 
19
36
  def _return_class(cls, params):
20
37
  return cls
@@ -120,20 +137,16 @@ class Int[T]:
120
137
  pass
121
138
 
122
139
 
123
- class ProxyMethod[T]:
124
- """Type-checker marker for method forwarding annotations."""
140
+ class Flag[T]:
141
+ """Marker for a literal-preserving value that controls type-level evaluation."""
125
142
 
126
143
  pass
127
144
 
128
145
 
129
- def enable_torchscript_runtime_compat() -> None:
130
- """Erase shape-only runtime annotations to types TorchScript understands.
131
-
132
- This is a one-way, process-global compatibility mode for legacy TorchScript
133
- paths. It intentionally has no disable API for production callers.
134
- """
146
+ class ProxyMethod[T]:
147
+ """Type-checker marker for method forwarding annotations."""
135
148
 
136
- Int.__class_getitem__ = classmethod(_return_int)
149
+ pass
137
150
 
138
151
 
139
152
  @dataclass(frozen=True)
@@ -257,7 +270,7 @@ def shaped_array(*, shape: str) -> typing.Callable[[type], type]:
257
270
  return decorator
258
271
 
259
272
 
260
- def broadcast(*_args):
273
+ def broadcast(*_args: typing.Any) -> IntTuple:
261
274
  """Runtime placeholder for Pyrefly's native type-level broadcast intrinsic."""
262
275
 
263
276
  return IntTuple()
@@ -11,8 +11,12 @@ Only used inside DSL definition files (e.g. torch/_shapes.pyi), not in
11
11
  normal stubs or user code.
12
12
  """
13
13
 
14
+ from __future__ import annotations
15
+
14
16
  import typing
15
17
 
18
+ from . import Int as _IntSchema, IntTuple as _IntTupleSchema
19
+
16
20
 
17
21
  def shape_dsl_function(fn: typing.Callable) -> typing.Callable:
18
22
  """Marks a function as a shape DSL function.
@@ -59,7 +63,52 @@ class _Unknown:
59
63
  Unknown: _Unknown = _Unknown()
60
64
 
61
65
 
62
- def prod(xs: list[int]) -> int:
66
+ def Invalid(message: str) -> typing.Any:
67
+ """Return an invalid shape computation from a type-shape DSL body."""
68
+
69
+ ...
70
+
71
+
72
+ class Int:
73
+ """Operations that produce values in the DSL integer domain."""
74
+
75
+ @staticmethod
76
+ def gradual() -> typing.Any: ...
77
+
78
+
79
+ class IntTuple(_IntTupleSchema):
80
+ """Operations that produce values in the DSL integer-tuple domain."""
81
+
82
+ def __new__(cls, values: typing.Iterable[typing.Any]) -> _IntTupleSchema:
83
+ return _IntTupleSchema(values)
84
+
85
+ @staticmethod
86
+ def gradual() -> typing.Any: ...
87
+
88
+
89
+ def is_concrete_int(value: typing.Any) -> bool: ...
90
+
91
+
92
+ def is_int_value(value: object) -> typing.TypeIs[int]: ...
93
+
94
+
95
+ def concat(
96
+ left: typing.Iterable[typing.Any], right: typing.Iterable[typing.Any], /
97
+ ) -> _IntTupleSchema:
98
+ """Concatenate two shape values inside a type-shape DSL body."""
99
+
100
+ return _IntTupleSchema((*left, *right))
101
+
102
+
103
+ @typing.overload
104
+ def prod(xs: _IntTupleSchema, /) -> _IntSchema: ...
105
+
106
+
107
+ @typing.overload
108
+ def prod(xs: list[int]) -> int: ...
109
+
110
+
111
+ def prod(xs: _IntTupleSchema | list[int]) -> _IntSchema | int:
63
112
  """Compute the product of a list of dimension sizes."""
64
113
  ...
65
114
 
@@ -0,0 +1,346 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ # pyre-ignore-all-errors
7
+
8
+ """Shape annotations with TorchScript-compatible runtime behavior enabled.
9
+
10
+ Importing this module erases shape-only runtime annotations to types
11
+ TorchScript understands. This must happen before any annotated class body is
12
+ evaluated, because TorchScript reads class attribute annotations back out of
13
+ `__annotations__`, so a call made after import would be too late.
14
+
15
+ `Int` here is the same class object as `shape_extensions.Int`, so the change is
16
+ process-global and one-way: it also affects code that imports `shape_extensions`
17
+ directly. There is intentionally no way to undo it.
18
+
19
+ Importing this module also patches TorchScript's source loading so that shape
20
+ annotations written in source, rather than read back from `__annotations__`,
21
+ are erased too. The two halves are not independently useful: a model needs both
22
+ to be scriptable.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import ast
28
+ import textwrap
29
+
30
+ from . import * # noqa: F401, F403
31
+ from . import __all__ as _shape_extensions_all, _return_int, Int as _Int
32
+
33
+ __all__ = [*_shape_extensions_all, "remove_shape_types_from_torch_sources"]
34
+
35
+ _Int.__class_getitem__ = classmethod(_return_int)
36
+
37
+
38
+ _SHAPE_TYPE_REPLACEMENTS = (
39
+ ("shape_extensions.torchscript.Int[", "int"),
40
+ ("shape_extensions.Int[", "int"),
41
+ ("torch.Tensor[", "torch.Tensor"),
42
+ ("Tensor[", "torch.Tensor"),
43
+ ("Int[", "int"),
44
+ )
45
+
46
+
47
+ def _shape_type_end(source: str, open_bracket: int) -> int | None:
48
+ depth = 0
49
+ for i in range(open_bracket, len(source)):
50
+ if source[i] == "[":
51
+ depth += 1
52
+ elif source[i] == "]":
53
+ depth -= 1
54
+ if depth == 0:
55
+ return i + 1
56
+ return None
57
+
58
+
59
+ def _is_identifier_part(char: str) -> bool:
60
+ return char == "_" or char.isalnum()
61
+
62
+
63
+ def _has_name_boundary(source: str, start: int) -> bool:
64
+ return start == 0 or (
65
+ source[start - 1] != "." and not _is_identifier_part(source[start - 1])
66
+ )
67
+
68
+
69
+ def _replace_shape_types(source: str) -> str:
70
+ rewritten: list[str] = []
71
+ i = 0
72
+ while i < len(source):
73
+ for prefix, replacement in _SHAPE_TYPE_REPLACEMENTS:
74
+ if source.startswith(prefix, i) and _has_name_boundary(source, i):
75
+ end = _shape_type_end(source, i + len(prefix) - 1)
76
+ if end is None:
77
+ continue
78
+ rewritten.append(replacement)
79
+ i = end
80
+ break
81
+ else:
82
+ rewritten.append(source[i])
83
+ i += 1
84
+ return "".join(rewritten)
85
+
86
+
87
+ def _annotation_nodes(tree: ast.AST):
88
+ for node in ast.walk(tree):
89
+ if isinstance(node, ast.arg) and node.annotation is not None:
90
+ yield node.annotation
91
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
92
+ if node.returns is not None:
93
+ yield node.returns
94
+ elif isinstance(node, ast.AnnAssign):
95
+ yield node.annotation
96
+
97
+
98
+ def _source_line_offsets(source: str) -> list[int]:
99
+ offsets = [0]
100
+ for line in source.splitlines(keepends=True):
101
+ offsets.append(offsets[-1] + len(line))
102
+ return offsets
103
+
104
+
105
+ def _source_offset(
106
+ source: str, line_offsets: list[int], lineno: int, col_offset: int
107
+ ) -> int:
108
+ line_start = line_offsets[lineno - 1]
109
+ line_end = line_offsets[lineno] if lineno < len(line_offsets) else len(source)
110
+ line = source[line_start:line_end]
111
+ return line_start + len(line.encode("utf-8")[:col_offset].decode("utf-8"))
112
+
113
+
114
+ def _line_indent(source: str, start: int) -> str:
115
+ line_start = source.rfind("\n", 0, start) + 1
116
+ prefix = source[line_start:start]
117
+ return prefix[: len(prefix) - len(prefix.lstrip())]
118
+
119
+
120
+ def _preserve_line_count(source: str, replacement: str, indent: str) -> str:
121
+ missing_newlines = source.count("\n") - replacement.count("\n")
122
+ if missing_newlines <= 0:
123
+ return replacement
124
+
125
+ filler = [f"{indent}# shape annotation erased"] * (missing_newlines - 1)
126
+ return "\n".join([f"({replacement}", *filler, f"{indent})"])
127
+
128
+
129
+ def _is_type_checking_sentinel(test: ast.expr) -> bool:
130
+ """Recognize the typing sentinel, and only it.
131
+
132
+ `TYPE_CHECKING` and `typing.TYPE_CHECKING` are the spellings this erasure
133
+ supports. An attribute on anything else is not assumed to be the sentinel:
134
+ a project is free to have its own `TYPE_CHECKING` flag that is live at
135
+ runtime, and erasing that would delete real behavior. An aliased import
136
+ such as `import typing as t` is likewise not recognized, which errs toward
137
+ leaving code alone.
138
+ """
139
+
140
+ if isinstance(test, ast.Name):
141
+ return test.id == "TYPE_CHECKING"
142
+ return (
143
+ isinstance(test, ast.Attribute)
144
+ and test.attr == "TYPE_CHECKING"
145
+ and isinstance(test.value, ast.Name)
146
+ and test.value.id == "typing"
147
+ )
148
+
149
+
150
+ def _erase_type_checking_blocks(source: str) -> str:
151
+ """Replace `if TYPE_CHECKING:` blocks with `pass`, preserving line count.
152
+
153
+ TorchScript compiles both arms of an `if`, and cannot resolve
154
+ `TYPE_CHECKING` itself: it fails with "python value of type 'bool' cannot
155
+ be used as a value". Such a block is dead at runtime by construction, so
156
+ erasing it is safe, and it is what lets a scripted model carry static
157
+ `assert_type` checks on its shapes.
158
+
159
+ A block with an `else` is left alone: the `else` arm is the live one, and
160
+ rewriting it is beyond what this erasure is for.
161
+ """
162
+
163
+ tree = ast.parse(source)
164
+ line_offsets = _source_line_offsets(source)
165
+ spans: list[tuple[int, int]] = []
166
+ for node in ast.walk(tree):
167
+ if not isinstance(node, ast.If) or node.orelse:
168
+ continue
169
+ if not _is_type_checking_sentinel(node.test):
170
+ continue
171
+ if node.end_lineno is None or node.end_col_offset is None:
172
+ continue
173
+ spans.append(
174
+ (
175
+ _source_offset(source, line_offsets, node.lineno, node.col_offset),
176
+ _source_offset(
177
+ source, line_offsets, node.end_lineno, node.end_col_offset
178
+ ),
179
+ )
180
+ )
181
+
182
+ # Only the outermost of a set of nested blocks is erased. A nested block is
183
+ # already inside the text its enclosing block replaces, so keeping both
184
+ # would apply two edits to overlapping spans, and the second would be
185
+ # working from offsets the first had already invalidated.
186
+ outermost: list[tuple[int, int]] = []
187
+ for start, end in sorted(spans):
188
+ if outermost and start < outermost[-1][1]:
189
+ continue
190
+ outermost.append((start, end))
191
+
192
+ for start, end in reversed(outermost):
193
+ indent = _line_indent(source, start)
194
+ filler = [f"{indent}# type-checking block erased"] * source[start:end].count(
195
+ "\n"
196
+ )
197
+ replacement = "\n".join(["pass", *filler])
198
+ source = f"{source[:start]}{replacement}{source[end:]}"
199
+ return source
200
+
201
+
202
+ def _replace_shape_types_in_source(source: str) -> str:
203
+ try:
204
+ ast.parse(source)
205
+ except IndentationError:
206
+ source = textwrap.dedent(source)
207
+
208
+ # Erased first, in a separate pass, so that annotations inside these blocks
209
+ # are gone before annotation rewriting runs and cannot produce overlapping
210
+ # edits to the same span.
211
+ source = _erase_type_checking_blocks(source)
212
+ tree = ast.parse(source)
213
+
214
+ line_offsets = _source_line_offsets(source)
215
+ replacements: list[tuple[int, int, str]] = []
216
+ for node in _annotation_nodes(tree):
217
+ if (
218
+ node.end_lineno is None
219
+ or node.end_col_offset is None
220
+ or node.lineno is None
221
+ or node.col_offset is None
222
+ ):
223
+ continue
224
+ start = _source_offset(source, line_offsets, node.lineno, node.col_offset)
225
+ end = _source_offset(source, line_offsets, node.end_lineno, node.end_col_offset)
226
+ original = source[start:end]
227
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
228
+ # A wholly quoted annotation. Rewrite what the quotes contain and
229
+ # emit the result unquoted, rather than trying to consume the
230
+ # quotes while scanning: an annotation that continues past the
231
+ # shape type, such as `"Tensor[[B, D]] | None"`, would otherwise
232
+ # lose its opening quote and keep its closing one.
233
+ #
234
+ # Dropping the quotes is deliberate. TorchScript rejects a union
235
+ # written as a string but accepts the same union unquoted, so
236
+ # leaving the quotes on would turn a rewrite that parses into one
237
+ # that still fails to script. The cost is that a genuine forward
238
+ # reference inside a rewritten annotation is now evaluated eagerly.
239
+ # Compare against the contents rather than the quoted form, so an
240
+ # annotation with nothing to rewrite keeps its quotes.
241
+ rewritten = _replace_shape_types(node.value)
242
+ changed = rewritten != node.value
243
+ else:
244
+ rewritten = _replace_shape_types(original)
245
+ changed = rewritten != original
246
+ if changed:
247
+ replacements.append(
248
+ (
249
+ start,
250
+ end,
251
+ _preserve_line_count(
252
+ original, rewritten, _line_indent(source, start)
253
+ ),
254
+ )
255
+ )
256
+
257
+ for start, end, replacement in sorted(replacements, reverse=True):
258
+ source = f"{source[:start]}{replacement}{source[end:]}"
259
+ return source
260
+
261
+
262
+ class _ShapeTypingRemover:
263
+ def __init__(self, func) -> None:
264
+ self.func = func
265
+
266
+ def __call__(self, obj, error_msg=None):
267
+ source_lines, file_lineno, filename = self.func(obj, error_msg)
268
+ return (
269
+ _replace_shape_types_in_source("".join(source_lines)).splitlines(
270
+ keepends=True
271
+ ),
272
+ file_lineno,
273
+ filename,
274
+ )
275
+
276
+
277
+ class _ShapeAnnotationTypeRemover:
278
+ def __init__(self, func, torch) -> None:
279
+ self.func = func
280
+ self.torch = torch
281
+
282
+ def __call__(self, ann, *args, **kwargs):
283
+ if isinstance(ann, str):
284
+ rewritten = _replace_shape_types(ann)
285
+ if rewritten != ann:
286
+ rcb = kwargs.get("rcb", args[1] if len(args) > 1 else None)
287
+ annotations = self.torch.jit.annotations
288
+ # Resolved outside the try so that a rename or removal of these
289
+ # private torch APIs surfaces as an error here rather than being
290
+ # mistaken for an unresolvable annotation.
291
+ eval_no_call = annotations._eval_no_call
292
+ eval_env = annotations.EvalEnv(rcb)
293
+ try:
294
+ ann = eval_no_call(rewritten, {}, eval_env)
295
+ except (AttributeError, NameError, SyntaxError):
296
+ # Resolving the rewrite is best effort: it relies on private
297
+ # torch APIs, and on the rewritten text naming something
298
+ # resolvable in the caller's scope. Any failure means we
299
+ # cannot improve on the annotation we were given, so pass the
300
+ # original through and let TorchScript report it against the
301
+ # source the user wrote. Swallowing the error here would be
302
+ # wrong; TorchScript still rejects an annotation it cannot
303
+ # resolve, just with a better message than an eval traceback.
304
+ pass
305
+ return self.func(ann, *args, **kwargs)
306
+
307
+
308
+ def _is_shape_typing_remover(func) -> bool:
309
+ while func is not None:
310
+ if isinstance(func, _ShapeTypingRemover):
311
+ return True
312
+ func = getattr(func, "func", None)
313
+ return False
314
+
315
+
316
+ def _is_shape_annotation_type_remover(func) -> bool:
317
+ while func is not None:
318
+ if isinstance(func, _ShapeAnnotationTypeRemover):
319
+ return True
320
+ func = getattr(func, "func", None)
321
+ return False
322
+
323
+
324
+ def remove_shape_types_from_torch_sources() -> None:
325
+ """Patch TorchScript source loading to erase Pyrefly shape annotations."""
326
+
327
+ try:
328
+ import torch # @manual
329
+ except ImportError:
330
+ return
331
+
332
+ sources = torch._sources if hasattr(torch, "_sources") else torch.jit.frontend
333
+ if not _is_shape_typing_remover(sources.get_source_lines_and_file):
334
+ sources.get_source_lines_and_file = _ShapeTypingRemover(
335
+ sources.get_source_lines_and_file
336
+ )
337
+
338
+ annotations = torch.jit.annotations
339
+ if _is_shape_annotation_type_remover(annotations.ann_to_type):
340
+ return
341
+ annotations.ann_to_type = _ShapeAnnotationTypeRemover(
342
+ annotations.ann_to_type, torch
343
+ )
344
+
345
+
346
+ remove_shape_types_from_torch_sources()