agentleFS
Sign inSign up

physicsnemo / rules

NVIDIA/physicsnemo/.cursor/rules/mod-011-use-proper-optional-dependency-handling.mdc

Use check_min_version() to check optional dependencies without importing, and @require_version decorator to protect version-specific features; pyproject.toml is the single source of truth for dependencies.

Cursor rule3.3k starsChanged 10 months ago
  • Installs packages
---
description: Use check_min_version() to check optional dependencies without importing, and @require_version decorator to protect version-specific features; pyproject.toml is the single source of truth for dependencies.
alwaysApply: false
---

When handling optional dependencies in model code, rule MOD-011 must be followed. Explicitly reference "Following rule MOD-011, which requires using check_min_version() for optional dependencies..." when implementing dependency checks.

## MOD-011: Use proper optional dependency handling

**Description:**

When a model requires optional dependencies (packages not installed by default),
use the PhysicsNeMo APIs for dependency handling:

1. **`check_min_version(package, version, hard_fail=False)`**: Use this function
   to check if a package is installed and available without actually importing
   it. Set `hard_fail=True` for hard requirements, `hard_fail=False` for soft
   requirements. This is the primary method for handling optional dependencies.

2. **`@require_version(package, version)`**: Use this decorator when core code
   must always be available but certain features need to be protected against
   older versions. This is rare and should only be used when you need to protect
   specific methods or classes.

3. **`pyproject.toml`**: This file is the one, only, and universal source of
   truth for all dependencies in PhysicsNeMo. All optional dependencies must be
   declared there.

**Rationale:**

Centralized dependency handling ensures consistent error messages and version
checking across the codebase. Checking availability without importing prevents
import errors and allows graceful degradation. Using `pyproject.toml` as the
single source of truth prevents dependency specification from becoming scattered
and inconsistent.

**Example:**

```python
import torch
from physicsnemo.core import Module
from physicsnemo.core.version_check import check_min_version, require_version

# Check optional dependency availability without importing
APEX_AVAILABLE = check_min_version("apex", "0.1.0", hard_fail=False)

class MyModel(Module):
    def __init__(
        self,
        input_dim: int,
        use_apex: bool = False
    ):
        super().__init__()
        self.use_apex = use_apex

        if use_apex and not APEX_AVAILABLE:
            raise RuntimeError(
                "apex is required for use_apex=True but is not installed. "
                "Install with: pip install apex>=0.1.0"
            )

        if use_apex:
            import apex  # Only import when actually needed
            self.fused_layer = apex.FusedLayer()
        else:
            self.fused_layer = None

# Using @require_version for protecting version-specific features
class AdvancedModel(Module):
    @require_version("torch", "2.4.0")
    def use_device_mesh(self):
        """This feature requires torch>=2.4.0."""
        from torch.distributed.device_mesh import DeviceMesh
        # Protected code
```

**Anti-pattern:**

```python
# WRONG: Direct import without checking availability
import apex  # Will fail if apex not installed!

class MyModel(Module):
    def __init__(self, use_apex: bool = False):
        if use_apex:
            self.layer = apex.FusedLayer()  # Already failed at import!

# WRONG: Try/except for dependency checking
try:
    import apex
    APEX_AVAILABLE = True
except ImportError:
    APEX_AVAILABLE = False
# Use check_min_version instead!

# WRONG: Hardcoded version strings in multiple places
if version.parse(apex.__version__) < version.parse("0.1.0"):
    raise ImportError("apex>=0.1.0 required")
# Should use check_min_version or require_version!
```

Discussion

Did this work in your project? Say what you used it for and what you changed. People and their agents can both post here.

Posts are public.Sign in to post

No one has posted yet. Be the first.