Just Shuffle: Linear-Time Set Segmentation with Transformer Encoders

A Monte Carlo Approach to Global Context

Author

Valentin von Bornhaupt

Published

November 25, 2026

TL;DR

Classifying massive point clouds usually forces a painful tradeoff: either evaluate points locally and sacrifice global context, or preserve global context and face prohibitive O(n^2) complexity of full-set methods. I developed a method that allows using random context as an approximation of the set distribution.

  • Divide and conquer: Randomly split your unordered point cloud into small stochastic bags of size c (e.g., c = 256); no need for pre-sorting, spatial indexing, or clustering.
  • Capture global context: Each bag acts as a Monte Carlo approximation of the underlying point distribution, providing the model with enough contextual clues to segment each bag simultaneously.
  • Linear complexity: Runtime drops to O(n \cdot c) and memory footprint to O(c^2) for any fixed bag size c and sample set size n.
  • Empirically resilient: Stable across different bag sizes c and spatial gaps in evaluation sets.
  • Peer-reviewed & verified: Powers whole-brain streamline segmentation in RapidParc (published in Imaging Neuroscience), outperforming existing baselines on speed and accuracy while staying robust across severe anatomical alterations.

Introduction

During my master’s thesis, I needed a way to classify massive point clouds based on their global behavior without hitting the memory limits of traditional full-set methods. The solution is a linear-time, Transformer-based Monte Carlo approach that scales exceptionally well.

This blog post should help you understand the method and its attributes to add it to your own ML-toolbox.

Motivation – Static Scene: MLP is Sufficient

Take a look at the famous two spirals classification problem. You can see samples of two spirals which are twisted into each other – a blue and an orange one. This is a classic benchmark for ML-models: These two spirals are not separable by a single straight line (i.e. not “linearly separable”).

Code
import torch
import torch.nn as nn
import math
from typing import Tuple, List, Union
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.lines import Line2D
from pathlib import Path
import time
import os
import sys

sys.path.append(Path("").resolve().parent)
from two_spirals.benchmark import measure_duration
from two_spirals.helper import get_device, to_rad, to_deg
from two_spirals.visualizations import create_sample_plot


def get_spiral_samples(size: int, 
                noise: float,
                num_twists: float = 2.0, 
                shuffle: bool = True, 
                phase_shift_rad: float = 0.0,
                is_reversed: Union[float, bool] = False,
                device: Union[torch.device, str] = torch.device("cpu")
                ) -> Tuple[torch.Tensor, torch.Tensor]:
    # Spiral 0
    half_size = size // 2 # 50:50 both spirals
    t0 = torch.rand(half_size, device=device) # randoms in [0, …, 1], shape [half_size]
    radius =  t0 # randoms in [0, …, 1], shape [half_size]
    t = ((-1)**is_reversed * 2 * math.pi * num_twists) * t0 + phase_shift_rad # Circle parametrization, shape [half_size]
    spiral0X = torch.stack([
        radius * torch.cos(t) + torch.randn(half_size, device=device) * torch.sqrt(radius) * noise / num_twists,
        radius * torch.sin(t) + torch.randn(half_size, device=device) * torch.sqrt(radius) * noise / num_twists
        ], dim=1) # [half_size, 2]

    # Spiral 1
    half_size = size - half_size # = half_size if size is even else half_size+1 
    t0 = torch.rand(half_size, device=device) # randoms in [0, …, 1], shape [half_size]
    radius =  t0 # randoms in [0, …, 1], shape [half_size]
    t = ((-1)**is_reversed * 2 * math.pi * num_twists) * t0 + (phase_shift_rad + math.pi) # Circle parametrization, shape [half_size]
    spiral1X = torch.stack([
        radius * torch.cos(t) + torch.randn(half_size, device=device) * torch.sqrt(radius) * noise / num_twists, 
        radius * torch.sin(t) + torch.randn(half_size, device=device) * torch.sqrt(radius) * noise / num_twists
        ], dim=1) # [half_size, 2]

    spiral_samples = torch.vstack([spiral0X, spiral1X]) # [size, 2]
    spiral_labels = torch.tensor([0] * len(spiral0X) + [1] * len(spiral1X), device=device) # [size]

    if shuffle:
        perm = torch.randperm(size, device=device) # [size]
        return spiral_samples[perm], spiral_labels[perm] # [size, 2], [size]
    else:
        return spiral_samples, spiral_labels # [size, 2], [size]

                           
################ Code: ################
save_dir = Path("two_spirals") / "weights_and_statistics"
if not save_dir.is_dir():
    save_dir.mkdir()

NUM_TWISTS = 1.75
SAMPLE_NOISE = 0.15
DEVICE = get_device()
cmap_blue_orange = LinearSegmentedColormap.from_list("blue_orange", ["tab:blue", "tab:orange"])
create_sample_plot(num_samples=5000, num_twists=NUM_TWISTS, phase_shift_rad=0, noise=SAMPLE_NOISE)
Figure 1: Samples of a static Two-Spirals instance

A more sophisticated model – like a simple Multi-Layer-Perceptron (MLP) – can easily learn this static two-spirals scene (Figure 2). My MLP here has a \, 2-32-32-2 architecture (i.e. 1218 parameters) with LeakyReLU activations.

Code
from sklearn.metrics import f1_score, accuracy_score
import numpy as np
import pickle
from two_spirals.visualizations import plot_decision_boundary_for_mlp


class MLP(nn.Module): 
    def __init__(self, layers: List[int], dropout_prob: float = 0.1): 
        super(MLP, self).__init__()
        self.layers = nn.ModuleList([
            nn.Linear(in_feat, out_feat) for in_feat, out_feat in zip(layers[:-1], layers[1:])
            ])
        self.activation = nn.LeakyReLU()
        self.dropout = nn.Dropout(dropout_prob)
        # print(self)
        # print(f"Number trainable parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad)} \n")

    def forward(self, x: torch.Tensor) -> torch.Tensor: 
        for layer in self.layers[:-1]:
            x = self.activation(layer(x))
            x = self.dropout(x)
        return self.layers[-1](x)


def train_mlp(model: nn.Module, 
          num_epochs: int, 
          batch_size: int,
          num_twists: float, 
          device: Union[torch.device, str], 
          sample_noise: float, 
          lr: float = 0.001):
    model.train()
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)

    for epoch in range(num_epochs):
        x, y_true = get_spiral_samples(size=batch_size, num_twists=num_twists, device=device, noise=sample_noise)
        optimizer.zero_grad()      
        y_pred = model(x)
        loss = criterion(input=y_pred, target=y_true)
        loss.backward()
        optimizer.step()

        # if epoch % (num_epochs // 10) == 0 or epoch == num_epochs-1:
        if epoch == num_epochs - 1:
            with torch.inference_mode():
                x, y_true = get_spiral_samples(size= 2**12, num_twists=num_twists, device=device, noise=sample_noise)
                model.eval()
                y_pred = torch.argmax(model(x), dim=-1).cpu() # shape [2**12], values in {0,1}
                model.train()
                y_true = y_true.cpu()
                f1 = f1_score(y_true = y_true, y_pred = y_pred, zero_division = 0)
                acc = accuracy_score(y_true = y_true, y_pred = y_pred)
                # print(f"Epoch {epoch + 1}/{num_epochs}, Train Loss: {loss.cpu().item():.4f}, Test F1: {100*f1:.2f} %, Test Acc: {100*acc:.2f} %")

    return model, f1, acc



try: # …to open pretrained model
    with open(save_dir/"mlp_specs.pickle", 'rb') as handle:
        mlp_specs = pickle.load(handle)
    mlp = MLP(layers=mlp_specs["layers"])
    mlp.load_state_dict(torch.load(save_dir/"mlp.pth", weights_only=True, map_location="cpu"))
    mlp = mlp.to(DEVICE)

except (FileNotFoundError, RuntimeError) as e:
    # Else: Train new MLP Model:
    mlp_specs = dict()
    mlp_specs["layers"] = [2, 32, 32, 2]
    mlp_specs["num_epochs"] = 30000
    mlp = MLP(layers=mlp_specs["layers"])
    mlp = mlp.to(DEVICE)
    with measure_duration(DEVICE) as t:
        mlp, f1, acc = train_mlp(
            model=mlp,
            num_epochs=mlp_specs["num_epochs"], 
            batch_size=2**11, 
            num_twists=NUM_TWISTS, 
            sample_noise=SAMPLE_NOISE, 
            device=DEVICE)
    torch.save(obj=mlp.state_dict(), f=save_dir/"mlp.pth")
    mlp_specs["duration"] = t.duration
    mlp_specs["f1"] = f1
    mlp_specs["acc"] = acc
    with open(save_dir/"mlp_specs.pickle", "wb") as handle:
        pickle.dump(mlp_specs, handle)

print(f'{mlp_specs["num_epochs"]} epochs, Test F1: {100 * mlp_specs["f1"]:.2f} %, Test Acc: {100 * mlp_specs["acc"]:.2f} %')
print(f'Training took {mlp_specs["duration"]:.2f}s on M2 MacBook Air')
plot_decision_boundary_for_mlp(
    model=mlp, 
    sample_noise=SAMPLE_NOISE, 
    num_points=2**20, 
    num_twists=NUM_TWISTS, 
    device=DEVICE)
30000 epochs, Test F1: 97.22 %, Test Acc: 97.22 %
Training took 60.71s on M2 MacBook Air
Figure 2: Result of a trained MLP on samples of a static two-spirals instance with 1.75 twists. The network learned the underlying class distribution quite well (plotted as a contour in the background).
Evaluating 1,048,576 samples took 0.037s.

Dynamic Scene: MLP is not Sufficient Anymore

So far, so easy. But you could also define other variants of these two-spirals by changing the number of twists, rotating the spirals by a few degrees or reversing the spirals’ direction of rotation (Figure 3).

Code
from two_spirals.visualizations import plot_9_spirals
    
################ Code: ################
plot_9_spirals(
    twists = 0.5 + 3 * torch.rand(9), 
    phase_shifts_rad = to_rad(-45 + 90 * torch.rand(9)),
    reverseds = torch.bernoulli(torch.rand(9)),
    sample_noise = SAMPLE_NOISE
)
Figure 3: Samples of nine random two-spirals instances.

Imagine now you want to write a single model to classify every configuration of twists, rotation and is_reversed.

In the simple scenario (with only a single (static) two-spirals configuration) the trained model is able to predict the class labels based on 2D coordinates. It learned that certain 2D-coordinates correspond to certain class-probabilities. Or, to be more precise, it is the approximation of the class distributions (as seen in the background coloring of Figure 2).

The more general case is way more complex:

Imagine a third person selects a two-spirals configuration, draws samples, hands you just the samples without their respective colors nor configuration, and you have to reassign the labels again.

Just the position of a sample (2D coordinate) is not sufficient for reassigning the label anymore, since you don’t know the underlying two-spirals configuration. A single 2D coordinate could be part of the orange or the blue spiral, depending on the underlying two-spirals configuration (Compare Figure 8 with c=1).

We actually want to classify (blue/ orange) samples based on their underlying distribution (the parametrized two-spirals and noise). But the parameters of the distribution are unknown and vary. This creates a loop:

  • If we knew the parameters of the underlying distribution during inference time, we could easily predict the colors. (Train a model with twists, is_reversed and rotation as additional inputs)

  • But for estimating these parameters using traditional regression methods, we need labeled / colored samples.

We have neither of them. During inference time, we only have a bunch of unlabeled / uncolored samples of an unknown configuration. In the following, we handle both problems in parallel.

Method: Transformer Encoder + Monte Carlo

Figure 4: Method’s three main steps: (a) dataset is split into bags. Each contains c=bag_size samples (b) all bags are classified simultaneously (c) the output is combined

We need parallel sample prediction and estimating of the underlying distribution.

How? As mentioned above, it is impossible to infer the label based on just a single 2D coordinate. But what if you were looking at a few hundred or thousand simultaneously? Instead of handling single samples, you could bag multiple samples together. These bags clearly contain valuable information about the two-spirals configurations. Let’s say you partition the samples into bags of size c. The most efficient way would clearly be a network architecture, which takes this bag of c samples and directly predicts c labels for them – in parallel.

So, we want a c \to c network for this approach. Meaning: c 2D coordinates have to be mapped to their respective c labels.

We could design an MLP which tries to solve this problem. MLPs are universal function approximators. They could do it. If we designed an MLP for this task, the inputs would be 2c dimensional vectors (c points per bag, each 2D) and the outputs would be 2c dimensional vectors (c points per bag in class logits style).

  • First of all, having an MLP connecting 2c input nodes with 2c output nodes would require at least 4c^2 weights. This would limit c to be very small and could be a harsh contrast to c being sufficiently big to describe the two-spirals parameters sufficiently (e.g., for c=256, an MLP would have 4c^2 = 2^{18} vs. 1858 parameters of the transformer in Figure 5).

  • Secondly, while the order of entries within a vector (MLPs) is relevant, the order of 2D points within a bag is arbitrary. So the network would have to learn that the order of the c-2D coordinates is not relevant. We could teach the network this using augmentations. We could shuffle the input and the output vector in the same way using multiple, random permutations during training (data augmentation). There are c! permutations of c elements. We cannot show the model every permutation during training (since c! is huge; e.g. 10! > 10^6, 100! > 10^{157}, 1000! > 10^{2567}). And after training, you would not have a guarantee that changing the order of bag-elements does not affect the label assignments. The underlying problem is: MLPs are not permutation equivariant.

Permutation Equivari-WHAT?

We call a function f: \mathbb{R}^{n \times m} \to \mathbb{R}^{n \times m} permutation equivariant, if for any permutation matrix P \in \mathbb{R}^{n \times n} and any input matrix X \in \mathbb{R}^{n \times m} , we have f\left(P\cdot X\right) = P\cdot f(X)\;.

TipIntuition Behind Permutation Equivariance

Shuffling the inputs does automatically shuffle the outputs in the same way. The function’s output is the same – but it changed its order as the input did. For getting this behavior, no data augmentation during training or further tricks are needed – this behavior is just a property of f.

Examples of Permutation Equivariant Functions

  • A function that is applied to every element in the bag independently is always permutation equivariant.
    • Applying an MLP to a batch of samples is permutation equivariant in the batch dimension.
    • Layer Normalization is applied to each sample independently and therefore permutation equivariant.
  • Multi-head self-attention layers are permutation equivariant (if no positional encodings are used). This is a well known fact and easy to prove.

So if we use the attention mechanism, we get this property for free and we overcome the n! permutation complexity we had with MLPs.

Attention layers are like magic: Every input token can influence every output token, the number of weights does not depend on the number of tokens n, and attention layers are permutation equivariant.

Applying the Method

Model Architecture

This small 1,858-parameter model is a standard Transformer Encoder acting as a sequence-to-sequence map. It maps \mathbb{R}^{c \times d_{\text{in}}} to class logits \mathbb{R}^{c \times d_\text{out}}.

  • Transformer Encoder: Three standard multi-head self-attention layers (d_model = 8, nhead = 2, dim_feedforward = 16)
  • Input and Output Layers: Linear mappings (d_{\text{in}} \to d_\text{model} and d_\text{model} \to d_{\text{out}})
  • No positional encodings: Since they break permutation equivariance.

Training

  • Heavy Data Augmentations: For each bag, generate c samples. Select for every bag a new random configuration:
    • num_twists\sim \textit{Unif}([0.5,\, 3.5])
    • rotation\sim \textit{Unif}([-45^{\circ}, \, 45^{\circ}])
    • is_reversed \sim \textit{Ber}(0.5)
  • Batching: Combine B independent bags into a tensor of shape [B, c, d_{\text{in}}].
  • Loss: Point-wise cross-entropy applied to whole batch

Inference Pipeline (for Arbitrary Set Size n)

[Unordered Set: n points]
       │
       ▼  Step 1: Random Shuffle (π)
[Permuted Set]
       │
       ▼  Step 2: Partition into bags of size c (pad residual bag)
[Bags: ⌈n/c⌉ × c × d_in]
       │
       ▼  Step 3: Batched Forward Pass (Transformer Encoder)
[Bag Logits: ⌈n/c⌉ × c × d_out]
       │
       ▼  Step 4: Unpad, Argmax, and Invert Permutation (π⁻¹)
[Final Predictions: n labels]
  1. Global Permutation: Shuffle the n input points using a random permutation \pi. This breaks any spatial or sequential sorting artifacts present in the raw data.
  2. Bag Partitioning: Reshape the array into bags of size c. If n is not divisible by c, pad the residual bag by recycling points from another bag. This guarantees the last bag to have the same context quality as all other bags.
  3. Batched Forward Pass: Pass the bags through the encoder in mini-batches.
  4. Reassembly: Flatten the predicted labels, discard the padded samples (from step 2), and apply the inverse permutation \pi^{-1} to restore the original input order.
Code
from two_spirals.visualizations import plot_loss_curve
import pandas as pd
from sklearn.metrics import f1_score, accuracy_score

RANGE_NUM_TWISTS = [0.5, 3.5]
RANGE_ROTATIONS = [-math.pi/4, math.pi/4] # ± 45°
SAMPLE_NOISE = 0.12


# Model
class TransformerEncoder(nn.Module):
    def __init__(
        self,
        input_dim: int,
        output_dim: int,
        d_model: int,
        nhead: int,
        num_layers: int,
        dim_feedforward: int,
        dropout: float,
    ):
        super().__init__()
        assert d_model % nhead == 0, f"nhead = {nhead} has to be a divisor of d_model = {d_model} but is not."
        self.input_layer = nn.Linear(input_dim, d_model)
        layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=dim_feedforward,
            dropout=dropout,
            activation="relu",
            batch_first=True
            # norm_first=True,
        )
        self.encoder = nn.TransformerEncoder(
            encoder_layer = layer,
            num_layers = num_layers,
            norm = nn.LayerNorm(d_model),
            enable_nested_tensor=False,
        )
        self.output_layer = nn.Linear(d_model, output_dim)
        self._reset_parameters()
        # print(self)
        # print(f"Number of trainable parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad)} \n")

    def _reset_parameters(self):
        # Recommended by warning on https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.transformer.TransformerEncoder.html
        for module in self.modules():
            if isinstance(module, nn.Linear):
                nn.init.xavier_uniform_(module.weight)
                if module.bias is not None:
                    nn.init.zeros_(module.bias)

            elif isinstance(module, nn.LayerNorm):
                nn.init.ones_(module.weight)
                nn.init.zeros_(module.bias)

    def forward(self, x):
        x = self.input_layer(x)
        x = self.encoder(x)
        return self.output_layer(x)



def train_transformer():
    model_specs = {
        "input_dim": 2,
        "output_dim": 2,
        "d_model": 8,
        "nhead": 2,
        "num_layers": 3,
        "dim_feedforward": 16,
        "dropout": 0.1,
        "RANGE_NUM_TWISTS": RANGE_NUM_TWISTS,
        "RANGE_ROTATIONS": RANGE_ROTATIONS,
        "SAMPLE_NOISE": SAMPLE_NOISE,
        "num_epochs": 150000,
        "batch_size": 2**4,
        "training_bag_size": 2**8      
    }
    # Enclosure for batch wise sampling
    sample_generator = lambda num_twists, phase, is_reversed: get_spiral_samples(
        size=model_specs["training_bag_size"], 
        num_twists=num_twists, 
        device=DEVICE, 
        noise=model_specs["SAMPLE_NOISE"], 
        phase_shift_rad=phase,
        is_reversed=is_reversed)
    batched_sample_generator = torch.func.vmap(sample_generator, randomness="different")

    model = TransformerEncoder(
        input_dim=model_specs["input_dim"],
        output_dim=model_specs["output_dim"],
        d_model=model_specs["d_model"],
        nhead=model_specs["nhead"],
        num_layers=model_specs["num_layers"],
        dim_feedforward=model_specs["dim_feedforward"],
        dropout=model_specs["dropout"])
    model.train()
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    model = model.to(DEVICE)

    ######### Do training #########
    epoch = 0
    loss_curve = []
    with measure_duration(DEVICE) as t:
        for epoch in range(model_specs["num_epochs"]):
            x, y_true = batched_sample_generator(
                RANGE_NUM_TWISTS[0] + (RANGE_NUM_TWISTS[1] - RANGE_NUM_TWISTS[0]) * torch.rand  (model_specs["batch_size"], device=DEVICE), 
                RANGE_ROTATIONS[0] + (RANGE_ROTATIONS[1] - RANGE_ROTATIONS[0]) * torch.rand (model_specs["batch_size"], device=DEVICE),
                torch.bernoulli(torch.rand(model_specs["batch_size"], device=DEVICE)))
            optimizer.zero_grad()
            y_pred = model(x)
            loss = criterion(input=y_pred.reshape(-1, 2), target=y_true.flatten())
            loss.backward()
            optimizer.step()
            loss_curve.append(loss.item())
    model_specs["loss_curve"] = loss_curve
    model_specs["duration"] = t.duration
    return model_specs, model



@torch.inference_mode()
def eval_transformer(
        model: nn.Module, 
        x: torch.Tensor, 
        eval_bag_size: int, 
        eval_batch_size: int = 2**20, # if not defined: take all
        return_duration: bool = False
    ):
    """
        Eval Function for the Transformer Encoder. Important are the sample shuffling and the filling up of the last bag (if necessary).
    """
    assert next(model.parameters()).device == x.device, \
        f"The model's device {next(model.parameters()).device} and the data's {x.device} differ."
    device = x.device
    assert len(x.shape) == 2 and x.shape[1] == 2, \
        f"Assumed x to have shape [num_samples, 2], but got {x.shape}"

    model.eval()
    with measure_duration(device) as t:
        perm = torch.randperm(x.shape[0], device=device) 
        inv_perm = torch.empty_like(perm)
        inv_perm[perm] = torch.arange(len(perm), device=device)
        x_perm = x[perm] 
        original_num_samples = len(x)
        if len(x_perm) < eval_bag_size:
            x_bags = x_perm.unsqueeze(0) # Shape [1, num_samples, 2]
            print(f"Warning: You wanted to evaluate the model with eval_bag_size: {eval_bag_size} " +\
                  f"but just handed in {len(x_perm)} samples. The prediction now uses " +\
                  f"only eval_bag_size {len(x_perm)} instead.")
        else:
            # => There is at least one full bag. 
            if original_num_samples % eval_bag_size == 0:
                x_bags = x_perm.reshape(-1, eval_bag_size, 2)
            else:
                # What if the last bag is too small? 
                # -> Fill up last bag with samples of first bag:
                residual = eval_bag_size - original_num_samples % eval_bag_size
                x_bags = torch.vstack([x_perm, x_perm[:residual]])
                x_bags = x_bags.reshape(-1, eval_bag_size, 2)

        # Eval model
        y_pred = []
        for i in range(math.ceil(len(x_bags) / eval_batch_size)):
            logits = model(x_bags[i * eval_batch_size : (i+1) * eval_batch_size])
            y_pred.append(
                torch.argmax(logits, dim=-1).flatten()
            )

        y_pred = torch.hstack(y_pred)
        # Discard the added samples
        y_pred = y_pred[:original_num_samples] 
        # Do unshuffling:
        y_pred = y_pred[inv_perm]
    return (y_pred, t.duration) if return_duration else y_pred



############# Code: #############
try: #... to load trained model and specs
    with open(save_dir/"transformer_model_specs.pickle", 'rb') as handle:
        model_specs = pickle.load(handle)
    model = TransformerEncoder(
        input_dim=model_specs["input_dim"],
        output_dim=model_specs["output_dim"],
        d_model=model_specs["d_model"],
        nhead=model_specs["nhead"],
        num_layers=model_specs["num_layers"],
        dim_feedforward=model_specs["dim_feedforward"],
        dropout=model_specs["dropout"])
    model.load_state_dict(torch.load(save_dir/"transformer_model.pth", weights_only=True, map_location="cpu"))
    model = model.to(DEVICE)

except (FileNotFoundError, RuntimeError) as e:
    model_specs, model = train_transformer()
    torch.save(obj=model.state_dict(), f=save_dir/"transformer_model.pth")
    with open(save_dir/"transformer_model_specs.pickle", "wb") as handle:
        pickle.dump(model_specs, handle)

print(f"Training {model_specs['num_epochs']} epochs with bag size {model_specs['training_bag_size']} took {model_specs['duration']:.2f}s on M2 MacBook Air")
plot_loss_curve(model_specs["loss_curve"])
Training 150000 epochs with bag size 256 took 2268.83s on M2 MacBook Air
Figure 5: The loss curve on the Transformer Encoder: Stable convergence

Visual Results

Now that our model is trained, we can inspect some visual results.

Try the Transformer Encoder Model in your Browser

Click on the widget below or open it in a new tab. Play with the parameters. Your CPU will calculate each forward pass in real-time.

Click here to test the algorithm
Interactive real-time widget

Precomputed Visual Results

If your browser blocks JavaScript, the live widget above might not work. For that case, I generated some static precomputed examples: I combined three number of twists [1, 2, 3] with three rotations [-30°, 0°, 30°] to create 9 two-spirals instances. Below, you can see the model’s respective predictions:

Code
from two_spirals.visualizations import plot_visual_results

plot_visual_results(
    model = model, 
    eval_bag_size = 2**10,
    num_twists_arr = [1, 2, 3], 
    rotations = to_rad(np.array([-(30 + 10e-4), 0, (30 + 10e-4)])), 
    is_reversed = False,
    device = DEVICE,
    sample_noise = SAMPLE_NOISE,
    evaluate_model_function = eval_transformer)
Figure 6: Visual results for the trained Monte Carlo Attention model for various number of twists and rotations. The dot color corresponds to the model prediction. If the border color is red, the model prediction is wrong.
Evaluating 9 x 8,192 samples, each with evaluation bag size 1024 
and batch size 8 took 0.41s in total on M2.

We get similarly good results if we reverse the spirals (i.e. changed twist direction):

Code
plot_visual_results(
    model = model, 
    eval_bag_size = 2**10,
    num_twists_arr = [1, 2, 3], 
    rotations = to_rad(np.array([-(30 + 10e-4), 0, (30 + 10e-4)])), 
    is_reversed = True,
    device = DEVICE,
    sample_noise = SAMPLE_NOISE,
    evaluate_model_function = eval_transformer)
Figure 7: Visual results for the trained Monte Carlo Attention model for various number of twists and rotations. But this time the spirals are reverse twisted. The dot color corresponds to the model prediction. If the border color is red, the model prediction is wrong.
Evaluating 9 x 8,192 samples, each with evaluation bag size 1024 
and batch size 8 took 0.33s in total on M2.

Analysis of the Monte Carlo Behavior

Robustness to Bag Size Selection

As you might know, one big advantage of the Transformer architecture is that it is independent of the number of input samples. Thus, when we train a Transformer using a certain bag size we can evaluate it later using any other bag size. Maybe you noticed that I trained the Transformer Encoder in Section 2.2 with training_bag_size = 256 while I evaluated it in Figure 6 and Figure 7 with eval_bag_size = 1024. The classification result does of course depend somehow on the bag size c. If c is large, the model should get more valuable context and thus, be more accurate. But can we quantify this influence?

Let’s take our trained model from Section 2.2 and do the following: We take 2^{20} ≈ 1 million samples from 32 random configurations and classify them using bag sizes c = 1, 2, 4, 8, … , 4096 (each 20 times).

Code
import math
from collections import defaultdict
import numpy as np
import seaborn as sns
from two_spirals.visualizations import create_robustness_boxplots


@torch.inference_mode()
def compute_monte_carlo_statistics(
    num_samples: int = 2**20, # Approx. 1 million samples each
    num_runs: int = 20, # For testing random bagging
    num_configurations: int = 32, # Random Spirals each
    bag_sizes: List[int] = [2**i for i in range(13)]
    ):

    f1_scores = defaultdict(list)
    label_toggle_statistics = defaultdict(defaultdict(int).copy) # see next sub-section
    timings = defaultdict(int)

    for _ in range(num_configurations):
        # Randomly choose new configuration and sample
        num_twists = RANGE_NUM_TWISTS[0] + (RANGE_NUM_TWISTS[1] - RANGE_NUM_TWISTS[0]) * torch.rand(1, device=DEVICE)
        phase_shift_rad = RANGE_ROTATIONS[0] + (RANGE_ROTATIONS[1] - RANGE_ROTATIONS[0]) * torch.rand(1, device=DEVICE)
        is_reversed = torch.bernoulli(torch.rand(1, device=DEVICE))
        x, y_true = get_spiral_samples(size=num_samples, 
                            num_twists=num_twists, 
                            phase_shift_rad=phase_shift_rad,
                            is_reversed=is_reversed,
                            device=DEVICE, 
                            noise=SAMPLE_NOISE,
                            shuffle=False) # Happens in the eval function every call
        y_true = y_true.cpu().numpy()
        for c in bag_sizes:
            y_preds = []
            for _ in range(num_runs):
                y_pred, duration = eval_transformer(
                    model=model, 
                    x=x, 
                    eval_bag_size=c, 
                    eval_batch_size = max((max(bag_sizes) ** 2) // (c ** 2), 1), # I want to use ≤ 4 GB Unified Mem for this process
                    return_duration=True
                )
                timings[c] += duration
                assert len(y_pred) == len(x), \
                    f"Shape y_pred: {y_pred.shape}, but there are {len(x)} samples"
                y_pred = y_pred.cpu().numpy()
                y_preds.append(y_pred)
                f1_scores[c].append(f1_score(y_true=y_true, y_pred=y_pred))

            # Calculate: How often did the label assignment of samples change during num_runs baggings of the same samples?
            y_preds = np.array(y_preds)
            assert (y_preds.shape == np.array([num_runs, num_samples])).all(), \
                f"y_preds: {y_preds.shape}, but num_runs: {num_runs}, num_samples: {num_samples}"

            toggles = np.sum(y_preds != y_true[None, :], axis=0) # [num_runs, num_samples]
            toggles = np.fmin(toggles, num_runs - toggles) # [num_samples]
            assert (toggles.shape == np.array(num_samples)).all(), \
                f"toggles: {toggles.shape}, but num_samples: {num_samples}"

            values, counts = np.unique(toggles, return_counts=True)
            for value, count in zip(values, counts):
                label_toggle_statistics[c][int(value)] += int(count)
    return f1_scores, timings, label_toggle_statistics


try:
    with open(save_dir/"f1_scores.pickle", 'rb') as handle:
        f1_scores = pickle.load(handle)
    with open(save_dir/"timings.pickle", 'rb') as handle:
        timings = pickle.load(handle)
    with open(save_dir/"label_toggle_statistics.pickle", 'rb') as handle:
        label_toggle_statistics = pickle.load(handle)

except FileNotFoundError as e:
    f1_scores, timings, label_toggle_statistics = compute_monte_carlo_statistics()
    with open(save_dir/"f1_scores.pickle", "wb") as handle:
        pickle.dump(f1_scores, handle)
    with open(save_dir/"timings.pickle", "wb") as handle:
        pickle.dump(timings, handle)
    with open(save_dir/"label_toggle_statistics.pickle", "wb") as handle:
        pickle.dump(label_toggle_statistics, handle)


create_robustness_boxplots(f1_scores)
Figure 8: The classification f1 score depends on the bag size c. If the bag size increases we see better results. Note that the x-axis uses a logarithmic scale: c can be chosen to be relatively small (256 or greater) to get results comparable to the MLP from Figure 2.

As you can see, we get very good results if the bag size c is selected big enough for our needs. Note furthermore that the variance of the f1-scores does also decrease for increasing c.

The curve behaves somehow as expected for a Monte Carlo method. Single samples behave randomly (f1 score \approx 50 \% corresponds to coin flipping in this class-balanced setup). Larger bags provide a more representative empirical approximation of the underlying distribution (see law of large numbers). Empirically, the performance stabilizes as c increases.

But with larger bag size c, the runtime also increases:

Code
from two_spirals.visualizations import create_timing_barplot
create_timing_barplot(total_num_runs=len(f1_scores[1]), timings=timings)
Figure 9: Duration for predicting 2^{20} ≈ 1 million samples depending on the bag size during evaluation. The values are averages of 20 x 32 runs. Note that the x-axis uses a logarithmic scale: The duration increases linearly in c. All measurements are made on an M2 MacBook Air.

The runtime increases in c in a linear way: It roughly doubles if c doubles (see Section 4). As with many other Monte Carlo methods, it is up to you to balance accuracy with resource usage.

Robustness to Random Partitioning

Furthermore, if we randomly partition the dataset into bags and classify each bag independently, the classification result of a specific sample might change, depending on whether it is randomly bagged into one or another bag (one bag may provide more informative context than others). This is why I ran the experiment above 20 times: each time with a new random partition. I calculated how often the model changed its classification decision during the 20 runs for each of the 32 \times 2^{20} \approx 33.5 million samples:

Code
from two_spirals.visualizations import create_consistency_plot
create_consistency_plot(label_toggle_statistics)
Figure 10: What is the influence of random bagging? During 20 independent random partitions on the same 32 x 2^{20} samples set: How consistently did the model predict each sample? I call the model 100 % consistent on a certain sample if it predicts in all 20 times the same label. If it predicts on a certain sample 10 times orange and 10 times blue depending on the other samples in its bag I call it 0 % consistent. Note that the x-axis uses a logarithmic scale. The model is very consistent for surprisingly small bag sizes.

Some notes on the graphic:

  • Edge case c=1: Every bag has only one sample inside. Therefore, there is no random context inside a bag and thus, the model is 100 % consistent in its answers. Note that this does not mean the model predicts correctly (compare Figure 8) – it’s just consistent.
  • The model rapidly gains consistency as c increases. The law of large numbers is on our side again. Sure, this result is compatible with Figure 8 above.

Consistency Benchmarking as Trustworthiness Measure

Applying random partitioning and evaluating the model multiple times does not involve any target values. Meaning: This test is always possible during inference time. - This test can be used to check if a bag size c is chosen large enough. If the model swaps too often, try to choose a larger bag size c. - When you want to apply the trained model to a similar, unseen data set, this test can signal how well the model describes the data. Low consistency could be an indicator for out-of-distribution behavior.

Robustness to Spatially Missing Regions

Let’s draw spirals and punch some holes into the datasets to account for missing regions (without training on this new problem). How stable is the model w.r.t. this perturbation?

Code
@torch.inference_mode()
def plot_missing_region_results(
        model: nn.Module, 
        num_twists_array: List[float], 
        holes: List[float], 
        eval_bag_size: int,
        num_samples: int = 2**13,
        is_reversed: bool = False):

    num_effective_samples = 0
    duration = 0.0

    model.eval()
    model = model.to(DEVICE)
    fig, axes = plt.subplots(len(holes), len(num_twists_array), figsize=(12, 4.34*len(holes))) 
    for i, (hole_x, hole_y, hole_radius) in enumerate(holes):
        for j, num_twists in enumerate(num_twists_array):
            # is_reversed = (i + j) % 2 == 0
            ax = axes[i, j]
            x, y_true = get_spiral_samples(size=num_samples, 
                                      noise=SAMPLE_NOISE, 
                                      device=DEVICE,
                                      num_twists=num_twists, 
                                      phase_shift_rad=0.0,
                                      is_reversed=is_reversed,
                                      shuffle=False)

            ############# Perturb: Delete circle and eval model #############
            outside_hole_mask = (x[:, 0] - hole_x) ** 2  + (x[:, 1] - hole_y) ** 2 > hole_radius ** 2
            x, y_true = x[outside_hole_mask], y_true[outside_hole_mask]
            num_effective_samples += len(x)
            y_pred, duration_run = eval_transformer(
                model = model, 
                x = x, 
                eval_bag_size = eval_bag_size, 
                eval_batch_size = 2**20, # just do all in one pass
                return_duration = True)
            y_pred = y_pred.cpu()
            y_true = y_true.cpu()
            duration += duration_run

            ############# Create Plot #############
            incorrect = (y_pred != y_true)
            edge_colors = ["red" if wrong else "black" for wrong in incorrect]
            line_widths = [0.8 if wrong else 0.02 for wrong in incorrect]

            ax.scatter(
                x[:, 0].cpu(), 
                x[:, 1].cpu(), 
                c=y_pred, 
                cmap=cmap_blue_orange, 
                s=10, 
                edgecolors=edge_colors, 
                linewidths=line_widths,
                alpha=0.7
            )

            ax.set_aspect("equal", adjustable="box")
            ax.set_xlim([-1.2, 1.2])
            ax.set_ylim([-1.2, 1.2])
            reversal_text = ", reversed" if is_reversed else ""
            acc = accuracy_score(y_true=y_true, y_pred=y_pred)
            f1 = f1_score(y_true, y_pred)
            ax.set_title(
                f"{num_twists} twist(s) {reversal_text}\n Hole at {(hole_x, hole_y)} with radius {hole_radius}\n"\
                +f"F1: {100*f1:.2f} %, Acc: {100*acc:.2f} %"
                )
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)
    plt.show()
    print(f"Evaluating {num_effective_samples:,d} samples with evaluation bag size {eval_bag_size} took {duration:.2f}s in total on M2.")


########### Code ###########
plot_missing_region_results(
    model = model, 
    num_twists_array = [1, 2, 3], 
    holes = [(-0.5, 0.5, 0.2), (-0.5, 0.5, 0.3), (-0.5, 0.5, 0.4), (-0.5, 0.5, 0.5)], 
    eval_bag_size = 2**10
)
Figure 11: Spirals with holes: You can see 12 two-spirals instances where I deleted all samples inside a certain area (large circle). I used the trained model from above to classify the remaining samples (dot content = model prediction; red border = prediction is wrong). Even if I did not train the model again the model still performs reliably.
Evaluating 88,612 samples with evaluation bag size 1024 took 0.46s in total on M2.

Remember: The model has not seen these perturbations during training – complete out-of-distribution test set. The model still performs pretty well (\approx 90 \% accuracy and higher). This is due to the fact that the model is trained to handle only fractions (bags) of the whole set. If regions are missing in the whole sample set, the model might interpret the missing values as just not included in the observed random bag. Bags which do not contain any information of certain areas are unlikely, but possible.

I could also argue that the wrong predictions in Figure 11 are actually markers where the model would have needed samples in the missing region.

Linear Runtime and Memory Complexity

If n is the number of samples and c the bag size, the resulting runtime complexity is O\left(\frac{n}{c} \cdot c^2 \right) = O\left(n \cdot c \right) because we have \lceil\frac{n}{c} \rceil bags and calculating attention to each bag is in O(c^2). If c is a small constant, this algorithm runs in O(n).

The memory complexity is O\left(c^2 \right) if we handle the data as streams.

Comparison to other Architectures

PointTransformer v3 and LitePT are very advanced Transformer and Convolution-based methods for 3D-Point clouds. They first discretize the space and then use space-filling curves for defining local neighborhood orders. These orders result in a 1D vector. Then, a U-Net like network structure is applied on local windows of this 1D vector to generate a global-local segmentation method for the point cloud.

But: I created the MC-method because I needed to segment 45 dimensional point clouds (RapidParc). Applying the method of space filling curves to 45 dimensions is not practical:

  • Grid representation issues: Calculating space filling curves in 3D can be done efficiently using bit acrobatics. Applying this method to higher dimensions results in headaches. Using uint64 would give you only 1 bit per axis (i.e. only two values per axis \to bad resolution). If we chose 10 bits per axis (1024 positions per axis) we would need a 450-bit global index. 450 bit cannot be computed efficiently on standard hardware. Therefore, the efficiency gains of PTv3 and LitePT do not hold anymore.

  • Many dimensions = many neighbors: The idea of Morton codes is based on the idea that if two points are close to each other in a grid space, they are close to each other in the 1D order of the space-filling curve. This argument fails in 45 dimensional space. While a point in a 3D grid has 26 neighbors, it has 3^{45}-1 \approx 2.9\times 10^{21} neighbors in a 45 dimensional grid. Therefore, any possible window size would be too small to capture all neighbors. Or: A small window size could include the wrong neighbors. Furthermore, as there are so many neighbors in 45D, we cannot utilize sparse convolutions as these methods did.

  • CUDA implementation: The implementation of these methods uses CUDA kernels. I currently don’t have NVIDIA Accelerators for testing.

PointNet is a pioneering MLP-based point cloud segmentation method. It combines shared MLPs with pooling layers for global feature extraction. This global information is concatenated to every point feature vector. Another shared MLP classifies each vector separately.

Code
from two_spirals.pointnet import PointNetSeg, train_pointnet
from two_spirals.visualizations import plot_visual_results, plot_loss_curve

# --- Train or Load Pretrained Weights ---
try:
    with open(save_dir / "pointnet_model_specs.pickle", "rb") as handle:
        pn_specs = pickle.load(handle)
    pn_model = PointNetSeg(
        input_dim=pn_specs["input_dim"],
        output_dim=pn_specs["output_dim"],
        feat_dim=pn_specs["feat_dim"],
    )
    pn_model.load_state_dict(torch.load(save_dir / "pointnet_model.pth", weights_only=True, map_location="cpu"))
    pn_model = pn_model.to(DEVICE)

except (FileNotFoundError, RuntimeError):
    pn_specs, pn_model = train_pointnet(
        DEVICE=DEVICE, 
        RANGE_NUM_TWISTS=RANGE_NUM_TWISTS, 
        RANGE_ROTATIONS=RANGE_ROTATIONS, 
        SAMPLE_NOISE=SAMPLE_NOISE)
    torch.save(obj=pn_model.state_dict(), f=save_dir / "pointnet_model.pth")
    with open(save_dir / "pointnet_model_specs.pickle", "wb") as handle:
        pickle.dump(pn_specs, handle)

print(f"{pn_specs['num_epochs']} epochs took {pn_specs['duration']:.2f}s")
print(f"Trainable parameters: {sum(p.numel() for p in pn_model.parameters() if p.requires_grad)}")
plot_loss_curve(pn_specs["loss_curve"])

# --- Visual Inspection ---
plot_visual_results(
    model=pn_model,
    num_samples=2**13, # results in [1, 2**13, 2] model input
    eval_bag_size=2**13, # same as num_samples => only one bag, no random bagging
    num_twists_arr=[1, 2, 3],
    rotations=to_rad(np.array([-(30 + 10e-4), 0, (30 + 10e-4)])),
    is_reversed=False,
    device=DEVICE,
    sample_noise=SAMPLE_NOISE,
    evaluate_model_function=eval_transformer # possible due to eval_bag_size=num_samples => no random bagging
)
100000 epochs took 717.55s
Trainable parameters: 2898
Evaluating 9 x 8,192 samples, each with evaluation bag size 8192 
and batch size 1 took 0.03s in total on M2.
(a) Training and evaluating a PointNet baseline on the dynamic two-spirals task using the same stochastic bag setup as with the Transformer Encoder + Monte Carlo Approach
(b)
Figure 12

The result? It fails entirely. Because all of these dynamic spirals occupy roughly the same noisy 2D disk, PointNet’s global max-pooling discards the fine-grained relational structure needed to infer twists, rotation, and direction—it looks at the overall geometry, shrugs, and decides everything is just a very confusing circle.

Final Notes

  • This method is easy to understand and fast to implement.
  • It is highly accurate (see RapidParc (published in Imaging Neuroscience)).
  • It has a fast O(n\cdot c) runtime and a small memory footprint O(c^2).
  • It does not require discretization.
  • It is very stable to missing values in the evaluation set; even if whole areas are missing.
  • But: Is the pipeline as a whole now permutation equivariant? Well yes and no: The computations within each bag are permutation equivariant. But the whole pipeline is in theory not. But, the model learned via random bagging (as data augmentation) that it should behave in a permutation-equivariant way (which it does quite well, see Figure 8 & Figure 10).

Citation

BibTeX citation:
@online{von_bornhaupt2026,
  author = {von Bornhaupt, Valentin},
  title = {Just {Shuffle:} {Linear-Time} {Set} {Segmentation} with
    {Transformer} {Encoders}},
  date = {2026-11-25},
  url = {https://vavobo.de/posts/monte_carlo_set_segmentation.html},
  langid = {en}
}
For attribution, please cite this work as:
Bornhaupt, Valentin von. 2026. “Just Shuffle: Linear-Time Set Segmentation with Transformer Encoders.” November 25. https://vavobo.de/posts/monte_carlo_set_segmentation.html.