{"record":{"id":"96f912523c818290","repo":"pytorch/pytorch","slug":"dim-repr-self-previously-bound-to-a-dimension","errorCode":null,"errorMessage":"Dim '{repr(self)}' previously bound to a dimension of size {self._size} cannot bind to a dimension of size {v}","messagePattern":"Dim '(.+?)' previously bound to a dimension of size (.+?) cannot bind to a dimension of size (.+?)","errorType":"exception","errorClass":"DimensionBindError","httpStatus":null,"severity":"error","filePath":"functorch/dim/__init__.py","lineNumber":920,"sourceCode":"    def ndim(self) -> int:\n        return 1\n\n    @classmethod\n    def check_exact(cls, obj: Any) -> bool:\n        return type(obj) is cls\n\n    @property\n    def size(self) -> int:\n        if self._size == -1:\n            raise ValueError(f\"dimension {self._name} is unbound\")\n        return self._size\n\n    @size.setter\n    def size(self, v: int) -> None:\n        if self._size == -1:\n            self._size = v\n        elif self._size != v:\n            raise DimensionBindError(\n                f\"Dim '{repr(self)}' previously bound to a dimension of size {self._size} \"\n                f\"cannot bind to a dimension of size {v}\"\n            )\n\n    @property\n    def is_bound(self) -> bool:\n        \"\"\"Return True if this dimension is bound to a size.\"\"\"\n        return self._size != -1\n\n    def _get_range(self) -> torch.Tensor:\n        \"\"\"\n        Get a tensor representing the range [0, size) for this dimension.\n\n        Returns:\n            A 1D tensor with values [0, 1, 2, ..., size-1]\n        \"\"\"\n        if self._range is None:\n            self._range = torch.arange(self.size)","sourceCodeStart":902,"sourceCodeEnd":938,"githubUrl":"https://github.com/pytorch/pytorch/blob/dcd2ecae775af66439b7ede4e7a82540b058c59c/functorch/dim/__init__.py#L902-L938","documentation":"A Dim is a persistent name that remembers the extent it was first bound to. The size setter allows exactly one binding; a second assignment with a different value raises DimensionBindError. This is by design: reusing the same Dim for two differently-sized dimensions would make named-indexing ambiguous, so the library enforces size consistency across the whole program.","triggerScenarios":"Reusing one Dim object for tensor dimensions of different lengths: t1 = torch.zeros(4)[d]; t2 = torch.zeros(8)[d]. Also triggered inside split when unbound target dims get assigned sizes that conflict with an earlier binding, or in setitem/getitem dim packs where an inferred size disagrees with a prior bind.","commonSituations":"Copy-pasting a pipeline block that uses the same dims() objects on batches with a different sequence length; loop iterations where the first batch had seq_len=32 and the next has 64; mixing a global 'batch' Dim across models whose batch sizes differ.","solutions":["Create fresh Dim objects per shape: call dims(n) or construct new Dims inside the loop/function instead of reusing module-level ones.","If the shape is genuinely fixed, fix the data: make the incoming tensors agree with the already-bound size (e.g. pad/truncate or set a consistent batch size).","Catch DimensionBindError where variable-size inputs are legitimate, and rebuild the dims for that batch (see tryCatchPattern)."],"exampleFix":"d = dims(1)\n_ = torch.zeros(4)[d]\n_ = torch.zeros(8)[d]  # DimensionBindError\n\n# after (fresh dim per shape)\nfor batch in batches:\n    d = dims(1)\n    _ = batch[d]","handlingStrategy":"try-catch","validationCode":"if d.is_bound and d.size != expected:\n    raise ValueError(f'{d!r} bound to {d.size}, data has {expected}')","typeGuard":null,"tryCatchPattern":"from functorch.dim import DimensionBindError\ntry:\n    _ = batch[d]\nexcept DimensionBindError:\n    d = dims(1)  # fresh dim for this batch's size\n    _ = batch[d]","preventionTips":["Never share module-level Dim objects across differently-sized batches.","Create dims inside the training step, not once at import time.","Add a shape assert at the data boundary so mismatches surface as data errors, not bind errors."],"tags":["torchdim","first-class-dims","binding","size-mismatch","stateful-api"],"backgroundTag":null,"analyzedSha":"dcd2ecae775af66439b7ede4e7a82540b058c59c","analyzedAt":"2026-08-14T19:21:26.615Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}