Module contents
Lesson 8 of 30Core 105 min

Permutation symmetry: sets, DeepSets and equivariant layers

Study permutation invariance and equivariance, characterize linear set and graph layers, and explore DeepSets, pooling and Set Transformers.

After this lesson you can

  • Define permutation actions and invariant and equivariant graph functions.
  • Characterize linear set-equivariant layers as λI + γ11ᵀ.
  • Explain the DeepSets representation and its latent-dimension limits.
  • Count equivariant linear operators on adjacency matrices and identify nonlocal operations.
  • Implement sum, max and attention set architectures and check numerical invariance.

Before you start

Order is not a graph feature

A network of five machines remains the same network if we number its machines differently. Yet entries of an adjacency matrix move when numbering changes. A classifier that gives different answers solely because rows were reordered has learned a storage convention, not a graph property. A graph-level output should remain unchanged; a node-level output should follow its corresponding node.

For permutation matrix PP and attributes X∈Rn×dX\in\R^{n\times d}, the action on graphs is (X,A)↦(PX,PAP⊤)(X,A)\mapsto(PX,PAP\T). The second multiplication permutes columns as well as rows: an edge must continue connecting the same two entities. A graph function FF is invariant if F(PX,PAP⊤)=F(X,A)F(PX,PAP\T)=F(X,A); a node function HH is equivariant if H(PX,PAP⊤)=PH(X,A)H(PX,PAP\T)=PH(X,A). This is the distinction between invariance and equivariance: the former removes ordering from the output, the latter carries it correctly.

The orbit of (X,A)(X,A) contains all its renumberings. Two representations of the same graph lie in the same orbit; equal predictions on that orbit do not force distinction between non-isomorphic graphs. Testing a few permutations is useful, but does not prove an arbitrary function satisfies the identity for all permutations.

For example, in a three-node directed network with edges 1→21\to2 and 2→32\to3, swapping names 1 and 3 transforms both coordinates of each edge: they become 3→23\to2 and 2→12\to1. Permuting only rows of AA leaves columns naming the previous nodes and describes a different relationship. With attributes x1,x2,x3x_1,x_2,x_3, the node formerly numbered 1 must carry x1x_1 with it. In global classification the prediction stays the same; in segmentation, the label previously assigned to node 1 must now appear at node 3’s position.

If H1H_1 and H2H_2 are equivariant, then H2(H1(PX))=PH2(H1(X))H_2(H_1(PX))=PH_2(H_1(X)). Summing rows of an equivariant output gives 1⊤PH(X)=1⊤H(X)\mathbf1\T PH(X)=\mathbf1\T H(X) because 1⊤P=1⊤\mathbf1\T P=\mathbf1\T. This composition explains the usual structure: shared layers produce per-node representations, followed by a symmetric readout of the whole set. A positional label tied to storage index breaks symmetry; a real node feature can be permuted with the node.

Two kinds of weight for a set

Let y=Wxy=Wx with x∈Rnx\in\R^n. The condition for linear equivariance on sets is PW=WPPW=WP for every permutation. Equivalently PWP⊤=WPWP\T=W. The symmetric group can map any diagonal position (i,i)(i,i) to another, and any off-diagonal pair (i,j)(i,j) with i≠ji\ne j to any other. Thus all diagonal coefficients are equal and all remaining coefficients are equal. For n≥2n\ge2:

W=λI+γ11⊤,yi=λxi+γ∑j=1nxj.W=\lambda I+\gamma\mathbf1\mathbf1\T,\qquad y_i=\lambda x_i+\gamma\sum_{j=1}^n x_j.

Under this parameterization the diagonal is λ+γ\lambda+\gamma and remaining entries are γ\gamma. The condition is sufficient because both II and 11⊤\mathbf1\mathbf1\T commute with any PP. For n=1n=1 the two terms are dependent and the space has dimension one. With input and output channels, λ\lambda and γ\gamma become shared matrices; an equivariant bias is identical for every element.

InteractiveSymmetry ties the weights

Click a cell to cycle through values from −2 to 2. Blue marks the diagonal; orange marks other positions.

Input: 1.0, 2.0, −1.0, 0.5, 3.0
Actual output: 1.00, 2.00, −1.00, 0.50, 3.00
Expected output: 1.00, 2.00, −1.00, 0.50, 3.00

One permutation is a partial test; equality within both orbits guarantees the property for all.

Maximum error0.0000
Each button edits an entry of W. Expected output is computed by permuting the previous output. Enforcing equivariance averages the two position orbits and obtains a matrix commuting with all permutations, not only the one shown.

The figure’s projection changes parameters; it does not preserve all earlier predictions. Global summation lets each element receive information from all others; it is equivariant even though it is not a local graph operation.

The proof can equivalently be viewed as parameter sharing. If names ii and jj are swapped, the weight with which an element views itself must be the same for both: Wii=WjjW_{ii}=W_{jj}. For any two ordered pairs of distinct indices, a permutation maps the first to the second, so all cross weights coincide. This conclusion requires all permutations. A circulant layer, for example, can commute with cyclic shifts but not an arbitrary transposition; a test using only shifts need not detect the problem.

Input and output can have multiple channels. Then for output channel bb, the self contribution combines input channels using one matrix and the global contribution uses another. Every node uses the same two matrices. Applying an elementwise nonlinearity afterward preserves equivariance provided it is the same in every row. A weight specific to row 3 breaks the rule even if matrix shapes are compatible.

DeepSets: encode, sum and read out

An invariant family is f({xi})=ρ(∑iϕ(xi))f(\{x_i\})=\rho(\sum_i\phi(x_i)): the same function ϕ\phi transforms each element, the sum is independent of order, and ρ\rho reads the result. The DeepSets theorem concerns conditions on domain and regularity; it does not claim that a fixed-latent-dimension network exactly represents every continuous function on sets of arbitrary size. Zaheer and colleagues establish a representation for countable domains; the continuous case requires attention to set size and latent dimension.

For a concrete construction, take a multiset of exactly nn real numbers in a compact interval and choose ϕ(x)=(x,x2,…,xn)\phi(x)=(x,x^2,\ldots,x^n). Power sums determine elementary symmetric polynomials via Newton’s identities. These are coefficients of the polynomial whose roots are the elements, with multiplicity: the representation distinguishes multisets. Every continuous fixed-size symmetric function can be written as a continuous function of that representation on its image; a sufficiently expressive network can approximate the required functions on compact sets. For bounded variable sizes, add a constant coordinate that counts elements. This construction explains sufficiency in one case, not a guarantee of efficient training.

Wagstaff and colleagues show dimensional limits for universal continuous representation: with maximum cardinality nn, latent dimension below nn is insufficient in general. The result establishes existence of difficult functions under its assumptions; it does not say every particular task fails when d<nd<n or that a training plot must show a perfect step. The interactive’s median is one task with finite networks, limited initialization and optimization.

InteractiveHow many dimensions does the sum need?

Rows: size n. Columns: latent dimension d. Select a cell to read its error; deeper blue means lower RMSE.

n/d12342345

A separate network is trained for each size and dimension. This illustration depends on optimization and data; its errors do not prove representational impossibility.

Size n2
Dimension d1
Test RMSEnot run
Each cell trains a sum-based network from scratch for set size n and dimension d, and measures RMSE on 256 new sets. Data are synthetic uniform numbers; the map does not prove a universal limit or guarantee convergence.

Set pooling can also use mean or maximum. With constant features, summing 11 counts cardinality; mean and maximum return 11 for any nonempty set of identical elements. PointNet max pooling can ignore elements that win no channel and is useful as a global descriptor, but generally does not count duplicates. If nn is known another way, it can be supplied explicitly: losing it in pooling does not make it impossible to recover from any enriched input.

The example {1,1}\{1,1\} versus {1,1,1}\{1,1,1\} shows cardinality loss: their means and maxima coincide, while sums are 2 and 3. If every set has exactly five elements, the mean is the sum multiplied by 1/51/5 and loses no additional information relative to it. If size changes, mean no longer determines sum unless size is also known. No pooling is optimal for every objective: max is sensitive to a single winner per channel, sum can vary with point count, and mean changes interpretation as the sampling distribution changes.

Attention without positional encodings is also equivariant: jointly permuting queries, keys and values permutes the score matrix on both axes and row-wise softmax preserves that correspondence. A fixed learned query attending to the set produces an invariant readout. Set Transformer combines attention blocks and seed pooling; its inducing points reduce attention cost relative to the quadratic case when their count is fixed. Normalized attention does not automatically count duplication of every identical element either: it needs a cardinality signal if the task requires one.

Fifteen operators for matrices

A linear layer on matrices has coefficients Tij,klT_{ij,kl} in Yij=∑klTij,klAklY_{ij}=\sum_{kl}T_{ij,kl}A_{kl}. Permuting nodes simultaneously in input and output requires coefficients to be constant on each orbit of quadruples (i,j,k,l)(i,j,k,l). Two quadruples belong to the same orbit if their indices have the same equality pattern. For n≥4n\ge4 there are 15 partitions of four positions, the Bell number B4=15B_4=15: each exact-equality mask defines an operator and masks are independent because their supports are disjoint. For n=2n=2 there are eight patterns and for n=3n=3 fourteen; patterns requiring more distinct indices than nodes do not exist.

InteractiveThe 15 equivariant layers of an adjacency
Adjacency
0
1
1
0
0
0
1
0
1
0
0
0
1
1
0
1
0
0
0
0
1
0
1
1
0
0
0
1
0
1
0
0
0
1
1
0
Output
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

Equal letters mean equal indices; distinct letters mean distinct indices. Without loops, patterns requiring diagonal inputs yield zero. Some outputs aggregate global edges and are nonlocal.

1
Pattern (i,j,k,l)a a a a
Equivariance error0.0000
Each operator sums entries whose four indices satisfy an exact equality pattern. The six-node matrix realizes all 15 patterns; output computed after permutation is compared with permutation of the previous output.

The equivariant graph linear basis of Maron and colleagues includes identity, transposition, diagonal information and row, column or whole-matrix aggregates. The figure uses another valid basis made from exact-equality masks; linear combinations of these recover familiar operators. For symmetric matrices, constrained diagonals or other conventions, the effective space can have another dimension. Equivariance alone imposes neither locality nor sparsity; a global sum can communicate distant nodes in one layer.

To interpret a mask, consider pattern (a,b,a,b)(a,b,a,b): it requires i=ki=k, j=lj=l and i≠ji\ne j, so it copies off-diagonal entries. Pattern (a,a,a,a)(a,a,a,a) retains the diagonal. Adding them gives the full identity. Pattern (a,b,b,a)(a,b,b,a) copies transposed off-diagonal entries and adding the diagonal pattern gives transposition. Other patterns sum many entries for each position. In the figure, without loops diagonal entries are zero and several masks return zero: that is a property of this input, not a linear dependence between operators defined on all matrices. Enable loops and direction to explore more cases.

The same count for a matrix input and vector output has three indices (i,k,l)(i,k,l). With at least three nodes there are five partitions: all equal, each of three ways to equate exactly two, and all distinct. This count applies to scalar channels; multiple channels introduce coefficient matrices for each orbit. Equivariant biases form another space and are not included in the 15 linear operators.

Local neighbor-aggregation layers, studied later, add a structural constraint and usually scale with edges. The choice among symmetry, locality and pooling is an architectural decision. In the module’s second half the same question is generalized to geometric group actions.

Lab: dimensions and manual gradients

The following system represents coefficient equalities imposed by adjacent transpositions generating SnS_n. Each connected component of these equalities contributes one free variable. This solves the parameter-sharing system without constructing a dense equation matrix and shows why fifteen requires at least four nodes. Then a network with shared tanh⁡\tanh, sum and decoder is implemented; backward is computed by hand and checked against a central difference.

[ ]Generators and equality systemBrowser
import itertools
import numpy as np

def equivariant_dim(n,order):
    tuples=list(itertools.product(range(n),repeat=order))
    m=len(tuples); pos={v:i for i,v in enumerate(tuples)}
    parent=list(range(m*m))
    def root(i):
        while parent[i]!=i:
            parent[i]=parent[parent[i]]; i=parent[i]
        return i
    def union(a,b):
        a,b=root(a),root(b)
        if a!=b: parent[a]=b
    for s in range(n-1):
        p=list(range(n)); p[s],p[s+1]=p[s+1],p[s]
        mapped=[pos[tuple(p[x] for x in v)] for v in tuples]
        for i in range(m):
            for j in range(m): union(i*m+j,mapped[i]*m+mapped[j])
    return len({root(i) for i in range(m*m)})
[ ]Count free parametersBrowser
for n in (2,3,4): print('n',n,'conjuntos',equivariant_dim(n,1),'matrices',equivariant_dim(n,2))
assert [equivariant_dim(n,2) for n in (2,3,4)]==[8,14,15]
[ ]DeepSets forward and backwardBrowser
class DeepSet:
    def __init__(self,seed=3,d=12,h=16):
        r=np.random.default_rng(seed)
        self.p=[r.normal(0,.4,(1,d)),np.zeros(d),r.normal(0,.2,(d,h)),np.zeros(h),r.normal(0,.2,(h,1)),np.zeros(1)]
    def forward(self,x):
        w,b,v,c,u,z=self.p
        h=np.tanh(x[:,:,None]*w+b); s=h.sum(axis=1); q=np.tanh(s@v+c); y=(q@u+z)[:,0]
        return y,(x,h,s,q)
    def loss_grad(self,x,y):
        pred,(x,h,s,q)=self.forward(x); w,b,v,c,u,z=self.p
        e=pred-y; loss=np.mean(e*e); dy=(2*e/len(y))[:,None]
        gu=q.T@dy; gz=dy.sum(axis=0); dq=([email protected])*(1-q*q)
        gv=s.T@dq; gc=dq.sum(axis=0); [email protected]
        dh=ds[:,None,:]*(1-h*h)
        gw=np.sum(dh*x[:,:,None],axis=(0,1))[None,:]; gb=dh.sum(axis=(0,1))
        return loss,[gw,gb,gv,gc,gu,gz]
    def fit(self,x,y,steps=250):
        m=[np.zeros_like(p) for p in self.p]; v=[np.zeros_like(p) for p in self.p]; rng=np.random.default_rng(91)
        for t in range(1,steps+1):
            ix=rng.integers(len(x),size=64); loss,g=self.loss_grad(x[ix],y[ix])
            for i,p in enumerate(self.p):
                m[i]=.9*m[i]+.1*g[i]; v[i]=.999*v[i]+.001*g[i]**2
                p-=.005*(m[i]/(1-.9**t))/(np.sqrt(v[i]/(1-.999**t))+1e-8)
        return loss

Samples are synthetic digits normalized between 0 and 1 in five-element sets. Training and test are generated separately; targets are sum and population variance. The equivariance check compares one permutation, while the sum architecture proves invariance for all in exact arithmetic. The lab’s Adam optimizer is also implemented in NumPy.

[ ]Check a gradientBrowser
rng=np.random.default_rng(17); x=rng.integers(0,10,size=(512,5))/9; test=rng.integers(0,10,size=(256,5))/9
model=DeepSet(); y=x.sum(axis=1); loss,grad=model.loss_grad(x[:4],y[:4]); old=model.p[0][0,0]; eps=1e-5
model.p[0][0,0]=old+eps; plus=model.loss_grad(x[:4],y[:4])[0]
model.p[0][0,0]=old-eps; minus=model.loss_grad(x[:4],y[:4])[0]; model.p[0][0,0]=old
print('gradiente numérico/manual',round((plus-minus)/(2*eps),7),round(grad[0][0,0],7))
assert abs((plus-minus)/(2*eps)-grad[0][0,0])<1e-5
[ ]Learn the sumBrowser
def evaluar(name,target,target_test):
    model=DeepSet(); model.fit(x,target); pred=model.forward(test)[0]; rmse=np.sqrt(np.mean((pred-target_test)**2)); perm=np.array([3,0,4,1,2]); err=np.max(np.abs(pred-model.forward(test[:,perm])[0]))
    print(name,'RMSE test',round(float(rmse),5),'error permutación',round(float(err),12))

evaluar('suma',x.sum(axis=1),test.sum(axis=1))
[ ]Learn the varianceBrowser
evaluar('varianza',x.var(axis=1),test.var(axis=1))

With the stated seeds, the checked gradient is approximately 0.0436084 by both methods; root-mean-square errors are 0.07813 for sum and 0.01003 for variance. These results come from a synthetic split and 250 updates, not a proof of universal accuracy. The sum gradient sends each element the same derivative with respect to the aggregated representation; then each activation multiplies by the local derivative of tanh⁡\tanh. Central difference detects errors in the tested parameter but does not replace checks of others.

Local lab: point clouds

The ModelNet10 dataset contains CAD meshes and official train and test splits. Download the official archive, extract meshes and run the full preparation from the point-cloud lesson: sample 256 points per surface, center and normalize by maximum radius, and save modelnet10_train.npz and modelnet10_test.npz. Preparation requires NumPy, PyTorch and Open3D. The cell looks for files in the current directory or the folder indicated by ORYON_MODELNET_DIR, and accepts shortened names train.npz and test.npz. It does not download data during automated execution.

A seeded selection chooses 1024 training examples and 256 from the test split, using the first 64 prepared points of each cloud. All four models share the split and epoch count. The sum network divides by 64, a constant for this fixed-size sample; the max network resembles PointNet; attention uses self-attention and a learned query, a small version of the Set Transformer scheme rather than the full paper architecture. The MLP flattens the cloud and receives a random order per sample each epoch. Augmentation can improve robustness but does not guarantee invariance. Such a short evaluation illustrates symmetry properties; it does not rank architectures.

[ ]Compare architectures on ModelNet10Local GPU
import os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

# Preparación reproducible completa en m24-l15: 256 puntos por malla, centrados y normalizados.
root=Path(os.environ.get('ORYON_MODELNET_DIR','.'))
train_path=root/'modelnet10_train.npz'; test_path=root/'modelnet10_test.npz'
if not train_path.exists():
    train_path=root/'train.npz'; test_path=root/'test.npz'
if not train_path.exists() or not test_path.exists():
    raise FileNotFoundError('Ejecuta la preparación de ModelNet10 de m24-l15 y conserva modelnet10_train.npz y modelnet10_test.npz')
train=np.load(train_path); test=np.load(test_path)
rng=np.random.default_rng(71); tr=rng.permutation(len(train['x']))[:1024]; te=rng.permutation(len(test['x']))[:256]
xtr=torch.tensor(train['x'][tr,:64],dtype=torch.float32); ytr=torch.tensor(train['y'][tr],dtype=torch.long)
xte=torch.tensor(test['x'][te,:64],dtype=torch.float32); yte=torch.tensor(test['y'][te],dtype=torch.long)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('dispositivo',device,'train/test',len(tr),len(te),'puntos',xtr.shape[1])

class PoolNet(nn.Module):
    def __init__(self,kind):
        super().__init__(); self.kind=kind
        self.phi=nn.Sequential(nn.Linear(3,32),nn.ReLU(),nn.Linear(32,32),nn.ReLU())
        self.head=nn.Sequential(nn.Linear(32,32),nn.ReLU(),nn.Linear(32,10))
    def forward(self,x):
        h=self.phi(x); h=h.sum(1)/64 if self.kind=='sum' else h.max(1).values
        return self.head(h)

class SetAttention(nn.Module):
    def __init__(self):
        super().__init__(); self.embed=nn.Linear(3,32); self.self_att=nn.MultiheadAttention(32,4,batch_first=True); self.pool=nn.MultiheadAttention(32,4,batch_first=True); self.seed=nn.Parameter(torch.randn(1,1,32)*.02); self.head=nn.Linear(32,10)
    def forward(self,x):
        x=self.embed(x); h,_=self.self_att(x,x,x,need_weights=False); h=h+x
        z,_=self.pool(self.seed.expand(len(x),-1,-1),h,h,need_weights=False)
        return self.head(z[:,0])

class OrderedMLP(nn.Module):
    def __init__(self):
        super().__init__(); self.net=nn.Sequential(nn.Flatten(),nn.Linear(64*3,128),nn.ReLU(),nn.Linear(128,10))
    def forward(self,x): return self.net(x)

for kind in ('sum','max','attention','ordered'):
    torch.manual_seed(42); torch.cuda.manual_seed_all(42)
    model=(PoolNet(kind) if kind in ('sum','max') else SetAttention() if kind=='attention' else OrderedMLP()).to(device)
    opt=torch.optim.Adam(model.parameters(),lr=.001)
    loader=DataLoader(TensorDataset(xtr,ytr),batch_size=32,shuffle=True,generator=torch.Generator().manual_seed(52))
    for epoch in range(3):
        model.train(); total=0
        for x,y in loader:
            # Orden aleatorio por muestra para los cuatro modelos, cada época.
            order=torch.rand(x.shape[0],x.shape[1]).argsort(1); x=x.gather(1,order[:,:,None].expand_as(x)).to(device); y=y.to(device)
            opt.zero_grad(); logits=model(x); loss=nn.functional.cross_entropy(logits,y); loss.backward(); opt.step(); total+=loss.item()*len(x)
    model.eval(); perm=torch.randperm(64)
    with torch.no_grad():
        logits=torch.cat([model(b.to(device)).cpu() for b in xte.split(32)]); reordered=torch.cat([model(b[:,perm].to(device)).cpu() for b in xte.split(32)])
    print(kind,'pérdida última',round(total/len(xtr),4),'exactitud test',round(float((logits.argmax(1)==yte).float().mean()),4),'error máximo al permutar',round(float((logits-reordered).abs().max()),7))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In an RTX 3060 execution, test accuracies were 0.1953 for sum, 0.2305 for max, 0.0898 for attention and 0.1367 for the MLP. Maximum logit differences after permutation were approximately 10−710^{-7}, 0, 2×10−72\times10^{-7} and 0.694198, respectively. The first three errors are consistent with floating-point rounding; the last shows order dependence in that execution. Low accuracies and one split reflect the reduced budget, not a conclusive comparison. Implementations and devices can produce small numerical differences.

Exercises

Proof
Prove: Prove that W commutes with every permutation if and only if W = λI + γ11ᵀ for n≥2.
0
Consider simultaneous action on row and column indices of W.

Step 1 of 2. Which positions can be exchanged by a common row and column permutation?

Proof
Prove: Prove that composition of equivariant layers is equivariant and summing their rows produces an invariant output.
0
Assume H₁(PX)=PH₁(X) and H₂(PZ)=PH₂(Z).

Step 1 of 2. What is H₂(H₁(PX))?

Numeric
For n≥3, how many independent linear operators from an n×n matrix to an n-vector are equivariant to all permutations?
Quiz
With the same function per element and identical inputs, which pooling can count elements without receiving the count separately?
Code
Implement check_equivariance(f, X, A, trials): test reproducible random permutations and return the maximum absolute error between f(PX, PAPᵀ) and P f(X,A). Output of f has one row per node.
import numpy as np
def check_equivariance(f, X, A, trials=20):
  pass
Shift+Enter to run

Key ideas

Key idea
An equivariant layer carries renumbering into its output; symmetric pooling turns a per-element representation into an invariant output.

Symmetry ties parameters and removes ordering artifacts, but alone guarantees neither locality, universal expressivity at small dimension nor correct training.