torchmodal.nn¶
torchmodal.nn.operators ¶
torchmodal.nn.operators ~~~~~~~~~~~~~~~~~~~~~~~
Differentiable aggregation operators as nn.Module wrappers.
These modules wrap the functional API in :mod:torchmodal.functional,
adding learnable or configurable temperature parameters.
.. note::
Named SmoothMin / SmoothMax (not Softmin / Softmax)
to avoid confusion with the standard probability-normalization
torch.softmax. Legacy aliases Softmin and Softmax are
provided for backward compatibility.
SmoothMin ¶
Bases: Module
Differentiable smooth minimum module (log-sum-exp lower bound).
Sound lower bound on :func:torch.min:
smooth_min(x) <= min(x) for x_i \in [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
Initial temperature. Default 0.1. |
0.1
|
learnable
|
bool
|
If |
False
|
dim
|
int
|
Dimension to aggregate over. Default -1. |
-1
|
Source code in torchmodal/nn/operators.py
SmoothMax ¶
Bases: Module
Differentiable smooth maximum module (log-sum-exp upper bound).
Sound upper bound on :func:torch.max:
smooth_max(x) >= max(x) for x_i \in [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
Initial temperature. Default 0.1. |
0.1
|
learnable
|
bool
|
If |
False
|
dim
|
int
|
Dimension to aggregate over. Default -1. |
-1
|
Source code in torchmodal/nn/operators.py
ConvPool ¶
Bases: Module
Convex pooling module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
Initial temperature. Default 0.1. |
0.1
|
learnable
|
bool
|
If |
False
|
dim
|
int
|
Dimension to pool over. Default -1. |
-1
|
Source code in torchmodal/nn/operators.py
Softmin ¶
Deprecated alias for :class:SmoothMin.
Source code in torchmodal/nn/operators.py
Softmax ¶
Deprecated alias for :class:SmoothMax.
Source code in torchmodal/nn/operators.py
torchmodal.nn.connectives ¶
torchmodal.nn.connectives ~~~~~~~~~~~~~~~~~~~~~~~~~
Propositional logic connectives as nn.Module wrappers.
These implement Łukasiewicz fuzzy logic operators over real-valued truth bounds in [0, 1], following the LNN framework (Riegel et al., 2020) as extended by MLNN (Sulc, 2026).
Each connective operates on truth bounds [L, U] ⊆ [0, 1] and
preserves the bound invariant L <= U.
Negation ¶
Bases: Module
Fuzzy negation: :math:\neg x = 1 - x.
For bounds, swaps and negates: [L', U'] = [1-U, 1-L].
Source code in torchmodal/nn/connectives.py
Conjunction ¶
Bases: Module
Łukasiewicz conjunction (fuzzy AND).
For bounds:
- L_{a∧b} = max(0, L_a + L_b - 1)
- U_{a∧b} = min(U_a, U_b)
Source code in torchmodal/nn/connectives.py
Disjunction ¶
Bases: Module
Łukasiewicz disjunction (fuzzy OR).
For bounds:
- L_{a∨b} = max(L_a, L_b)
- U_{a∨b} = min(1, U_a + U_b)
Source code in torchmodal/nn/connectives.py
Implication ¶
Bases: Module
Łukasiewicz implication: :math:a \to b = \min(1, 1 - a + b).
For bounds:
- L_{a→b} = max(0, 1 - U_a + L_b) (strongest constraint)
- U_{a→b} = min(1, 1 - L_a + U_b)
Source code in torchmodal/nn/connectives.py
torchmodal.nn.modal ¶
torchmodal.nn.modal ~~~~~~~~~~~~~~~~~~~
Core modal operator neurons: Necessity (□) and Possibility (♢).
These are the central building blocks of the MLNN framework, implementing differentiable Kripke semantics (Section 3.2.1 of the paper).
The Necessity neuron acts as a "weakest link" detector — aggregating truth values across accessible worlds via differentiable implication.
The Possibility neuron acts as an "evidence scout" — seeking any accessible world where the proposition holds.
Necessity ¶
Bases: Module
Necessity (Box / □) neuron.
Implements the differentiable universal quantification over accessible worlds:
.. 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{ (1 - \tilde{A}{w,w'}) + U_{\phi,w'} \bigr}_{w' \in W}
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). The selection is made on the aggregated
terms, not on à alone, so the true minimum is always kept: the
bounds stay sound, the smooth lower bound is within tau * log(k)
of the crisp minimum, and the result does not depend on |W|. This
is where top-k masking belongs — it used to live on the accessibility
modules, which was unsound (see :func:torchmodal.functional.necessity).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
Temperature for soft aggregation. Default 0.1. |
0.1
|
learnable_tau
|
bool
|
If |
False
|
top_k
|
Optional[int]
|
If set, aggregate only the |
None
|
For temperature annealing during training, update the temperature via
:meth:set_tau rather than assigning to .tau (buffers/parameters
cannot be assigned a plain float).
Example::
>>> box = torchmodal.nn.Necessity(tau=0.1)
>>> # prop_bounds: (|W|, 2) truth bounds for proposition ϕ
>>> # A: (|W|, |W|) accessibility matrix
>>> box_phi = box(prop_bounds, A)
>>> box.set_tau(0.05) # annealing
>>> box_k = torchmodal.nn.Necessity(tau=0.1, top_k=8) # k-neighbourhoods
Source code in torchmodal/nn/modal.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
|
required |
accessibility
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in torchmodal/nn/modal.py
set_tau ¶
Possibility ¶
Bases: Module
Possibility (Diamond / ♢) neuron.
Implements the differentiable existential quantification over accessible worlds:
.. math:: L_{\Diamond\phi,w} = \operatorname{conv_pool}\tau \bigl{ \tilde{A}{w,w'} + L_{\phi,w'} - 1 \bigr}_{w' \in W}
.. math:: U_{\Diamond\phi,w} = \operatorname{smooth_max}\tau \bigl{ \tilde{A}{w,w'} + U_{\phi,w'} - 1 \bigr}_{w' \in W}
Satisfies modal duality: ♢ϕ ≡ ¬□¬ϕ.
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 kept, the bounds stay
sound, and the smooth upper bound is within tau * log(k) of the
crisp maximum. See :class:Necessity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
Temperature for soft aggregation. Default 0.1. |
0.1
|
learnable_tau
|
bool
|
If |
False
|
top_k
|
Optional[int]
|
If set, aggregate only the |
None
|
For temperature annealing during training, update the temperature via
:meth:set_tau rather than assigning to .tau.
Example::
>>> diamond = torchmodal.nn.Possibility(tau=0.1)
>>> dia_phi = diamond(prop_bounds, A)
Source code in torchmodal/nn/modal.py
forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_bounds
|
Tensor
|
|
required |
accessibility
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in torchmodal/nn/modal.py
set_tau ¶
torchmodal.nn.accessibility ¶
torchmodal.nn.accessibility ~~~~~~~~~~~~~~~~~~~~~~~~~~~
Accessibility relation modules for Kripke structures.
Provides four parameterizations:
- FixedAccessibility: Static, user-defined binary relation.
- LearnableAccessibility: Direct learnable logit matrix → sigmoid. O(|W|²) parameters — suitable for |W| ≤ ~1000.
- MetricAccessibility: Metric-learning parameterization using latent embeddings with inner-product kernel. O(d·|W|) parameters — scales to |W| = 20,000+.
- AttentionAccessibility: Multi-head self-attention over world representations. O(d²) parameters — suitable when worlds have rich feature representations and the accessibility pattern is context-dependent. Addresses the reviewer concern (R1) that the kernel parameterization is not the only sub-quadratic alternative.
Top-k is not an accessibility-module concern. Earlier releases took a
top_k argument here and zeroed all but the k largest entries of each
row of A before the modal operators saw it. That was unsound: □ and ♢
aggregate (1 - A) + L and A + U - 1, so choosing neighbours by
A alone can drop the world whose L / U carries the extremum,
and the zeroed entries still enter the log-sum-exp with mass that grows
with |W| and drives every bound to [0, 1]. Top-k aggregation now
lives on :class:torchmodal.nn.Necessity / :class:~torchmodal.nn.Possibility
(top_k=), which select the k extreme aggregation terms per endpoint.
top_k here is deprecated and ignored (with a DeprecationWarning).
What remains available here is sparsify=k: a deliberately sparsified
relation in which each world accesses only its k most accessible
worlds. That is a modelling choice — it defines a different Kripke frame —
not an aggregation optimisation, and the operators then reason soundly
about the sparsified frame.
FixedAccessibility ¶
Bases: Module
Fixed (non-learnable) accessibility relation.
Wraps a user-defined binary relation matrix as a frozen buffer. Useful for deductive mode where the logical structure is known (e.g., Sudoku constraints, temporal flow, grammatical rules).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relation
|
Tensor
|
Binary accessibility matrix of shape |
required |
sparsify
|
Optional[int]
|
If set, keep only the |
None
|
top_k
|
Optional[int]
|
Deprecated and ignored. Masking |
None
|
Example::
>>> # Sudoku: cells in same row/col/box are accessible
>>> R = build_sudoku_accessibility(9)
>>> access = FixedAccessibility(R)
>>> A = access() # (81, 81) binary matrix
Source code in torchmodal/nn/accessibility.py
forward ¶
LearnableAccessibility ¶
Bases: Module
Learnable accessibility relation via direct logit matrix.
Parameterizes R as a matrix of learnable logits passed through
sigmoid: A = σ(logits). Suitable for small-to-medium world
sets (|W| ≤ ~1000).
The parameter space is O(|W|²).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_worlds
|
int
|
Number of possible worlds |W|. |
required |
init_bias
|
float
|
Initial bias for logits. Negative values encode a "prior of distrust" (default -2.0). |
-2.0
|
reflexive
|
bool
|
If |
True
|
sparsify
|
Optional[int]
|
If set, keep only the |
None
|
top_k
|
Optional[int]
|
Deprecated and ignored. Masking |
None
|
Example::
>>> access = LearnableAccessibility(7, reflexive=True)
>>> A = access() # (7, 7) matrix in [0, 1]
Source code in torchmodal/nn/accessibility.py
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 | |
forward ¶
Returns the accessibility matrix (|W|, |W|) in [0, 1].
Source code in torchmodal/nn/accessibility.py
MetricAccessibility ¶
Bases: Module
Scalable metric-learning accessibility relation.
Maps each world to a latent embedding and computes accessibility via a kernel function:
.. math:: A(w_i, w_j) = \sigma\bigl(h_{w_i}^\top h_{w_j}\bigr)
This reduces the parameter space from O(|W|²) to O(d·|W|) and enables scaling to |W| = 20,000+ on a single GPU.
The encoder can optionally accept external features per world.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_worlds
|
int
|
Number of possible worlds |W|. |
required |
embed_dim
|
int
|
Embedding dimension d. Default 64. |
64
|
input_dim
|
Optional[int]
|
If provided, the encoder takes external features of this dimension. Otherwise, uses learnable embeddings. |
None
|
hidden_dim
|
int
|
Hidden dimension of the encoder MLP. Default 128. |
128
|
reflexive
|
bool
|
Enforce self-accessibility. Default |
True
|
sparsify
|
Optional[int]
|
If set, keep only the |
None
|
top_k
|
Optional[int]
|
Deprecated and ignored. Masking |
None
|
Example::
>>> access = MetricAccessibility(1000, embed_dim=64)
>>> A = access() # (1000, 1000) accessibility matrix
>>> # With external features:
>>> access = MetricAccessibility(100, embed_dim=32, input_dim=384)
>>> A = access(features) # features: (100, 384)
Source code in torchmodal/nn/accessibility.py
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 | |
forward ¶
Compute the accessibility matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Optional[Tensor]
|
Optional external features |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Accessibility matrix |
Source code in torchmodal/nn/accessibility.py
AttentionAccessibility ¶
Bases: Module
Attention-based accessibility relation.
Uses multi-head self-attention over world representations to compute
a context-dependent accessibility matrix. Unlike
:class:MetricAccessibility (which uses a fixed inner-product
kernel), attention weights are input-dependent and can capture
asymmetric relationships naturally.
The parameter count is O(d²) — independent of |W| — making this suitable for settings where worlds have rich feature representations (e.g., sentence embeddings in the Diplomacy experiment).
This addresses Reviewer 1's observation that "if worlds were a space of rich state representations rather than indices, directly learning a kernel does not require quadratic parameters" by providing an alternative that operates entirely in feature space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int
|
Dimension of per-world feature vectors. |
required |
num_heads
|
int
|
Number of attention heads. Default 4. |
4
|
reflexive
|
bool
|
Enforce self-accessibility. Default |
True
|
sparsify
|
Optional[int]
|
If set, keep only the |
None
|
top_k
|
Optional[int]
|
Deprecated and ignored. Masking |
None
|
Example::
>>> access = AttentionAccessibility(input_dim=384, num_heads=4)
>>> features = torch.randn(7, 384) # 7 worlds, 384-d features
>>> A = access(features) # (7, 7) accessibility matrix
Source code in torchmodal/nn/accessibility.py
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 | |
forward ¶
Compute the accessibility matrix from world features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Tensor
|
Per-world features |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Accessibility matrix |
Source code in torchmodal/nn/accessibility.py
top_k_mask ¶
Sparsify an accessibility matrix to its k largest entries per row.
For each world (row), only the k highest accessibility values are
kept; all others are set to 0, i.e. those worlds become
inaccessible. This defines a different (sparser) Kripke frame and is
what the sparsify= option of the accessibility modules applies.
.. warning::
This is a modelling choice, not an aggregation optimisation.
It does not reduce the cost of □ / ♢ (the operators still aggregate
over the full (|W|, |W|) row) and it must not be used to emulate
top-k aggregation: neighbours are chosen by A alone rather than
by the aggregated terms, and the zeroed entries still enter the
log-sum-exp with term 1 + L each, so the bounds drift to
[0, 1] as |W| grows. For sound top-k aggregation with a
tau * log(k) gap use top_k= on
:func:torchmodal.functional.necessity /
:func:~torchmodal.functional.possibility or the
:class:torchmodal.nn.Necessity / :class:~torchmodal.nn.Possibility
modules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
Tensor
|
Accessibility matrix of shape |
required |
k
|
int
|
Number of neighbors to retain per world. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Sparsified accessibility matrix of the same shape. |