torchmodal.losses¶
torchmodal.losses ¶
torchmodal.losses ~~~~~~~~~~~~~~~~~
Loss functions for MLNN training.
The combined loss drives learning by balancing task performance against logical consistency:
.. math:: \mathcal{L}{\text{total}} = \mathcal{L}{\text{task}} + \beta \mathcal{L}_{\text{contra}}
ContradictionLoss ¶
Bases: Module
Logical contradiction loss.
Penalizes states where the lower bound exceeds the upper bound, indicating a logical inconsistency in the Kripke model:
.. math:: \mathcal{L}{\text{contra}} = \sum{w \in W} \sum_\phi \max(0,\; L_{\phi,w} - U_{\phi,w})
Can use either sum or mean reduction, and optionally
applies squared penalty for smoother gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reduction
|
str
|
|
'mean'
|
squared
|
bool
|
If |
False
|
Source code in torchmodal/losses.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds
|
Tensor
|
Tensor of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Contradiction loss (scalar or per-element). |
Source code in torchmodal/losses.py
ModalLoss ¶
Bases: Module
Combined modal training loss.
.. math:: \mathcal{L}{\text{total}} = \mathcal{L}{\text{task}} + \beta \mathcal{L}_{\text{contra}}
This is the standard MLNN training objective (Equation 3 of the paper). The task loss drives performance, while the contradiction loss ensures logical consistency. The hyperparameter β controls the trade-off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
Weight for the contradiction loss. Default 0.1. |
0.1
|
squared
|
bool
|
Use squared contradiction penalty. Default |
False
|
Example::
>>> criterion = ModalLoss(beta=0.3)
>>> task_loss = nn.functional.cross_entropy(logits, targets)
>>> bounds = model.all_bounds() # dict of (|W|, 2) tensors
>>> loss = criterion(task_loss, bounds)
Source code in torchmodal/losses.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_loss
|
Tensor
|
Task-specific loss (e.g., cross-entropy). |
required |
bounds
|
dict[str, Tensor] | Tensor
|
Either a dict mapping proposition names to bounds
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Combined scalar loss. |
Source code in torchmodal/losses.py
SparsityLoss ¶
Bases: Module
L1 sparsity regularization on the accessibility matrix.
Encourages the model to discover the minimal trust structure:
.. math:: \mathcal{L}{\text{sparse}} = \lambda |A\theta|_1
Typically applied to off-diagonal elements only (self-trust is expected).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lambda_sparse
|
float
|
Regularization strength. Default 0.05. |
0.05
|
exclude_diagonal
|
bool
|
Exclude diagonal from penalty. Default |
True
|
Source code in torchmodal/losses.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
Accessibility matrix |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar sparsity loss. |
Source code in torchmodal/losses.py
CrystallizationLoss ¶
Bases: Module
Entropy minimization loss for forcing crisp truth assignments.
Used in satisfiability mode (e.g., Sudoku) to push truth values toward 0 or 1:
.. math:: \mathcal{L}{\text{crystal}} = -\sum{w,p} p \log p + (1-p) \log(1-p)
Often combined with temperature annealing for a "phase transition" effect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reduction
|
str
|
|
'mean'
|
eps
|
float
|
Small constant for numerical stability. Default 1e-8. |
1e-08
|
Source code in torchmodal/losses.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Tensor
|
Truth values in (0, 1) of any shape. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Entropy loss (scalar). |
Source code in torchmodal/losses.py
AxiomRegularization ¶
Bases: Module
Regularization losses for enforcing modal logic axiom systems.
Provides differentiable penalties that encourage the learned accessibility relation to satisfy structural properties:
- Axiom T (Reflexivity):
A[i,i] = 1for all i. System T: □ϕ → ϕ (knowledge is veridical). - Axiom 4 (Transitivity):
A @ A ≤ A. System S4: □ϕ → □□ϕ (positive introspection). - Axiom B (Symmetry):
A ≈ Aᵀ. System B: ϕ → □♢ϕ (Brouwerian axiom). - Axiom D (Seriality): every world has a successor,
max_j A[i,j] = 1. System D: □ϕ → ♢ϕ (consistency — what is necessary is possible). - Axiom 5 (Euclidean):
A[i,j] ∧ A[i,k] → A[j,k]. System S5: ♢ϕ → □♢ϕ (negative introspection).
These can be combined to enforce specific modal logic systems: - System T = K + Reflexivity - System S4 = K + Reflexivity + Transitivity - System S5 = K + Reflexivity + Transitivity + Symmetry - System B = K + Reflexivity + Symmetry
.. warning::
Seriality and the identity relation. The obvious reading of "every
world has a successor" is max_j A[i,j] = 1, and the identity matrix
satisfies it perfectly while relating nothing to anything else. Since
:class:~torchmodal.nn.LearnableAccessibility is reflexive by default,
the identity is exactly where a fit can comfortably settle — so a user
who asks for "no dead ends" can get a relation that coordinates
nothing. Pass serial_hollow=True (the default) to require a
successor other than the world itself, which is what people mean.
.. note::
The seriality penalty uses a hard max, not
:func:~torchmodal.functional.smooth_max. The smooth surrogate is an
upper bound on the max, so relu(1 - smooth_max(...)) understates
the violation and scores a non-serial relation as satisfied unless it
is debiased by tau * log n. Using the exact max avoids the trap;
the gradient reaches the maximal entry of each row, which is enough to
drive it toward 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reflexivity
|
float
|
Weight for reflexivity penalty. Default 0.0. |
0.0
|
transitivity
|
float
|
Weight for transitivity penalty. Default 0.0. |
0.0
|
symmetry
|
float
|
Weight for symmetry penalty. Default 0.0. |
0.0
|
seriality
|
float
|
Weight for the Axiom D penalty. Default 0.0. |
0.0
|
euclidean
|
float
|
Weight for the Axiom 5 penalty. Default 0.0. |
0.0
|
serial_hollow
|
bool
|
When |
True
|
Example::
>>> # Enforce System S4 (reflexive + transitive)
>>> reg = AxiomRegularization(reflexivity=1.0, transitivity=0.5)
>>> A = model.get_accessibility()
>>> loss = reg(A)
Source code in torchmodal/losses.py
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 | |
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
Accessibility matrix |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar regularization loss. |
Source code in torchmodal/losses.py
SemanticLoss ¶
Bases: Module
Semantic constraint loss (Xu et al., 2018) — NeSy baseline.
Implements the Semantic Loss from "A Semantic Loss Function for Deep Learning with Symbolic Knowledge" (Xu et al., ICML 2018). This is provided as a baseline for comparing MLNN's modal contradiction loss against non-modal neurosymbolic approaches.
For a propositional constraint C over a set of Boolean
variables with predicted probabilities p, the semantic loss is:
.. math:: \mathcal{L}{\text{semantic}} = -\log \sum{\mathbf{x} \models C} \prod_i p_i^{x_i}(1 - p_i)^{1 - x_i}
This computes the negative log-probability of the constraint being satisfied under the current predictions.
Relationship to MLNN's ContradictionLoss:
Both losses penalize logical inconsistency, but they differ in key ways:
SemanticLossoperates over propositional constraints on a single world — it cannot natively express modal (cross-world) constraints like □ϕ or ♢ϕ.ContradictionLossoperates over truth bounds and can propagate constraints across worlds via the accessibility relation.SemanticLossrequires enumerating satisfying assignments (exponential in the worst case), whileContradictionLossis always polynomial.
For mutual exclusivity (exactly-one-of-K), the semantic loss
has a closed-form solution (see :meth:forward_mutual_exclusive).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reduction
|
str
|
|
'mean'
|
Example::
>>> # Mutual exclusivity: exactly one of 9 digits per cell
>>> sem_loss = SemanticLoss()
>>> probs = torch.softmax(logits, dim=-1) # (81, 9)
>>> loss = sem_loss.forward_mutual_exclusive(probs)
References
Xu et al., "A Semantic Loss Function for Deep Learning with Symbolic Knowledge", ICML 2018.
Source code in torchmodal/losses.py
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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | |
forward_mutual_exclusive ¶
Semantic loss for mutual-exclusivity constraints.
Exactly one variable in each group should be true. This has a closed-form solution that avoids assignment enumeration:
.. math:: \mathcal{L} = -\log \sum_k p_k \prod_{j \neq k} (1 - p_j)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probs
|
Tensor
|
Predicted probabilities |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Semantic loss (scalar or per-element). |
Source code in torchmodal/losses.py
forward ¶
Compute semantic loss for a named constraint type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probs
|
Tensor
|
Predicted probabilities. |
required |
constraint_type
|
str
|
Currently supports |
'mutual_exclusive'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Semantic loss. |