Developer Tools

PyTorch enforces strict pyrefly type checking on torch/_numpy modules

First batch of annotation enforcement across PyTorch, with Claude AI co-authoring the PR.

Deep Dive

PyTorch has taken a major step toward stricter type safety with the merge of PR #187688, the first installment of a broader effort to enforce whole-file pyrefly type checking across the codebase. This round targets several torch/_numpy modules (linalg, _reductions_impl, fft, _dtypes, _normalizations, _util) that previously carried a '# mypy: ignore-errors' directive, meaning they had zero enforced annotation coverage. Every previously-unannotated function in these files is non-public, so fully annotating them does not change any public API signature, keeping downstream type-checking unaffected. For each file, the PR removes the file-level ignore, annotates all definitions, and adds an exact-path '[[sub-config]]' block to pyrefly.toml that enables unannotated-return, -parameter, and -attribute checks. Per-file sub-configs were deliberately chosen because sibling torch/_numpy files remain intentionally out of scope for now.

A particularly notable technical choice was made in _normalizations.py. The marker names (ArrayLike, DTypeLike, AxisLike, OutArray, etc.) were previously TypeVars used solely as string-dispatch tokens by the 'normalizer' decorator—not as real generics. They were redefined as TypeAliases for the post-normalization runtime type (e.g., ArrayLike = torch.Tensor), so implementer bodies type-check against accurate types. Thanks to 'from __future__ import annotations', the annotations remain lazy, and the decorator's string-based dispatch is unchanged. The alternative—leaving the TypeVars and suppressing per line—was rejected because it would scatter dozens of ignores and leave function bodies untyped. The PR was authored with the help of Claude AI and approved by bobrenjc93. Test results are strong: lintrunner reports no issues, test/torch_np shows 3,507 passed, 2,913 skipped, and 592 xfailed; test/test_numpy_interop.py shows 69 passed and 23 skipped.

Key Points
  • Removed '# mypy: ignore-errors' from 6 torch/_numpy files and annotated every function, method, and attribute.
  • Introduced per-file pyrefly sub-configs to enable strict checking without affecting sibling modules.
  • Changed TypeVars in _normalizations.py to TypeAliases to enable accurate type checking while preserving string dispatch via lazy annotations.

Why It Matters

Strict type checking reduces bugs in PyTorch's numpy compatibility layer, improving reliability for millions of users.

📬 Get the top 10 AI stories daily