agentleFS
NVIDIAKnown publisherNVIDIA/physicsnemo/.cursor/rules/mod-005-invalid-or-missing-tensor-shape-validation.mdc

physicsnemo / rules

Cursor rule3.3k starsChanged 12 months agoApache-2.0View on GitHub

All forward and public methods must validate tensor shapes at the beginning, wrapped in torch.compiler.is_compiling() guard, with standardized error messages.

Trending

Quiet since September.about the whole repository

Dec 2025: 0 mentionsJan 2026: 3 mentionsFeb 2026: 1 mentionMar 2026: 1 mentionApr 2026: 0 mentionsMay 2026: 1 mentionJun 2026: 3 mentionsJul 2026: 3 mentionsAug 2026: 0 mentionsSep 2026: 2 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the NVIDIA/physicsnemo repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about NVIDIA/physicsnemo

The biggest 5 of 15 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 15

Talked about on GitHub (15 times).

On GitHub · 15

10 more on GitHub

The file

We split this mod-005-invalid-or-missing-tensor-shape-validation.mdc into the rules it gives an agent

2 rules. About 0 are common, 2 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When implementing forward or public methods, rule MOD-005 must be followed.

    line 6
  2. Distinctive:

    All forward methods and other public methods that accept tensor arguments must validate tensor shapes at the beginning of the method.

    line 12

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
mod-005-invalid-or-missing-tensor-shape-validation.mdc
---
description: All forward and public methods must validate tensor shapes at the beginning, wrapped in torch.compiler.is_compiling() guard, with standardized error messages.
alwaysApply: false
---

When implementing forward or public methods, rule MOD-005 must be followed. Explicitly reference "Following rule MOD-005, which requires tensor shape validation at the beginning of methods with torch.compiler.is_compiling() guard..." when adding validation code.

## MOD-005: Invalid or missing tensor shape validation logic

**Description:**

All forward methods and other public methods that accept tensor arguments must
validate tensor shapes at the beginning of the method. This rule applies to:
- Individual tensor arguments
- Containers of tensors (lists, tuples, dictionaries)

For containers, validate their length, required keys, and the shapes of
contained tensors. Validation statements should be concise (ideally one check
per argument). Error messages must follow the standardized format:
`"Expected tensor of shape (B, D) but got tensor of shape {actual_shape}"`.

To avoid interactions with `torch.compile`, all validation must be wrapped in a
conditional check using `torch.compiler.is_compiling()`. Follow the "fail-fast"
approach by validating inputs before any computation.

**Rationale:**

Early shape validation catches errors at the API boundary with clear, actionable
error messages, making debugging significantly easier. Without validation, shape
mismatches result in cryptic errors deep in the computation graph. The
`torch.compile` guard ensures that validation overhead is eliminated in
production compiled code while preserving debug-time safety.

**Example:**

```python
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
    """Forward pass with shape validation."""
    ### Input validation
    # Skip validation when running under torch.compile for performance
    if not torch.compiler.is_compiling():
        # Extract expected dimensions
        B, C, H, W = x.shape if x.ndim == 4 else (None, None, None, None)

        # Validate x shape
        if x.ndim != 4:
            raise ValueError(
                f"Expected 4D input tensor (B, C, H, W), got {x.ndim}D tensor with shape {tuple(x.shape)}"
            )

        if C != self.in_channels:
            raise ValueError(
                f"Expected {self.in_channels} input channels, got {C} channels"
            )

        # Validate optional mask
        if mask is not None:
            if mask.shape != (B, H, W):
                raise ValueError(
                    f"Expected mask shape ({B}, {H}, {W}), got {tuple(mask.shape)}"
                )

    # Actual computation happens after validation
    return self._process(x, mask)
```

**Anti-pattern:**

```python
# WRONG: No validation at all
def forward(self, x: torch.Tensor) -> torch.Tensor:
    return self.layer(x)  # Will fail with cryptic error if shape is wrong

# WRONG: Validation not guarded by torch.compiler.is_compiling()
def forward(self, x: torch.Tensor) -> torch.Tensor:
    if x.ndim != 4:  # Breaks torch.compile
        raise ValueError(f"Expected 4D tensor, got {x.ndim}D")
    return self.layer(x)

# WRONG: Validation after computation has started
def forward(self, x: torch.Tensor) -> torch.Tensor:
    h = self.layer1(x)  # Computation started
    if x.shape[1] != self.in_channels:  # Too late!
        raise ValueError(f"Wrong number of channels")
    return self.layer2(h)
```

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.