Reject Duplicate Derivative Labels

This tutorial shows the Torch input validation error when two gradient-enabled project keys reuse one solver derivative label.

Experimental feature

The jcmsuite.torch integration is experimental. Its API and behavior can change in future releases. Do not depend on its current interface for production workflows without testing each package update.

Run it from demos/documentation_tutorials:

python derivatives/torch/validation_duplicate/run.py
"""Reject derivative labels reused by two Project Keys."""

import torch

import jcmsuite
from jcmsuite.torch import RealDerivative

try:
    jcmsuite.torch.solve(
        "project.jcmp",
        keys={
            "width": torch.tensor(31.0, requires_grad=True),
            "swa": torch.tensor(88.0, requires_grad=True),
        },
        key_derivative_map={
            "width": RealDerivative("same"),
            "swa": RealDerivative("same"),
        },
    )
except ValueError as error:
    assert "cannot be reused" in str(error)
    print(error)
else:
    raise AssertionError("Duplicate derivative labels were accepted")

Project File

project.jcmp
Project {
  Derivatives {
    Order = 1
  }
}