torchmodal.diagnostics¶
torchmodal.diagnostics ¶
torchmodal.diagnostics ~~~~~~~~~~~~~~~~~~~~~~
Diagnostics for silently-dead terms in differentiable logic.
The characteristic failure mode of a differentiable logic is not an
exception — it is a term that has been pinned to the floor or the ceiling
of [0, 1] and whose gradient has vanished. Nothing raises; the term
simply stops contributing while the rest of the model keeps training, and
the symptom surfaces much later as "the constraint had no effect".
Three constructs in this library can reach that state:
- :func:
torchmodal.functional.until— its Łukasiewicz backward sweep loses1 - L_phiper step, so a long chain drives the lower bound to zero regardless of the data. - Iterated :func:
torchmodal.functional.necessity— each level coststau * H(w)(see :func:torchmodal.functional.box_width_entropy), so a deep enough nest floors at exactlyceil(1 / (tau * H))levels. - :func:
torchmodal.functional.contradictionafter a modal neuron — it is identically zero, with zero gradient, until the bound crossing exceeds the box width.
:func:gradient_health reports the condition; :func:assert_has_signal
is the raising variant for tests.
Example::
from torchmodal.diagnostics import gradient_health
A = torch.ones(8, 8, requires_grad=True)
report = gradient_health(
lambda: nested_necessity(A, depth=6), {"A": A}
)
print(report["healthy"]) # False
print(report["issues"]) # ["bound 'output' is vacuous: ...", ...]
print(report["warnings"]) # ["term 'output.L' is dead: ...", ...]
GradientHealthError ¶
gradient_health ¶
gradient_health(fn: Callable[..., Any], params: ParamSpec, *args: Any, names: Optional[Sequence[str]] = None, bounds: Union[bool, str] = 'auto', floor: float = 0.0, ceiling: float = 1.0, sat_atol: float = 1e-06, grad_atol: float = 1e-12, saturated_frac: float = 1.0, vacuous_atol: float = 1e-06, **kwargs: Any) -> Dict[str, Any]
Report whether a differentiable-logic term still carries signal.
Calls fn(*args, **kwargs) and reports, per output term and per
parameter tensor, whether the value has been pinned to the floor or
the ceiling of the truth interval and whether its gradient vanished.
Gradients are attributed per term — one :func:torch.autograd.grad
call each — so a dead endpoint is still located when the other
endpoint of the same bound is alive.
This detects the failure mode described in the module docstring: a term that is silently stuck, contributing nothing to training while raising nothing.
Bound tensors of shape (..., 2) are split into "<name>.L" and
"<name>.U" before checking, because the dead state of a modal
neuron is L = 0 with U = 1 — checked jointly, neither column
looks pinned.
What counts as unhealthy. A term is reported as dead when it is
pinned and its gradient to every parameter has vanished, and as
saturated when pinned but still differentiable. Both go to
"warnings", not "issues": on its own, a pinned endpoint does
not mean anything is wrong. A sound upper bound that has legitimately
reached 1 is indistinguishable, at the level of a single term, from a
broken one — and whether the clamp at the interval edge passes gradient
exactly at the boundary is a torch-version convention (2.8 passes
1.0, 2.14 passes 0.0), so keying healthy on it would be both noisy
and version-dependent.
healthy is therefore False only on signals that mean the term
has genuinely stopped carrying information:
- a vacuous bound — width spanning the whole interval everywhere, so the pair says nothing at all (this is what a collapsed nest of modal operators produces, on every torch version);
- no parameter receiving a usable gradient from any term;
- a term with no autograd path at all, or a parameter with
requires_grad=False.
Read "warnings" as well when diagnosing: a dead endpoint whose
bound is not yet vacuous is often the first sign of a nest about to
collapse.
.. note::
The call runs under torch.enable_grad and leaves .grad
untouched on the caller's tensors: gradients are taken with
:func:torch.autograd.grad, not .backward().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
Callable to diagnose. May return a tensor, or a sequence or mapping containing tensors. Non-tensor entries are ignored. |
required |
params
|
ParamSpec
|
Tensors whose gradients are checked. Accepts a single
tensor, a sequence, a |
required |
*args
|
Any
|
Positional arguments forwarded to |
()
|
names
|
Optional[Sequence[str]]
|
Optional replacement names for the returned tensors, in order, applied before bound splitting. Must match the number of tensors returned. |
None
|
bounds
|
Union[bool, str]
|
|
'auto'
|
floor
|
float
|
Lower end of the truth interval. Default 0.0. |
0.0
|
ceiling
|
float
|
Upper end of the truth interval. Default 1.0. |
1.0
|
sat_atol
|
float
|
Tolerance for calling a value saturated at an end of the interval. Default 1e-6. |
1e-06
|
grad_atol
|
float
|
A gradient whose maximum absolute entry is at or below this is reported as vanished. Default 1e-12. |
1e-12
|
saturated_frac
|
float
|
Fraction of a term's entries that must sit at one end before it counts as pinned. Default 1.0 (every entry). |
1.0
|
vacuous_atol
|
float
|
Tolerance for calling a split bound pair vacuous
( |
1e-06
|
**kwargs
|
Any
|
Keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dict with keys: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Example
import torch from torchmodal import functional as F from torchmodal.diagnostics import gradient_health A = torch.ones(8, 8, requires_grad=True) def deep_box(): ... b = torch.ones(8, 2) ... for _ in range(6): ... b = F.necessity(b, A, tau=0.1) ... return b gradient_health(deep_box, {"A": A})["healthy"] False
Source code in torchmodal/diagnostics.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
assert_has_signal ¶
assert_has_signal(fn: Callable[..., Any], params: ParamSpec, *args: Any, msg: Optional[str] = None, **kwargs: Any) -> Dict[str, Any]
Raising variant of :func:gradient_health, for use in tests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
Callable to diagnose. |
required |
params
|
ParamSpec
|
Tensors whose gradients are checked. |
required |
*args
|
Any
|
Positional arguments forwarded to |
()
|
msg
|
Optional[str]
|
Optional prefix for the raised message. |
None
|
**kwargs
|
Any
|
Keyword arguments forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
The report from :func: |
Raises:
| Type | Description |
|---|---|
GradientHealthError
|
If any output is pinned at an end of the truth interval, or any parameter's gradient vanished. |
Source code in torchmodal/diagnostics.py
vacuity_report ¶
vacuity_report(term_fn: Callable[[Tensor], Tensor], accessibility: Tensor, *, margin_atol: float = 0.0001) -> Dict[str, Any]
Distinguish a term that is satisfied from one that is vacuous.
Every :math:\square-built quantity is maximal on the empty relation:
an agent that can see nothing vacuously knows everything, because
L_□ = smooth_min((1 - A) + L_φ) has no small terms left to find. A
specification written only in :math:\square therefore has a global
optimum that satisfies every axiom and constrains nothing, and — the part
that catches people — an :math:\ell_1 sparsity penalty pushes toward
that optimum rather than against it.
This evaluates term_fn twice, on the supplied relation and on the
all-zero relation of the same shape, and reports the margin between them.
A term whose value is no better than its own vacuous value is carrying no
information about the relation, however satisfied it looks.
This is the tool the :func:torchmodal.functional.contradiction docstring
asks for when it warns that L_contra "must not be the sole guard
against a degenerate optimum".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
term_fn
|
Callable[[Tensor], Tensor]
|
Callable taking an accessibility matrix and returning a tensor — a bound, a residual, or a scalar score. |
required |
accessibility
|
Tensor
|
The relation to test, |
required |
margin_atol
|
float
|
A margin at or below this counts as vacuous. Default 1e-4. |
0.0001
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dict with |
Dict[str, Any]
|
returned tensor), |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
box-like term, |
Dict[str, Any]
|
is the signal for whether a specification is one-sided. |
Example
import torch from torchmodal import functional as F from torchmodal.diagnostics import vacuity_report A = torch.rand(6, 6) phi = torch.zeros(6, 2) # unsupported everywhere r = vacuity_report(lambda a: F.necessity(phi, a)[:, 0], A) r["vacuous"] # box on an unsupported prop True
Source code in torchmodal/diagnostics.py
monotone_in_accessibility ¶
Is this bound endpoint monotone in the accessibility relation?
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operator
|
str
|
|
required |
endpoint
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
argument is available for it. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the operator/endpoint pair is not recognised. |
Example
from torchmodal.diagnostics import monotone_in_accessibility monotone_in_accessibility("necessity", "L") True monotone_in_accessibility("necessity", "U") False