Models¶
All models are torch.nn.Modules with the same learning interface:
model.update(x, y) -> votes— one learning step on a batch,model(x)/model.forward(x) -> votes— vote sums(B, n_outputs),model.predict(x),model.predict_proba(x),model.confidence(x),model.rules(),model.clause_expression(j),model.included_mask(),model.state_summary().
Dense (segmentation) models add model.vote_map(x) -> (B, K, H, W),
model.predict(x) -> (B, H, W) and model.clause_map(x); their forward() returns the
folded votes (B·H·W, K).
GraphTsetlinMachine takes a torchtsetlin.data.GraphBatch instead of a tensor and adds
model.node_clause_outputs(g) and model.node_messages(g, layer) (see the
graph guide).
torchtsetlin.models.TsetlinMachine ¶
TsetlinMachine(n_features: Optional[int], n_classes: int, n_clauses: int, T: float, s: float = 10.0, *, weighted: bool = False, max_weight: Optional[int] = None, focused_negative_sampling: bool = False, **kwargs)
Bases: TsetlinMachineBase
Multi-class Tsetlin machine with class-owned clauses of positive/negative polarity.
Each of the n_classes classes owns n_clauses clauses. The first half of them
vote for the class (positive polarity), the second half vote against it (negative
polarity). The class sum is v_k = sum(w_j c_j) - sum(w_j c_j) over the two halves,
clamped to [-T, T], and the prediction is argmax_k v_k.
Learning follows the standard algorithm (Granmo, 2018): for an example of class y
the clauses of y receive feedback with probability (T - v_y)/(2T) (Type I to
positive clauses, Type II to negative ones) and the clauses of one randomly chosen
other class q receive feedback with probability (T + v_q)/(2T) (Type II to
positive, Type I to negative clauses).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
Optional[int]
|
number of Boolean features ( |
required |
n_classes
|
int
|
number of classes ( |
required |
n_clauses
|
int
|
clauses per class. |
required |
T
|
float
|
vote margin (threshold). Larger |
required |
s
|
float
|
specificity. |
10.0
|
weighted
|
bool
|
learn an integer weight per clause (Integer-Weighted TM). Weights start at 1, grow with Type Ia feedback and shrink with Type II feedback (min 1, as in pyTsetlinMachine and tmu). |
False
|
max_weight
|
Optional[int]
|
optional upper bound on the clause weights (PyTsetlinMachineCUDA stores
them as |
None
|
focused_negative_sampling
|
bool
|
sample the negative class proportionally to how strongly it currently votes, instead of uniformly. |
False
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Shape
- input
x:(B, F)Boolean (extra trailing dimensions are flattened). - output of :meth:
forward:(B, n_classes)float vote sums in[-T, T].
Example
model = TsetlinMachine(n_features=12, n_classes=2, n_clauses=20, T=10, s=3.9) votes = model.update(x, y) # learn from a batch, returns pre-update votes pred = model(x).argmax(dim=1) # predict
Source code in src/torchtsetlin/models/classifier.py
predict ¶
predict_proba ¶
Class probabilities (B, n_classes).
method="linear" uses the calibrated score of Abeyrathna et al.,
p_k ∝ (1 + v_k/T)/2; method="softmax" applies a softmax to v/T.
Source code in src/torchtsetlin/models/classifier.py
confidence ¶
clause_info ¶
Metadata for one clause: class, polarity, weight and the literal expression.
Source code in src/torchtsetlin/models/classifier.py
rules ¶
rules(feature_names: Optional[Sequence[str]] = None, class_names: Optional[Sequence[str]] = None, skip_empty: bool = True, polarity: Optional[int] = None, class_index: Optional[int] = None) -> List[str]
Human readable IF ... THEN rules for all (non-empty) clauses.
Source code in src/torchtsetlin/models/classifier.py
torchtsetlin.models.CoalescedTsetlinMachine ¶
CoalescedTsetlinMachine(n_features: Optional[int], n_outputs: int, n_clauses: int, T: float, s: float = 10.0, *, multi_label: bool = False, negative_scale: float = 1.0, max_weight: Optional[int] = None, focused_negative_sampling: bool = False, **kwargs)
Bases: TsetlinMachineBase
Coalesced (multi-output) Tsetlin machine with clause sharing (Glimsdal & Granmo, 2021).
All n_clauses clauses are shared by the n_outputs outputs. Clause j votes for
output i with an integer weight W[j, i]: positive weights vote for, negative
weights against. Vote sums are v = c @ W clamped to [-T, T].
Learning per output i with binary target y_i: with probability
d_i = |q_i - v_i| / (2T) (q_i = T if y_i = 1 else -T) a clause receives
Type I feedback when its weight sign agrees with y_i and Type II feedback otherwise.
Weights of matching, selected clauses move by +1 for y_i = 1 and -1 for
y_i = 0, so a clause can change sides over time.
In multi-class mode (multi_label=False) the target class and one random negative
class are updated per example; in multi-label mode every output is updated with its own
probability (negative outputs scaled by negative_scale).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
Optional[int]
|
Boolean feature count ( |
required |
n_outputs
|
int
|
number of classes (multi-class) or labels (multi-label). |
required |
n_clauses
|
int
|
total number of shared clauses. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
multi_label
|
bool
|
interpret |
False
|
max_weight
|
Optional[int]
|
optional bound on the magnitude of the signed clause weights
( |
None
|
negative_scale
|
float
|
multiplier of the Type II probability for negative outputs in
multi-label mode (the |
1.0
|
focused_negative_sampling
|
bool
|
multi-class only; bias the negative class towards strongly voting classes. |
False
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Source code in src/torchtsetlin/models/coalesced.py
predict ¶
Class indices (B,) (multi-class) or a Boolean (B, n_outputs) matrix.
predict_proba ¶
Probabilities: per-output (1 + v/T)/2 (multi-label) or normalised over classes.
Source code in src/torchtsetlin/models/coalesced.py
rules ¶
rules(feature_names: Optional[Sequence[str]] = None, class_names: Optional[Sequence[str]] = None, skip_empty: bool = True, min_abs_weight: int = 1) -> List[str]
IF ... THEN rules listing every output the clause votes for/against with its weight.
Source code in src/torchtsetlin/models/coalesced.py
torchtsetlin.models.RegressionTsetlinMachine ¶
RegressionTsetlinMachine(n_features: Optional[int], n_clauses: int, T: float, s: float = 10.0, *, y_range: Optional[Tuple[float, float]] = None, weighted: bool = False, max_weight: Optional[int] = None, **kwargs)
Bases: TsetlinMachineBase
Regression Tsetlin machine (Abeyrathna et al.).
All clauses have positive polarity; the vote sum v = sum_j w_j c_j is clamped to
[0, T] and mapped linearly onto the target range:
y_hat = y_min + (v / T) * (y_max - y_min).
Learning: with the target expressed in vote units v* = T (y - y_min)/(y_max - y_min),
every clause receives Type I feedback with probability ((v* - v)/T)**2 when the
prediction is too low, and Type II feedback with probability ((v - v*)/T)**2 when it is
too high. The squared error is the rule of the reference implementations
(pyTsetlinMachine, pyTsetlinMachineParallel and tmu).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
Optional[int]
|
Boolean feature count ( |
required |
n_clauses
|
int
|
number of clauses. |
required |
T
|
float
|
vote margin — also the output resolution ( |
required |
s
|
float
|
specificity. |
10.0
|
y_range
|
Optional[Tuple[float, float]]
|
|
None
|
weighted
|
bool
|
learn integer clause weights (Type Ia |
False
|
max_weight
|
Optional[int]
|
optional upper bound on the clause weights ( |
None
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Source code in src/torchtsetlin/models/regression.py
predict ¶
rules ¶
IF ... THEN +w rules: each matching clause adds w * (y_max - y_min) / T.
Source code in src/torchtsetlin/models/regression.py
torchtsetlin.models.ConvTsetlinMachine ¶
ConvTsetlinMachine(n_classes: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrPair = 10, stride: IntOrPair = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int]] = None, **kwargs)
Bases: _ConvMixin, TsetlinMachine
Convolutional multi-class Tsetlin machine (Granmo et al., 2019).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_classes
|
int
|
number of classes. |
required |
n_clauses
|
int
|
clauses per class. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
patch_size
|
IntOrPair
|
|
10
|
stride
|
IntOrPair
|
window stride. |
1
|
position_encoding
|
bool
|
append thermometer-encoded patch coordinates to each patch. |
True
|
input_shape
|
Optional[Tuple[int, int, int]]
|
|
None
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Shape
- input:
(B, Z, H, W)Boolean ((B, H, W)is treated as one plane). - output:
(B, n_classes)vote sums.
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.ConvCoalescedTsetlinMachine ¶
ConvCoalescedTsetlinMachine(n_outputs: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrPair = 10, stride: IntOrPair = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int]] = None, **kwargs)
Bases: _ConvMixin, CoalescedTsetlinMachine
Convolutional coalesced Tsetlin machine (shared clauses, per-output weights).
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.ConvRegressionTsetlinMachine ¶
ConvRegressionTsetlinMachine(n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrPair = 10, stride: IntOrPair = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int]] = None, **kwargs)
Bases: _ConvMixin, RegressionTsetlinMachine
Convolutional regression Tsetlin machine (Abeyrathna et al., 2021).
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.Conv1dTsetlinMachine ¶
Conv1dTsetlinMachine(n_classes: int, n_clauses: int, T: float, s: float = 10.0, *, kernel_size: int = 5, stride: int = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int]] = None, **kwargs)
Bases: ConvTsetlinMachine
1D convolutional Tsetlin machine for sequences / time series.
Input (B, Z, L) (Z Boolean channels, length L) is handled as a (B, Z, 1, L)
image with a 1 x kernel_size window.
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.Conv3dTsetlinMachine ¶
Conv3dTsetlinMachine(n_classes: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrTriple = (3, 7, 7), stride: IntOrTriple = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int, int]] = None, patches_per_chunk: Optional[int] = None, **kwargs)
Bases: _Conv3dMixin, TsetlinMachine
Convolutional multi-class Tsetlin machine for volumes (3D windows).
The 3D generalisation of :class:ConvTsetlinMachine: windows slide over depth, height
and width, so one clause can find a pattern anywhere in a volume — an MRI/CT stack, or a
(time, H, W) sequence of frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_classes
|
int
|
number of classes. |
required |
n_clauses
|
int
|
clauses per class. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
patch_size
|
IntOrTriple
|
|
(3, 7, 7)
|
stride
|
IntOrTriple
|
window stride (int or |
1
|
position_encoding
|
bool
|
append thermometer-encoded patch coordinates (depth, row, column) to each patch. |
True
|
input_shape
|
Optional[Tuple[int, int, int, int]]
|
|
None
|
patches_per_chunk
|
Optional[int]
|
evaluate at most this many patches together (bounds memory on
large volumes). |
None
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Shape
- input:
(B, Z, D, H, W)Boolean ((B, D, H, W)is treated as one plane). - output:
(B, n_classes)vote sums.
Example
model = Conv3dTsetlinMachine(2, 40, T=15, patch_size=3, position_encoding=False) model.update(volumes, labels) # volumes: (B, 1, 8, 16, 16) Boolean model.clause_patch(0).shape # (Z, kd, kh, kw)
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.Conv3dCoalescedTsetlinMachine ¶
Conv3dCoalescedTsetlinMachine(n_outputs: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrTriple = (3, 7, 7), stride: IntOrTriple = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int, int]] = None, patches_per_chunk: Optional[int] = None, **kwargs)
Bases: _Conv3dMixin, CoalescedTsetlinMachine
3D convolutional coalesced Tsetlin machine (shared clauses, per-output weights).
Arguments as :class:Conv3dTsetlinMachine, with n_outputs instead of n_classes
and n_clauses counting the shared clause pool.
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.Conv3dRegressionTsetlinMachine ¶
Conv3dRegressionTsetlinMachine(n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrTriple = (3, 7, 7), stride: IntOrTriple = 1, position_encoding: bool = True, input_shape: Optional[Tuple[int, int, int, int]] = None, patches_per_chunk: Optional[int] = None, **kwargs)
Bases: _Conv3dMixin, RegressionTsetlinMachine
3D convolutional regression Tsetlin machine.
Arguments as :class:Conv3dTsetlinMachine, without n_classes.
Source code in src/torchtsetlin/models/conv.py
torchtsetlin.models.SegmentationTsetlinMachine ¶
SegmentationTsetlinMachine(n_classes: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrPair = 3, stride: IntOrPair = 1, padding: Union[str, IntOrPair] = 'same', position_encoding: PositionEncoding = False, input_shape: Optional[Tuple[int, int, int]] = None, patches_per_commit: Optional[int] = 128, ignore_index: Optional[int] = None, pixel_order: str = 'raster', class_feedback_p: Optional[Tensor] = None, **kwargs)
Bases: _DenseMixin, TsetlinMachine
Dense per-pixel Tsetlin machine with class-owned clauses.
Each class owns n_clauses clauses (half voting for it, half against), exactly as in
:class:~torchtsetlin.models.TsetlinMachine; the difference is that a pixel, not an
image, is the example. Predictions are label maps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_classes
|
int
|
number of segmentation classes. |
required |
n_clauses
|
int
|
clauses per class. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
patch_size
|
IntOrPair
|
|
3
|
stride
|
IntOrPair
|
output-grid stride ( |
1
|
padding
|
Union[str, IntOrPair]
|
|
'same'
|
position_encoding
|
PositionEncoding
|
|
False
|
input_shape
|
Optional[Tuple[int, int, int]]
|
|
None
|
patches_per_commit
|
Optional[int]
|
commit accumulated feedback every this many pixels
(default |
128
|
pixel_order
|
str
|
|
'raster'
|
ignore_index
|
Optional[int]
|
label value that contributes no feedback and is excluded from metrics (the "void" class of CamVid / Cityscapes / Pascal VOC). |
None
|
class_feedback_p
|
Optional[Tensor]
|
optional |
None
|
**kwargs
|
Any
|
forwarded to :class: |
{}
|
Shape
- input:
(B, Z, H, W)Boolean ((B, H, W)is treated as one plane). - :meth:
forward:(B*Py*Px, n_classes)vote sums (patches folded into the batch). - :meth:
vote_map:(B, n_classes, Py, Px); :meth:predict:(B, Py, Px).
Example
model = SegmentationTsetlinMachine(4, n_clauses=200, T=60, s=10.0, patch_size=3) model.update(x, labels) # x: (B, Z, H, W) bool, labels: (B, H, W) long model.eval(); pred = model.predict(x) # (B, H, W)
Source code in src/torchtsetlin/models/segmentation.py
set_class_feedback_p ¶
Set (or clear) the per-class probability that a pixel contributes feedback.
Source code in src/torchtsetlin/models/segmentation.py
torchtsetlin.models.CoalescedSegmentationTsetlinMachine ¶
CoalescedSegmentationTsetlinMachine(n_outputs: int, n_clauses: int, T: float, s: float = 10.0, *, patch_size: IntOrPair = 3, stride: IntOrPair = 1, padding: Union[str, IntOrPair] = 'same', position_encoding: PositionEncoding = False, input_shape: Optional[Tuple[int, int, int]] = None, patches_per_commit: Optional[int] = 128, ignore_index: Optional[int] = None, pixel_order: str = 'raster', **kwargs)
Bases: _DenseMixin, CoalescedTsetlinMachine
Dense per-pixel Tsetlin machine with one shared clause pool and per-class weights.
The coalesced output layer (Glimsdal & Granmo, 2021) is a better fit than class-owned clauses when classes share structure — edges, textures and gradients are the same features whichever class they belong to — because one clause can serve every class it is useful for instead of being relearned per class.
With multi_label=True the targets are a Boolean stack of masks (B, K, H, W) and
a pixel may belong to several classes at once (overlapping structures); ignore_index
does not apply in that mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_outputs
|
int
|
number of classes (or of overlapping masks in multi-label mode). |
required |
n_clauses
|
int
|
total number of shared clauses. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
**kwargs
|
Any
|
the dense arguments of
:class: |
{}
|
Source code in src/torchtsetlin/models/segmentation.py
predict ¶
Label map (B, Py, Px), or a Boolean mask stack (B, K, Py, Px) in
multi-label mode.
Source code in src/torchtsetlin/models/segmentation.py
torchtsetlin.models.GraphTsetlinMachine ¶
GraphTsetlinMachine(n_features: Optional[int], n_outputs: int, n_clauses: int, T: float, s: float = 10.0, *, depth: int = 1, message_size: int = 256, message_bits: int = 2, message_encoding: str = 'random', n_edge_types: int = 1, n_node_types: int = 1, shared_node_draw: bool = False, edge_type_names: Optional[Sequence[str]] = None, **kwargs)
Bases: _GraphMixin, CoalescedTsetlinMachine
Graph Tsetlin machine (Granmo et al., 2025): deep clauses over graph-structured input.
Every clause has depth components. Component 0 matches a node's own Boolean features;
component i >= 1 matches the node's inbox of layer i, which holds a message
(clause k, edge type t) for every in-neighbour, reached over an edge of type t, at
which clause k's components 0 .. i-1 all match. A clause is True for a graph when
its components 0 .. depth-1 all match at one node. Votes, clause sharing and the
feedback probabilities are those of :class:CoalescedTsetlinMachine; each feedback event
updates every layer of the clause from one random node where the whole clause matches.
Input: a :class:~torchtsetlin.data.GraphBatch. With depth=1 and the graphs of
:meth:GraphBatch.from_images, this is exactly
:class:~torchtsetlin.models.ConvCoalescedTsetlinMachine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
Optional[int]
|
Boolean features per node |
required |
n_outputs
|
int
|
number of classes (multi-class) or labels ( |
required |
n_clauses
|
int
|
number of shared clauses. |
required |
T
|
float
|
vote margin. |
required |
s
|
float
|
specificity. |
10.0
|
depth
|
int
|
number of layers |
1
|
message_size
|
int
|
inbox size |
256
|
message_bits
|
int
|
positions per clause message (hashed |
2
|
message_encoding
|
str
|
|
'random'
|
n_edge_types
|
int
|
edge types of the dataset (a message is bound to its edge type by a cyclic shift of its positions). |
1
|
n_node_types
|
int
|
node types; clause |
1
|
shared_node_draw
|
bool
|
draw one random matching node per (graph, clause) and use it for all classes and for Type I and II, as the reference implementation does. The default draws a node per feedback event, as the convolutional models do. |
False
|
edge_type_names
|
Optional[Sequence[str]]
|
names used when printing message literals (default |
None
|
**kwargs
|
forwarded to :class: |
{}
|
The reference implementation updates every class with probability scaled by
q / (K - 1) for the negative ones; multi_label=True with one-hot targets and
negative_scale = q / (K - 1) is that rule. It also learns one graph at a time:
feedback_mode="sequential".
Source code in src/torchtsetlin/models/graph.py
torchtsetlin.models.TsetlinMachineBase ¶
TsetlinMachineBase(n_features: Optional[int], n_clauses_total: int, *, n_states: int = 128, s: float = 10.0, boost_true_positive: bool = True, max_included_literals: Optional[int] = None, drop_clause_p: float = 0.0, drop_literal_p: float = 0.0, drop_granularity: str = 'batch', init: str = 'boundary', state_dtype: Optional[dtype] = None, compute_dtype: dtype = torch.float32, max_chunk_elements: int = 2 ** 27, feedback_mode: str = 'batch', budget_mode: str = 'soft', clamp_prediction_votes: Optional[bool] = None)
Bases: Module
Common machinery for Tsetlin machines: automata state, clause evaluation, dropout, and the batched learning loop.
The learnable state lives in the integer buffer ta_state of shape
(n_clauses_total, 2 * n_features). It moves with .to(device), is saved in
state_dict() and can be inspected directly.
Subclasses implement the output layer (how clause outputs become votes) and the
feedback policy (which clauses receive Type I / Type II feedback for a labelled
example) through :meth:_votes, :meth:_select_feedback and the weight hooks.
Convolutional variants additionally override :meth:_encode, :meth:_evaluate and
:meth:_feedback_counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
Optional[int]
|
number of Boolean input features |
required |
n_clauses_total
|
int
|
total number of clauses |
required |
n_states
|
int
|
automaton states per action |
128
|
s
|
float
|
specificity. Memorize probability |
10.0
|
boost_true_positive
|
bool
|
memorize True literals of matching clauses with probability 1
instead of |
True
|
max_included_literals
|
Optional[int]
|
optional budget on the number of included literals per clause
(clause size constraint). A matching clause above the budget receives only
forgetting (Type Ib) feedback until it shrinks back (see |
None
|
drop_clause_p
|
float
|
probability of dropping a clause during learning (a Tsetlin machine
analogue of dropout). The mask is resampled on every :meth: |
0.0
|
drop_literal_p
|
float
|
probability of freezing a literal (no feedback) per resample. |
0.0
|
drop_granularity
|
str
|
|
'batch'
|
init
|
str
|
|
'boundary'
|
clamp_prediction_votes
|
Optional[bool]
|
clamp vote sums to |
None
|
state_dtype
|
Optional[dtype]
|
integer dtype of the automata states. |
None
|
compute_dtype
|
dtype
|
floating dtype of the literals and feedback counts. On CUDA, clauses
are evaluated in |
float32
|
max_chunk_elements
|
int
|
memory budget (in tensor elements) for the largest intermediate tensor of an update; batches are processed in chunks that respect it. |
2 ** 27
|
feedback_mode
|
str
|
|
'batch'
|
budget_mode
|
str
|
how |
'soft'
|
Source code in src/torchtsetlin/models/base.py
reset_parameters ¶
Re-initialise all automata (keeps the shape).
clause_outputs ¶
Evaluate every clause on encoded literals -> (B, C) bool.
empty_value defaults to self.training (empty clauses are True while learning
and False when predicting).
Source code in src/torchtsetlin/models/base.py
evaluate_clauses ¶
Clause outputs for raw Boolean input x (prediction semantics) -> (B, C).
Source code in src/torchtsetlin/models/base.py
forward ¶
Vote sums (B, n_outputs). Uses prediction semantics for empty clauses when the
module is in eval() mode. The sums are not clamped to [-T, T] (unless the
model sets clamp_prediction_votes), as in the reference implementations.
Source code in src/torchtsetlin/models/base.py
update ¶
One learning step on a batch — the Tsetlin machine analogue of
loss.backward(); optimizer.step().
In "batch" mode every example of the batch is evaluated against the current
automata; the resulting Type I / Type II feedback events are accumulated and applied
once. With a batch size of 1 this is exactly the classical sequential algorithm;
larger batches trade a little fidelity for throughput (like mini-batch SGD). In
"sequential" mode (feedback_mode or the sequential argument) the examples
are processed one by one with the automata updated in between.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor | ndarray | list
|
Boolean input batch (any Boolean-like dtype). |
required |
y
|
Tensor | ndarray | list
|
targets (class indices, multi-label matrix or regression values, depending on the model). |
required |
sequential
|
Optional[bool]
|
override |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The vote sums computed before the update ( |
Tensor
|
metrics can be logged without a second forward pass. |
Source code in src/torchtsetlin/models/base.py
train ¶
As :meth:torch.nn.Module.train; switching to eval() also releases the count
buffers that learning keeps between updates.
Source code in src/torchtsetlin/models/base.py
include_bits ¶
The include mask bit-packed, (C, ceil(2F/32)) int32 (literal l in bit
l % 32 of word l // 32), refreshed from :attr:include when stale. The Triton
commit writes it directly.
Source code in src/torchtsetlin/models/base.py
include_bits_buffer ¶
The (C, ceil(2F/32)) int32 buffer behind :meth:include_bits, without refreshing
it (a commit kernel overwrites it whole).
Source code in src/torchtsetlin/models/base.py
resample_dropout ¶
Draw new clause / literal dropout masks (called automatically per update when
drop_granularity="batch"; call it once per epoch otherwise).
Source code in src/torchtsetlin/models/base.py
included_mask ¶
Boolean (C, 2F) mask of included literals (first F columns = positive
literals x_k, last F columns = negated literals NOT x_k).
Source code in src/torchtsetlin/models/base.py
clause_literals ¶
Indices of the included literals of one clause: {"positive": [...], "negated": [...]}.
Source code in src/torchtsetlin/models/base.py
literal_names ¶
Names of all 2F literals, e.g. ["x0", "x1", "NOT x0", "NOT x1"].
Source code in src/torchtsetlin/models/base.py
clause_expression ¶
clause_expression(clause: int, feature_names: Optional[Sequence[str]] = None, joiner: str = ' AND ') -> str
Human readable conjunction for one clause ("x1 AND NOT x3"; "TRUE" if empty).
Source code in src/torchtsetlin/models/base.py
literal_frequency ¶
state_summary ¶
Quick statistics about the automata (useful for logging).