torchmodal.functional¶
torchmodal.functional ¶
torchmodal.functional ~~~~~~~~~~~~~~~~~~~~~
Functional API for differentiable modal logic operators.
Provides stateless functions for soft logic aggregations, propositional connectives, and modal operators following the MLNN framework (Sulc, 2026) with Kripke semantics.
All functions operate on tensors of truth bounds in [0, 1].
.. note::
The aggregation operators are named smooth_min / smooth_max
(not softmin / softmax) to avoid confusion with the standard
probability-normalization torch.softmax. These operators are
log-sum-exp aggregations that serve as sound bounds on the true
min/max, not probability distributions. Legacy aliases softmin
and softmax are provided for backward compatibility.
smooth_min ¶
Differentiable smooth minimum (log-sum-exp lower bound).
.. math:: \operatorname{smooth_min}_\tau(\mathbf{x}) = -\tau \log \sum_i \exp(-x_i / \tau)
This is a sound lower bound on :func:torch.min:
smooth_min(x) <= min(x) for all x_i \in [0, 1].
As :math:\tau \to 0, converges to :func:torch.min.
.. note::
Not to be confused with torch.softmax (probability normalization).
This function computes a scalar aggregation via the log-sum-exp
identity, not a probability distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor of truth values in [0, 1]. |
required |
tau
|
float
|
Temperature controlling approximation sharpness. Default 0.1. |
0.1
|
dim
|
int
|
Dimension along which to aggregate. Default -1. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor with |
Source code in torchmodal/functional.py
smooth_max ¶
Differentiable smooth maximum (log-sum-exp upper bound).
.. math:: \operatorname{smooth_max}_\tau(\mathbf{x}) = \tau \log \sum_i \exp(x_i / \tau)
This is a sound upper bound on :func:torch.max:
smooth_max(x) >= max(x) for all x_i \in [0, 1].
As :math:\tau \to 0, converges to :func:torch.max.
.. note::
Not to be confused with torch.softmax (probability normalization).
This function computes a scalar aggregation via the log-sum-exp
identity, not a probability distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor of truth values in [0, 1]. |
required |
tau
|
float
|
Temperature controlling approximation sharpness. Default 0.1. |
0.1
|
dim
|
int
|
Dimension along which to aggregate. Default -1. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor with |
Source code in torchmodal/functional.py
softmin ¶
Deprecated alias for :func:smooth_min.
Source code in torchmodal/functional.py
softmax ¶
Deprecated alias for :func:smooth_max.
Source code in torchmodal/functional.py
conv_pool ¶
Convex pooling operator (attention-weighted average).
Computes a convex combination of x using attention weights
derived from z:
.. math:: \operatorname{conv_pool}_\tau(\mathbf{x}, \mathbf{z}) = \sum_i w_i\, x_i, \quad w_i = \frac{\exp(z_i / \tau)}{\sum_j \exp(z_j / \tau)}
The weights w are a standard probability-normalized softmax
(torch.softmax) applied to the logits z / tau.
Bound properties (for x_i \in [0, 1]):
z = x→ the largest values receive the highest weight, providing a differentiable lower bound onmax(x).z = -x→ the smallest values receive the highest weight, providing a differentiable upper bound onmin(x).
These two modes are used in the Necessity (□) and Possibility (♢)
operators to construct sound upper/lower bounds that complement
the smooth_min / smooth_max bounds.
Exact width. In the z = -x mode the gap to the matching lower
bound is not an estimate but an identity:
.. math:: \operatorname{conv_pool}\tau(\mathbf{x}, -\mathbf{x}) - \operatorname{smooth_min}\tau(\mathbf{x}) = \tau\, H\bigl(\operatorname{softmax}(-\mathbf{x}/\tau)\bigr) \;\le\; \tau \log n,
with equality in the upper bound iff every :math:x_i ties. Verified
to 8.9e-16 in float64 over 20k random draws. See
:func:box_width_entropy, which returns this quantity.
.. warning::
This operator is not monotone in x when z = -x. Its
derivative is
.. math:: \frac{\partial f}{\partial x_k} = w_k \left(1 - \frac{x_k - f}{\tau}\right),
which is negative whenever :math:x_k - f > \tau: raising a
term that is already far above the pooled value lowers the
result, because it loses weight faster than it gains value. For
example at :math:\tau = 0.1, going from x = [0, 1] to
x = [0, 2] decreases the pool (4.54e-5 → 4.1e-9), and at
x = [0.3, 0.9] the gradients are [+1.0123, -0.0123].
This is harmless for soundness — the enclosure holds regardless —
but it invalidates the tempting argument "the box neuron is
monotone in A\ , therefore the bound is sound". That
argument is not available. The correct route is monotonicity of
the hard min together with the one-sided enclosure
smooth_min <= min <= conv_pool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Values to pool, shape |
required |
z
|
Tensor
|
Logits controlling the convex weights, same shape as |
required |
tau
|
float
|
Temperature. Lower values sharpen the weighting toward the extreme element. Default 0.1. |
0.1
|
dim
|
int
|
Dimension along which to pool. Default -1. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor with |
Source code in torchmodal/functional.py
156 157 158 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 | |
negation ¶
Fuzzy negation: :math:\neg x = 1 - x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Truth values in [0, 1]. Can be bounds |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Negated truth values. |
conjunction ¶
Łukasiewicz conjunction (fuzzy AND).
.. math:: a \wedge b = \max(0,\; a + b - 1)
For bounds: L_{a∧b} = max(0, L_a + L_b - 1),
U_{a∧b} = min(U_a, U_b).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Tensor
|
First operand truth values in [0, 1]. |
required |
b
|
Tensor
|
Second operand truth values in [0, 1]. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Conjunction truth values. |
Source code in torchmodal/functional.py
disjunction ¶
Łukasiewicz disjunction (fuzzy OR).
.. math:: a \vee b = \min(1,\; a + b)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Tensor
|
First operand truth values in [0, 1]. |
required |
b
|
Tensor
|
Second operand truth values in [0, 1]. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Disjunction truth values. |
Source code in torchmodal/functional.py
implication ¶
Łukasiewicz implication.
.. math:: a \to b = \min(1,\; 1 - a + b)
Equivalent to disjunction(negation(a), b).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Tensor
|
Antecedent truth values in [0, 1]. |
required |
b
|
Tensor
|
Consequent truth values in [0, 1]. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Implication truth values. |
Source code in torchmodal/functional.py
necessity ¶
necessity(prop_bounds: Tensor, accessibility: Tensor, tau: float = 0.1, top_k: int | None = None, precision: float | None = None, mode: str = 'soft') -> Tensor
Necessity (Box / □) operator — differentiable Kripke semantics.
Computes truth bounds for □ϕ across all worlds using the weighted accessibility matrix. For each world w:
.. math:: L_{\Box\phi,w} = \operatorname{smooth_min}\tau \bigl{ (1 - \tilde{A}{w,w'}) + L_{\phi,w'} \bigr}_{w' \in W}
.. math:: U_{\Box\phi,w} = \operatorname{conv_pool}\tau \bigl( x{w'}, \; -x_{w'} \bigr), \quad x_{w'} = (1 - \tilde{A}{w,w'}) + U{\phi,w'}
The operator acts as a "weakest link" detector: if a world is highly accessible (Ã ≈ 1) but ϕ is false there, the score collapses.
Top-k aggregation. With top_k=k each endpoint aggregates only
the k smallest of its own implication terms — (1 - Ã) + L for
the lower bound, (1 - Ã) + U for the upper — instead of the full
row. Because the terms are selected on the aggregated quantity (not on
à alone), the true minimum is always among the kept terms:
L_□ <= min and U_□ >= min still hold (Theorem 1), the smooth
lower bound is within tau * log(k) of the crisp minimum, the result
does not depend on |W|, and gradients reach exactly the k
selected entries of à per endpoint. The |W| x |W| term matrix
is still formed; the aggregation itself is O(k * |W|).
.. warning::
Do not emulate top_k by zeroing entries of à before the
call (the top_k= of the accessibility modules up to 0.2.0). Zeroed
entries still enter the log-sum-exp with term 1 + L and their
summed mass drives the bounds to [0, 1] as |W| grows, and
choosing neighbours by à alone is unsound.
Exact mode. mode="exact" evaluates at zero temperature, using the
true extremum in place of the smooth aggregators. The bracket is then
exact — gap 0 — and there is no gradient. Two properties follow that
the soft mode does not have:
- it is monotone in
A, on both endpoints, because a hardminandmaxare (verified: 0 violations over 300 random perturbations, against 247 and 252 for theconv_poolendpoints in soft mode); - interval inputs propagate soundly through it, which is what lets it serve as an abstract interpreter over a modal transition system.
Use soft mode to learn and exact mode to certify: train a relation, then
round it and re-evaluate exactly to obtain an answer that owes nothing to
the temperature. See :mod:torchmodal.fixpoint for the CTL operators
built on this mode.
Accumulated slack under nesting. Each □ level widens the interval
by exactly :math:\tau H(w) — the entropy of its own softmin weights,
returned by :func:box_width_entropy — bounded by
:math:\tau \log n and maximal when the aggregated terms all tie. The
cost is therefore per level and set by the frame's effective
branching, not by :math:|W| as such. Nesting :math:k levels loses
about :math:k \tau \bar{H}, so a lower bound starting at 1 reaches
the floor at
.. math:: k^* = \left\lceil 1 / (\tau \bar{H}) \right\rceil ,
after which the term is dead: pinned at 0 with no gradient. Measured
with phi = [1, 1], tau = 0.1, |W| = 8, lower bound at
depth 1..6:
===================== ========================================== ===========
frame L at depth 1, 2, 3, 4, 5, 6 per level
===================== ========================================== ===========
complete (A=ones) 0.792, 0.584, 0.376, 0.168, 0.0, 0.0 0.2079
ring bidirectional 0.890, 0.780, 0.670, 0.561, 0.451, 0.341 0.1099
ring (self + next) 0.931, 0.861, 0.792, 0.723, 0.653, 0.584 0.0694
===================== ========================================== ===========
The per-level figures are :math:\tau \log 8, :math:\tau \log 3 and
:math:\tau \log 2 respectively — the frames' branching factors — and
each matches :func:box_width_entropy to four decimals. The
degradation is linear and predictable, but it is not negligible on a
densely connected frame: the complete frame above floors at depth 5,
exactly as :math:k^* predicts. Compute the budget rather than
assuming it, and check deep nests with
:func:torchmodal.diagnostics.gradient_health.
Batched input. A leading batch dimension is accepted on both
arguments: prop_bounds of (B, |W|, 2) against accessibility of
(B, |W|, |W|) returns (B, |W|, 2), and any number of leading
dimensions works. Results are bit-identical to looping over the batch.
Point-valued input is recognised by carrying exactly one dimension fewer
than the relation, which stays unambiguous even when |W| == 2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
Truth bounds of shape |
required |
accessibility
|
Tensor
|
Accessibility matrix of shape |
required |
tau
|
float
|
Temperature. Default 0.1. Ignored when |
0.1
|
top_k
|
int | None
|
If set, aggregate only the |
None
|
precision
|
float | None
|
Target bracket width, as an alternative to |
None
|
mode
|
str
|
|
'soft'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of shape |
Tensor
|
bounds. |
Source code in torchmodal/functional.py
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 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 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | |
possibility ¶
possibility(prop_bounds: Tensor, accessibility: Tensor, tau: float = 0.1, top_k: int | None = None, precision: float | None = None, mode: str = 'soft') -> Tensor
Possibility (Diamond / ♢) operator — differentiable Kripke semantics.
Computes truth bounds for ♢ϕ across all worlds. For each world w:
.. math:: L_{\Diamond\phi,w} = \operatorname{conv_pool}\tau \bigl( x{w'}, \; x_{w'} \bigr), \quad x_{w'} = \tilde{A}{w,w'} + L{\phi,w'} - 1
.. math:: U_{\Diamond\phi,w} = \operatorname{smooth_max}\tau \bigl{ \tilde{A}{w,w'} + U_{\phi,w'} - 1 \bigr}_{w' \in W}
The operator acts as an "evidence scout": it activates if it finds any world that is both accessible and where ϕ is true.
Top-k aggregation. With top_k=k each endpoint aggregates only
the k largest of its own conjunction terms — Ã + L - 1 for the
lower bound, Ã + U - 1 for the upper — so the true maximum is
always among the kept terms: L_♢ <= max and U_♢ >= max still
hold, the smooth upper bound is within tau * log(k) of the crisp
maximum, nothing depends on |W|, and gradients reach exactly the
k selected entries of à per endpoint. See :func:necessity
for why the selection must be made on the aggregated terms rather than
on à alone.
Exact mode. mode="exact" evaluates at zero temperature, using the
true extremum in place of the smooth aggregators. The bracket is then
exact — gap 0 — and there is no gradient. Two properties follow that
the soft mode does not have:
- it is monotone in
A, on both endpoints, because a hardminandmaxare (verified: 0 violations over 300 random perturbations, against 247 and 252 for theconv_poolendpoints in soft mode); - interval inputs propagate soundly through it, which is what lets it serve as an abstract interpreter over a modal transition system.
Use soft mode to learn and exact mode to certify: train a relation, then
round it and re-evaluate exactly to obtain an answer that owes nothing to
the temperature. See :mod:torchmodal.fixpoint for the CTL operators
built on this mode.
Accumulated slack under nesting. By the duality
♢ϕ ≡ ¬□¬ϕ the ♢ interval widens by the same
:math:\tau H(w) \le \tau \log n per level as □ — see the measured
table in :func:necessity. A nest of ♢ operators therefore drifts
toward the ceiling at the same rate that a nest of □ operators drifts
toward the floor.
Batched input. A leading batch dimension is accepted on both
arguments: prop_bounds of (B, |W|, 2) against accessibility of
(B, |W|, |W|) returns (B, |W|, 2), and any number of leading
dimensions works. Results are bit-identical to looping over the batch.
Point-valued input is recognised by carrying exactly one dimension fewer
than the relation, which stays unambiguous even when |W| == 2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
Truth bounds of shape |
required |
accessibility
|
Tensor
|
Accessibility matrix |
required |
tau
|
float
|
Temperature. Default 0.1. Ignored when |
0.1
|
top_k
|
int | None
|
If set, aggregate only the |
None
|
precision
|
float | None
|
Target bracket width, as an alternative to |
None
|
mode
|
str
|
|
'soft'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of shape |
Tensor
|
bounds. |
Source code in torchmodal/functional.py
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
serialize ¶
Make a relation serial by adding a self-loop at every dead end.
A relation is serial when every world has at least one successor. Several
operators in this library are only sound on a serial frame — notably
:func:until_graph with quantifier="box", and the universal CTL
operators in :mod:torchmodal.fixpoint, because at a dead end a universal
modality is vacuously satisfied and a path that simply stops counts as
success.
This is the standard repair used by model checkers: a state with no outgoing transition gets a self-loop, so "stuck" becomes "stutters forever". It changes the frame, not the semantics of the operators, and the change is confined to worlds that had nothing to say anyway.
What it guarantees. Every row of the result has an entry of at least
1.0 where the input row's maximum was below threshold; rows that
already had a successor are returned untouched, so a serial input is a
fixed point of this function.
.. note::
A self-loop is not free of consequences: a dead end repaired this way
satisfies EG phi whenever phi holds there, because stuttering
is an infinite path. That is the intended reading in model checking,
but it is a modelling decision and worth stating when you report a
result on a repaired frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
|
required |
threshold
|
float
|
A row whose maximum falls below this counts as a dead end. Default 0.5, which is the crisp reading for a graded relation. |
0.5
|
Returns:
| Type | Description |
|---|---|
Tensor
|
A relation of the same shape, serial at |
Example
import torch from torchmodal.functional import serialize A = torch.zeros(3, 3) A[0, 1] = 1.0 # world 2 is a dead end serialize(A)[2, 2].item() 1.0 serialize(A)[0, 0].item() # world 0 already had a successor 0.0
Source code in torchmodal/functional.py
auto_tau ¶
auto_tau(accessibility: Tensor, target_width: float, prop_bounds: Tensor | None = None, top_k: int | None = None, tol: float = 1e-09, max_iter: int = 80) -> float
Temperature achieving a target bracket width — the inverse of the gap.
Every other entry point in this module asks for a temperature and tells
you, afterwards, how wide the resulting bracket is. This inverts that:
state the imprecision you can tolerate, and get the tau that delivers
it.
Which direction it errs. The returned temperature is always safe —
the realised width is at most target_width, never more — so a bound
computed at this temperature encloses the crisp value to within the
requested tolerance.
Two modes:
- Closed form (
prop_bounds=None). Uses the frame-only bound :math:\tau H(w) \le \tau \log n, giving
.. math:: \tau = \varepsilon / \log n,
with n the number of aggregated terms (top_k, else |W|).
This holds for any proposition, so it is the temperature to use when
the bounds are not yet known — during training, for instance, where they
change every step. It is conservative: since :math:H \le \log n with
equality only when every term ties, the realised width is usually well
under target.
- Exact (
prop_boundssupplied). Bisects on the true :func:box_width_entropyfor those bounds, returning the largesttauwhose worst-case per-world width still meets the target. This is tighter — often by a wide margin on a non-uniform frame — and a largertaumeans better-conditioned gradients, so prefer it whenever the bounds are available.
.. note::
The width is monotone non-decreasing in tau (it vanishes as
:math:\tau \to 0, where the softmin weights concentrate on a single
term, and grows to :math:\tau \log n as the weights flatten), which
is what makes the bisection well posed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
Accessibility matrix |
required |
target_width
|
float
|
The bracket width to achieve, in truth units. Must be positive. |
required |
prop_bounds
|
Tensor | None
|
Optional |
None
|
top_k
|
int | None
|
Match the |
None
|
tol
|
float
|
Bisection tolerance on |
1e-09
|
max_iter
|
int
|
Maximum bisection steps. Default 80. |
80
|
Returns:
| Type | Description |
|---|---|
float
|
A temperature, as a Python float. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
import torch from torchmodal.functional import auto_tau, box_width_entropy A = torch.ones(10, 10) tau = auto_tau(A, target_width=0.05) bool(box_width_entropy(A, torch.full((10, 2), 0.5), ... tau=tau).max() <= 0.05 + 1e-9) True
Source code in torchmodal/functional.py
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | |
box_width_entropy ¶
box_width_entropy(accessibility: Tensor, prop_bounds: Tensor, tau: float = 0.1, top_k: int | None = None) -> Tensor
Per-world interval width contributed by one :func:necessity level.
The gap between the two endpoints of a □ neuron is not a bound — it is
an identity. For a common term vector :math:\mathbf{x},
.. math:: \operatorname{conv_pool}\tau(\mathbf{x}, -\mathbf{x}) - \operatorname{smooth_min}\tau(\mathbf{x}) = \tau\, H\bigl(\operatorname{softmax}(-\mathbf{x}/\tau)\bigr),
where :math:H is the Shannon entropy in nats. This function returns
the right-hand side per world, evaluated on the □ implication terms
:math:x_{w,w'} = (1 - \tilde{A}_{w,w'}) + U_{\phi,w'}.
What it bounds. This is an exact equality, not a bound: it is the
width that one modal level adds, so U_□ - L_□ decomposes as
.. math:: \underbrace{\tau H(w)}{\text{this function}} \;+\; \underbrace{ \operatorname{smooth_min}\tau(\mathbf{x}U) - \operatorname{smooth_min}\tau(\mathbf{x}L) }{\text{incoming width, propagated}} .
When prop_bounds is point-valued (or L == U) the second term
vanishes and the return value equals U_□ - L_□ exactly — provided
the □ output clamp does not engage. :func:necessity clamps its
result into [0, 1]; where a raw endpoint falls outside that range the
clamp truncates the interval and the measured width is smaller than
the entropy. Verified to 3.9e-16 in float64 over the unclamped regime.
Why it is useful. The quantity is bounded by :math:\tau \log n
(:math:n = number of aggregated terms, i.e. top_k or |W|),
with equality iff every term ties. It therefore:
- turns the faithful-nesting depth ceiling into a computed quantity,
:math:
k^* = \varepsilon / (\tau \bar{H}), rather than a guess; - gives each :math:
\squarea cheap tightness diagnostic — a large value means the frame is near-uniform and the bound is loose; - is exactly the dead zone of :func:
contradictionapplied after a □ neuron: a bound crossing smaller than this width is absorbed and produces neither loss nor gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
Accessibility matrix |
required |
prop_bounds
|
Tensor
|
Truth bounds |
required |
tau
|
float
|
Temperature. Must match the |
0.1
|
top_k
|
int | None
|
Match the |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of shape |
Tensor
|
□ level contributes at each source world. |
Example
import torch from torchmodal.functional import box_width_entropy, necessity A = torch.ones(6, 6) b = torch.full((6, 2), 0.5) # point-valued: L == U w = box_width_entropy(A, b, tau=0.1) box = necessity(b, A, tau=0.1) bool(torch.allclose(w, box[:, 1] - box[:, 0], atol=1e-6)) True
Source code in torchmodal/functional.py
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 | |
necessity_mts ¶
necessity_mts(prop_bounds: Tensor, must: Tensor, may: Tensor, tau: float = 0.1, top_k: int | None = None, mode: str = 'soft') -> Tensor
Necessity over a modal transition system.
A modal transition system carries two relations rather than one: must,
the transitions that are required to exist, and may, those that are
permitted. Well-formedness is must <= may pointwise, and it is checked.
This is an abstraction of a set of concrete Kripke frames — every frame
whose relation lies between must and may. The returned interval
therefore brackets the value of :math:\Box\varphi on all of them at
once, which is what makes it useful for verification: a conclusion proved
here holds for every concretisation.
Which relation each endpoint uses. :math:\Box is universal, so more
transitions make it harder to satisfy:
- the lower bound quantifies over
may— it must survive every transition that could exist; - the upper bound quantifies over
must— it need only hold across the transitions that definitely exist.
:func:possibility_mts swaps them, being existential. The two are duals.
Reduces exactly. With must == may == A this returns exactly
necessity(prop_bounds, A, ...); the single-relation operator is the
special case where nothing is uncertain.
.. note::
Use mode="exact" when the result is meant as a certificate.
Interval inputs propagate soundly through the exact endpoints, which
are monotone in the relation; the soft endpoints are not (see
:func:conv_pool), so a soft interval evaluation is a relaxation of an
abstraction and only the outer enclosure survives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
|
required |
must
|
Tensor
|
|
required |
may
|
Tensor
|
|
required |
tau
|
float
|
Temperature. Default 0.1. |
0.1
|
top_k
|
int | None
|
As on :func: |
None
|
mode
|
str
|
|
'soft'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the system is ill-formed ( |
Example
import torch from torchmodal.functional import necessity_mts, necessity A = torch.rand(4, 4) b = torch.rand(4, 2).sort(dim=1).values bool(torch.equal(necessity_mts(b, A, A), necessity(b, A))) True
Source code in torchmodal/functional.py
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
possibility_mts ¶
possibility_mts(prop_bounds: Tensor, must: Tensor, may: Tensor, tau: float = 0.1, top_k: int | None = None, mode: str = 'soft') -> Tensor
Possibility over a modal transition system.
The existential dual of :func:necessity_mts. :math:\Diamond is
satisfied by a single witness, so more transitions make it easier:
- the lower bound quantifies over
must— the witness has to be a transition that definitely exists; - the upper bound quantifies over
may— any permitted transition could serve.
Reduces exactly. With must == may == A this returns exactly
possibility(prop_bounds, A, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
|
required |
must
|
Tensor
|
|
required |
may
|
Tensor
|
|
required |
tau
|
float
|
Temperature. Default 0.1. |
0.1
|
top_k
|
int | None
|
As on :func: |
None
|
mode
|
str
|
|
'soft'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the system is ill-formed ( |
Source code in torchmodal/functional.py
until ¶
Until (U) operator — differentiable temporal semantics.
Computes truth bounds for ϕ U ψ ("ϕ holds until ψ becomes true")
over a forward-time accessibility structure. For each time step t:
.. math:: (\phi\;\mathcal{U}\;\psi)t = \bigvee{t' \geq t} \Bigl(\psi_{t'} \;\wedge\; \bigwedge_{t \leq s < t'} \phi_s\Bigr)
The implementation uses a backward dynamic-programming sweep that remains fully differentiable:
.. math:: U_t = \psi_t \;\lor\; (\phi_t \;\land\; U_{t+1})
with U_T = ψ_T at the final time step. All connectives use
Łukasiewicz fuzzy logic (see :func:conjunction, :func:disjunction)
so that the computation stays in [0, 1] and gradients flow smoothly.
This closes the expressiveness gap with STLCG (Leung et al., 2023) which supports the Until operator for signal temporal logic.
.. warning::
This operator is inert with respect to its relation. Only
accessibility.shape[0] is read, to obtain T; no aggregation
over accessibility takes place and no autograd path runs from
the result back to it. until(phi, psi, A) is bit-identical for
A = triu(ones) and A = zeros, and deleting an edge of the
chain does not change the output. The operator is correct for a
total order — consecutive time steps — and only for that. For
an arbitrary or learned relation, where "is there still a path?" is
the question, use :func:until_graph, whose bounds do depend on
the relation and do carry gradient into it.
.. warning::
Its Łukasiewicz backward sweep floors the lower bound. Each
step costs 1 - L_phi: over a 6-step chain with L_phi = 0.9
and ψ true only at the end, the lower bounds are
0.5, 0.6, 0.7, 0.8, 0.9, 1.0. That decay is the operator, not
the data, and for a long enough horizon the lower bound reaches 0
with no gradient. :func:until_graph uses idempotent Gödel
connectives instead and does not floor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phi_bounds
|
Tensor
|
Truth bounds for ϕ, shape |
required |
psi_bounds
|
Tensor
|
Truth bounds for ψ, shape |
required |
accessibility
|
Tensor
|
Forward-time accessibility matrix |
required |
.. note::
The tau argument was removed in 0.7.0. It never had any
effect — the backward DP contains no smooth aggregation, so no
temperature enters it — and it was deprecated from 0.2.2 onward.
Passing it now raises TypeError; delete it from the call. If you
wanted a temperature-controlled, relation-aware Until, that is
:func:until_graph.
Returns:
| Type | Description |
|---|---|
Tensor
|
Truth bounds for |
Source code in torchmodal/functional.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 | |
until_graph ¶
until_graph(phi_bounds: Tensor, psi_bounds: Tensor, accessibility: Tensor, tau: float = 0.1, tau_decay: float = 0.5, max_iter: int = 50, tol: float = 1e-06, quantifier: str = 'diamond') -> Tensor
Relation-aware Until — least fixpoint of U = ψ ∨ (φ ∧ ♢U).
Unlike :func:until, which reads its accessibility only for its
size, this operator aggregates over the relation: its bounds
depend on which edges exist and gradients flow back into them. That
makes it the operator to use with a learned or arbitrary (cyclic,
branching, disconnected) Kripke frame, where the question "is there
still a path along which ϕ holds until ψ?" has a non-trivial answer.
The fixpoint is reached by iterating
.. math:: U^{(0)} = \psi, \qquad U^{(j+1)} = \psi \;\vee_G\; \bigl(\phi \;\wedge_G\; \Diamond_{\tau_j} U^{(j)}\bigr)
to convergence, where :math:\vee_G and :math:\wedge_G are the
Gödel connectives (max and min). Gödel is used rather than
Łukasiewicz because it is idempotent: the iteration therefore has a
genuine fixpoint instead of decaying by 1 - L_phi per step the way
:func:until does, so the lower bound does not floor. The sequence is
monotone non-decreasing and bounded above by 1, so it converges.
The temperature is annealed across sweeps, :math:\tau_j = \tau
\rho^j with :math:\rho = tau_decay, so successive modal steps
are progressively sharper and the slack accumulated over the whole
iteration is a geometric series rather than a growing one.
What it bounds, and the gap. The returned [L, U] brackets the
crisp (τ → 0, Boolean-relation) value of ϕ U ψ evaluated over
the same frame: L <= crisp <= U. The connectives are exact — Gödel
min / max introduce no error — so the only relaxation is the
modal ♢ step, which contributes at most :math:\tau_j \log |W| per
sweep on each endpoint. Summed over the annealed schedule the total
gap is bounded by
.. math:: \frac{\tau \log |W|}{1 - \rho},
independent of the number of iterations. Setting tau_decay=1.0
disables annealing and the gap grows linearly in the sweep count
instead.
.. warning::
quantifier="box" computes AU ("along every path") and is
sound only on a serial relation — one where every world has at
least one successor. At a dead end □U is vacuously 1, so a path
that merely stops satisfies the formula. This is measured, not
hypothetical: on a 6-step chain the box variant returns 0.9
everywhere regardless of connectivity. Use "diamond" (EU,
"there is a path") unless the frame is known to be serial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phi_bounds
|
Tensor
|
Truth bounds for ϕ, shape |
required |
psi_bounds
|
Tensor
|
Truth bounds for ψ, same shape as |
required |
accessibility
|
Tensor
|
Accessibility matrix |
required |
tau
|
float
|
Initial temperature for the modal step. Default 0.1. |
0.1
|
tau_decay
|
float
|
Geometric annealing factor :math: |
0.5
|
max_iter
|
int
|
Maximum fixpoint sweeps. Default 50. |
50
|
tol
|
float
|
Stop once the largest bound change in a sweep falls below this. Default 1e-6. |
1e-06
|
quantifier
|
str
|
|
'diamond'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Truth bounds for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
import torch from torchmodal.functional import until_graph T = 6 A = torch.zeros(T, T) A[torch.arange(T - 1), torch.arange(1, T)] = 1.0 # a chain phi = torch.stack([torch.full((T,), 0.9), torch.ones(T)], -1) psi = torch.zeros(T, 2) psi[T - 1] = 1.0 round(until_graph(phi, psi, A)[0, 0].item(), 3) 0.9 A[2, 3] = 0.0 # cut the path round(until_graph(phi, psi, A)[0, 0].item(), 3) 0.0
Source code in torchmodal/functional.py
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 | |
contradiction ¶
Compute contradiction loss from truth bounds.
A contradiction arises when a lower bound exceeds an upper bound, an inconsistency no classical truth assignment can satisfy:
.. math:: \mathcal{L}_{\text{contra}} = \sum \max(0,\; L - U).
Two equivalent call forms are accepted:
- Stacked —
contradiction(bounds)withboundsof shape(..., 2)holding[L, U]on the last dimension. This is the bound contradictionReLU(L_phi - U_phi). - Split —
contradiction(L, U)with the lower and upper sources passed as separate tensors of matching shape, for when they are computed apart. For examplecontradiction(box, dia)penalises a necessity that exceeds its possibility (the modalBox phi -> Diamond phiconsistency requirement).
The two forms agree by construction::
contradiction(L, U) == contradiction(torch.stack([L, U], dim=-1))
.. warning::
Dead zone after a modal neuron. Applied to the output of a □
neuron this loss is identically zero, with zero gradient, until
the underlying bound crossing exceeds the box width
:func:box_width_entropy — that is, :math:\tau H(w), at most
:math:\tau \log n. The modal level widens the interval by
exactly that much, so any smaller crossing is absorbed before it
reaches the loss.
The correspondence is exact, not approximate. Driving a crossing
c through a complete frame at tau = 0.1:
=========== ==================== ==================
fan-in n dead zone (measured) :math:\tau\log n
=========== ==================== ==================
3 0.109861 0.109861
6 0.179176 0.179176
10 0.230259 0.230259
=========== ==================== ==================
Past the edge the loss is linear with unit slope per world.
Consequence: L_contra must not be the sole guard against
a degenerate optimum. A model can sit in a mildly contradictory
state indefinitely, paying nothing and receiving no gradient to
leave it. Either anneal tau downward (shrinking the dead zone
toward 0), check the raw pre-modal bounds as well, or pair the
loss with :func:torchmodal.diagnostics.gradient_health.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds
|
Tensor
|
Either a |
required |
upper
|
Tensor | None
|
Upper-bound tensor matching |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar contradiction loss, summed over all elements. |
Source code in torchmodal/functional.py
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 | |
announce ¶
announce(accessibility: Tensor, psi_bounds: Tensor, trust: Tensor | float = 1.0, tnorm: str = 'product') -> tuple[Tensor, Tensor]
Graded, trust-weighted public announcement of :math:\psi.
A public announcement is the dynamic-epistemic-logic update that edits the
model: crisp public announcement logic relativises the relation to the
worlds where :math:\psi holds. This is its graded, interval-valued
counterpart, returning the two relations that bracket it:
.. math:: A^{lo}{w,w'} &= A{w,w'} \otimes (1 - t \cdot (1 - U_{\psi,w'})) \ A^{hi}{w,w'} &= A{w,w'} \otimes (1 - t \cdot (1 - L_{\psi,w'}))
:math:A^{lo} cuts only the worlds that are certainly :math:\neg\psi,
so it is the largest surviving relation; :math:A^{hi} cuts every world
not certainly :math:\psi, so it is the smallest.
What it bounds. Since :math:L_\psi \le V_\psi \le U_\psi, the crisp
relativised relation is sandwiched pointwise:
.. math:: A^{hi} \le A^{crisp} \le A^{lo}.
That sandwich is what makes :func:necessity_after interval-sound; it is
verified over random graded inputs in the test-suite. With trust=1 and a
crisp :math:\psi the pair collapses onto crisp PAL relativisation, and
trust=0 returns the relation unchanged.
.. warning::
Worlds cut by the announcement become dead ends, where
:math:\square is vacuously true, whereas crisp PAL deletes them from
the model. The two therefore disagree at removed worlds by construction
— a cut world reports :math:K \approx [1, 1]. Restrict any comparison
against a crisp checker to the surviving worlds, and check that the
actual world survives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
|
required |
psi_bounds
|
Tensor
|
|
required |
trust
|
Tensor | float
|
How far the announcement cuts, in [0, 1]. Scalar, |
1.0
|
tnorm
|
str
|
Conjunction combining the relation with the survival factor —
|
'product'
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor]
|
|
Example
import torch from torchmodal.functional import announce A = torch.ones(3, 3) psi = torch.tensor([[1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]) lo, hi = announce(A, psi) bool((lo[:, 1] == 0).all() and (hi[:, 1] == 0).all()) True
Source code in torchmodal/functional.py
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 | |
necessity_after ¶
necessity_after(prop_bounds: Tensor, accessibility: Tensor, psi_bounds: Tensor, trust: Tensor | float = 1.0, tau: float = 0.1, tnorm: str = 'product', top_k: int | None = None) -> Tensor
Knowledge after an announcement: :math:[\psi] \square \varphi.
The lower endpoint is taken through :math:A^{lo} and the upper through
:math:A^{hi} (see :func:announce). The direction is not arbitrary: a
larger relation constrains :math:\square more, so the largest surviving
relation gives the lower bound.
What it bounds. Sound in both directions —
:math:L \le \square\varphi^{crisp} \le U on surviving worlds — reducing
to crisp public-announcement logic as tau -> 0 with trust=1.
The proof route matters, because the obvious one is wrong: it is not
monotonicity of the box neuron, whose upper endpoint uses
:func:conv_pool and is not monotone. It is monotonicity of the hard
min under the pointwise sandwich of :func:announce, composed with the
one-sided enclosure of the aggregators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
|
required |
accessibility
|
Tensor
|
|
required |
psi_bounds
|
Tensor
|
|
required |
trust
|
Tensor | float
|
See :func: |
1.0
|
tau
|
float
|
Temperature. Default 0.1. |
0.1
|
tnorm
|
str
|
See :func: |
'product'
|
top_k
|
int | None
|
Passed through to :func: |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in torchmodal/functional.py
group_announce ¶
group_announce(accessibility: Tensor, psi_bounds: Tensor, recipients: Tensor, trust: Tensor | float = 1.0, tnorm: str = 'product') -> tuple[Tensor, Tensor]
Action-model update for a message delivered to part of the group.
A public announcement reaches everyone; a message on a private or group
channel does not. Recipients update their relation by :func:announce,
non-recipients keep theirs unchanged — the graded counterpart of a
product update with two events, "heard" and "did not hear".
Why this is not a public announcement. Common knowledge is created only
by an event public to the whole group. After a group announcement the
recipients' knowledge rises while the others' does not, so the group's
:math:C_G need not move at all — which is exactly what makes
who-hears-what a real design question rather than a formality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility
|
Tensor
|
|
required |
psi_bounds
|
Tensor
|
|
required |
recipients
|
Tensor
|
|
required |
trust
|
Tensor | float
|
See :func: |
1.0
|
tnorm
|
str
|
See :func: |
'product'
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor]
|
|