Equivariant linear layers: intertwiners, irreps and Schur's lemma
Construct equivariant linear layers as constraint null spaces, use Schur’s lemma and characters to understand their structure, and compare numerical implementations.
After this lesson you can
- Solve intertwiner constraints using discrete and infinitesimal generators.
- Apply Schur’s lemma while distinguishing real and complex representations.
- Compute character multiplicities and isotypic projectors.
- Relate cyclic group Fourier transforms to shared convolution weights.
- Build and evaluate equivariant networks with explicit numerical tolerances.
Before you start
- 25Group representationEquivariant and invariant mapsSymmetry groups in machine learningEquivariant linear layers on setsEquivariant linear layers on graphs
- 02Null spaceNumerical rankSingular value decompositionKronecker productVec operator and the vec trickDFT matrixCirculant matrixMatrix exponential
- 24SO(3) exponential and logarithm maps
Turning symmetry into linear algebra
Suppose you know how each input and output channel transforms under a group. A linear layer is equivariant exactly when transforming before or after the layer gives the same result. The question “which layers are allowed?” becomes a linear equation system.
The intertwiner space between and contains matrices satisfying
It is a subspace: a linear combination of solutions is also a solution. If a basis is found, only its coefficients need be learned and one can write . An affine layer also has a bias that must be invariant under the output representation; not every bias vector is allowed.
For of size , stack its columns in . Identity gives a constraint with columns:
Column-stacking convention matters. If your library flattens by rows, formulas and Kronecker order change. Stacking constraints for several generators and computing the null space gives a layer basis. Nullity is the number of independent linear parameters before considering bias.
If equalities hold for generators they also hold for products and inverses: with invertible matrices implies . A very large finite group need not be enumerated. Adding a reflection to rotations of imposes and can reduce the null space; the figure identifies the group actually generated.
In practice use SVD of the stacked matrix and inspect the spectrum. Too high a threshold includes only approximately equivariant directions; too low can treat numerical noise as rank. The figure uses eigenvalues of to illustrate small dimensions: forming that matrix amplifies conditioning problems, so it does not replace stable SVD of .
The numerical basis is not unique. Two solvers can return different orthogonal combinations of the same null vectors. Comparing corresponding columns may suggest a nonexistent difference. A more robust comparison checks dimensions and subspace projectors, and tests each basis residual against all constraints.
If near-zero singular values are not clearly separated from the rest, dimension depends on precision and chosen threshold. Report scale, threshold and maximum residual and repeat at higher precision when possible. In the planar-representation example there are two independent directions; adding reflection leaves one. That reduction should not be interpreted as losing a valid solution: the removed direction does not satisfy the new constraint.
Distinguish the allowed weight space from total program parameters. An implementation can store a dense matrix and project it onto the subspace each pass, or directly store basis coefficients. The first may have redundant parameters and more compute cost while representing the same layer family. Biases, gates and nonlinear mixtures add their own parameters.
For an affine layer , the same reasoning requires . For example, a trivial scalar output allows a free bias; one vector admits no fixed nonzero bias that rotates correctly under all rotations. Do not assume a library disables bias without checking its representation.
Infinitesimal generators
In a connected Lie group, for a curve differentiate the condition at . If denotes the representation generator, this gives
In generator suffices. Real solutions commuting with it are . An additional reflection eliminates term and leaves only for . In all three independent infinitesimal generators are imposed. The infinitesimal condition characterizes the connected component they generate; if the group has other components, such as reflections in , discrete generators must be added.
The distinction appears when transforming a vector into an order-two tensor. For a linear map proportional to the fully antisymmetric tensor identifies an axial vector with an antisymmetric matrix. A reflection changes parity and removes that map if input and output are both declared ordinary polar tensors of . In the lab nullity is one for and zero after imposing a reflection. This comparison depends on correctly specifying representations and parity.
For a tensor formed from two vectors, a rotation’s representation is . Its infinitesimal generator is , obtained by differentiating . That Kronecker sum must not be confused with . A useful check evaluates the infinitesimal condition and also tests finite rotations generated by the exponential.
Connectivity is a structural assumption, not a numerical detail. No number of proper-rotation samples alone detects a reflection violation. Likewise, checking only identity in a finite group always passes and does not reveal whether a matrix respects other elements. For a random test include transformations from relevant components and record error norm.
Irreducibles and blocks
An irreducible representation has no nontrivial proper invariant subspaces. For finite groups over , Maschke’s theorem decomposes every finite-dimensional representation into a direct sum of irreps. Continuous finite-dimensional unitary representations of compact groups admit analogous analysis. Irreps are defined up to basis change; implementations must keep equivalent bases aligned when mixing copies.
Schur’s lemma follows by observing that an intertwiner’s kernel and image are invariant subspaces. Between two irreps a nonzero intertwiner must be invertible. Over , choosing eigenvalue of an irrep endomorphism makes have nontrivial kernel and hence be zero. Thus between inequivalent complex irreps only the zero map exists, and within one complex irrep every endomorphism is a scalar.
If a complex irrep appears times in input and times in output, its copies can mix with a matrix of that size. The number of complex parameters is . Identity on each irrep’s internal space repeats in every mixing block. Inequivalent types cannot be mixed by an equivariant linear layer.
Over there is an essential distinction: a real irrep’s endomorphism ring can have dimension 1, 2 or 4 over the reals. For the positive-frequency planar irrep of , gives dimension two. Thus two input and three output copies allow real parameters, not six. By contrast, planar irrep E of must also commute with reflection and allows only real identity multiples.
This exception does not contradict Schur: the proof using complex eigenvalues does not guarantee a real eigenvalue of a real matrix. Complex numbers and quaternions appear as possible endomorphism algebras of real irreps. To count parameters reliably, state the field, each irrep type and multiplicities; do not apply a complex formula without checking assumptions.
In the interactive example, input has dimensions and output . Mixtures among A₁ copies contribute two numbers, A₂ another two and E another two. The E block contains two scalar copies of the size-two identity; its four entries are not four independent parameters. The figure applies different basis changes to input and output, and the matrix appears full without gaining freedoms.
To check a basis change, transform representations too: if , input and output matrices transform with their respective . Changing only the weight matrix and keeping old group matrices formulates a different condition. In a network with consecutive layers, one layer’s output basis must match the next layer’s input basis.
Characters and projectors
A representation’s character is . Trace is unchanged by basis change and constant on each conjugacy class. For finite groups the complex character inner product averages over the group; its value is the multiplicity of irrep .
Classes allow one sum per type multiplied by class size. In , classes have sizes 1, 3 and 2; the natural three-coordinate representation decomposes into trivial plus two-dimensional standard. In , the regular representation contains every irrep with multiplicity equal to its dimension: four one-dimensional irreps and two copies of the two-dimensional one. Total dimension is .
In the figure, the unknown representation combines permutation of three letters with a coordinate changing by parity. The unknown permutes the square’s four diagonal vertices. First identify classes, then use fixed points and traces to obtain the character, and finally expand each inner product and select multiplicities before checking.
The complex isotypic projector of an irrep of dimension is . Its image gathers every copy of that type. Projectors of different types are orthogonal in a unitary representation and sum to identity. Obtaining an isotypic block does not automatically choose an internal basis aligned among all its copies.
In the regular representation of , projector ranks are 1, 1, 1, 1 and 4. The last rank is four because the E isotypic space has two copies of dimension two. The lab verifies idempotence, symmetry and that their sum is identity. These checks do not require knowing adapted basis vectors in advance.
For complex characters conjugating the first factor is indispensable. In characters of opposite frequencies are conjugates and their inner product must be zero; omitting conjugation can swap multiplicities. The coding exercise includes that case as well as natural and regular representations. Values near integers should only be rounded after checking numerical error.
Fourier on a cyclic group
The group Fourier transform expresses a signal in components adapted to its representations. For complex irreps are one-dimensional and the unitary DFT diagonalizes cyclic shift. Circular convolution is a polynomial in that shift; it is also diagonal in the Fourier basis and each frequency is multiplied by its response.
If generates , one character-table convention is , with . The conjugate sign is also valid when frequencies are exchanged. Orthogonality of those rows follows by summing roots of unity: inner product is one for the same frequency and zero for distinct ones.
The real regular representation of has eight real parameters in its commutant: the eight entries of a circular convolution. Although complex frequencies appear in conjugate pairs for real signals, they are not counted as independent real parameters without imposing that relation. For nonabelian groups Fourier produces matrix blocks larger than one instead of only scalars per frequency.
To see diagonalization, write convolution as a sum of shifts with kernel coefficients. The DFT diagonalizes each shift and therefore their sum. Inverse transforming returns to the node basis. Exponential sign determines the phase assigned to each frequency; reversing the shift convention as well keeps the result consistent.
The connection to shared weights is direct: a circulant matrix uses the same pattern at every position, cyclically shifted. If the boundary is not periodic, the matrix no longer represents the same action and the DFT need not diagonalize the operation. Zero-padded and circular convolution are different symmetry problems.
From a basis to a network
An equivariant MLP builds linear layers from intertwiners and combines blocks with compatible nonlinearities. An invariant scalar gate can multiply a vector without changing its transformation; coordinatewise ReLU on a rotating vector breaks the property. Tensor products can create new features but increase dimensions and cost.
EMLP automates basis construction for matrix-group representations and uses them in networks with gates and bilinear operations. The library is a concrete reference, not a guarantee that every large representation is cheap: the constraint matrix or its null space may be enormous. Tolerance, generator choice and tensor type remain design decisions.
In a deep network each layer must respect the declared action on its channels and one layer’s output must use the same component order as the next layer’s input. Equivariance of a linear layer cannot save normalization treating equivalent coordinates differently. An end-to-end test transforms an input, runs the whole network, transforms the original output and compares both routes at different scales.
Data augmentation is an empirical baseline but does not impose the equation for every transformation. To compare both choices, fix task, split and budget, record parameters and time, and assess prediction error separately from equivariance residual. A constant output can have zero residual and be useless for the task.
Lab: solve and decompose
The following cell uses NumPy SVD for both discrete and infinitesimal generators. It calculates D₄ projector ranks, S₃ multiplicities and diagonalizes a C₈ convolution. The infinitesimal constraint describes the connected group; for O(3) an explicit reflection is added.
import itertools
import numpy as np
def solve_intertwiners(gens_in,gens_out,rtol=1e-10):
# vec apila columnas: vec(W A)=(Aᵀ ⊗ I)vec(W).
if not gens_in or len(gens_in)!=len(gens_out):raise ValueError('generadores emparejados requeridos')
n=gens_in[0].shape[0]; m=gens_out[0].shape[0]
constraints=np.concatenate([np.kron(a.T,np.eye(m))-np.kron(np.eye(n),b) for a,b in zip(gens_in,gens_out)])
_,singular,vh=np.linalg.svd(constraints,full_matrices=True)
threshold=rtol*max(constraints.shape)*(singular[0] if len(singular) else 0)
rank=int(np.sum(singular>threshold))
return [v.reshape((m,n),order='F') for v in vh[rank:]],singular,threshold
def direct_sum(*matrices):
n=sum(a.shape[0] for a in matrices);out=np.zeros((n,n));i=0
for a in matrices:out[i:i+len(a),i:i+len(a)]=a;i+=len(a)
return out
J=np.array([[0.,-1.],[1.,0.]])
R=J.copy();S=np.diag([1.,-1.])
c4,svals,tol=solve_intertwiners([R],[R])
d4,_,_=solve_intertwiners([R,S],[R,S])
so2,_,_=solve_intertwiners([J],[J]) # J es generador infinitesimal, no elemento del grupo en esta restricción.
two_three,_,_=solve_intertwiners([direct_sum(J,J)],[direct_sum(J,J,J)])
assert (len(c4),len(d4),len(so2),len(two_three))==(2,1,2,12)
for w in d4: assert np.allclose(w@R,R@w) and np.allclose(w@S,S@w)
print('Dimensiones C4, D4, SO2, SO2 con 2→3 copias:',len(c4),len(d4),len(so2),len(two_three))
print('Valores singulares C4:',np.round(svals,7),'tolerancia:',tol)
Lx=np.array([[0,0,0],[0,0,-1],[0,1,0]],float)
Ly=np.array([[0,0,1],[0,0,0],[-1,0,0]],float)
Lz=np.array([[0,-1,0],[1,0,0],[0,0,0]],float)
lie=[Lx,Ly,Lz];lift=lambda a:np.kron(a,np.eye(3))+np.kron(np.eye(3),a)
so3,_,_=solve_intertwiners(lie,[lift(a) for a in lie])
reflection=np.diag([-1.,1.,1.])
o3,_,_=solve_intertwiners(lie+[reflection],[*(lift(a) for a in lie),np.kron(reflection,reflection)])
assert len(so3)==1 and len(o3)==0
print('Vector → tensor de orden 2, SO3/O3:',len(so3),len(o3))
def d4_mul(a,b):return ((a[0]+(-1)**a[1]*b[0])%4,(a[1]+b[1])%2)
elements=list(itertools.product(range(4),range(2)))
index={g:i for i,g in enumerate(elements)}
def standard(g):return np.linalg.matrix_power(R,g[0])@np.linalg.matrix_power(S,g[1])
def regular(g):
mat=np.zeros((8,8))
for j,h in enumerate(elements):mat[index[d4_mul(g,h)],j]=1
return mat
def chars(g):
k,f=g
return np.array([1,(-1)**f,(-1)**k,(-1)**(k+f),np.trace(standard(g))],float)
character_table=np.array([chars(g) for g in elements])
assert np.allclose(character_table.T@character_table/8,np.eye(5))
character_regular=np.array([np.trace(regular(g)) for g in elements])
mult=character_table.T@character_regular/8
assert np.allclose(mult,[1,1,1,1,2])
projectors=[]
for i,dim in enumerate([1,1,1,1,2]):
p=sum(dim*chars(g)[i]*regular(g) for g in elements)/8
assert np.allclose(p@p,p) and np.allclose(p.T,p)
projectors.append(p)
assert np.allclose(sum(projectors),np.eye(8))
print('D4 regular: multiplicidades',mult.astype(int).tolist(),'rangos isotípicos',[round(np.trace(p)) for p in projectors])
# S3: carácter de permutación = número de puntos fijos; signo = paridad.
perms=list(itertools.permutations(range(3)))
def sign(p):return (-1)**sum(p[i]>p[j] for i in range(3) for j in range(i+1,3))
s3chars=np.array([[1,sign(p),sum(p[i]==i for i in range(3))-1] for p in perms],float)
natural=np.array([sum(p[i]==i for i in range(3)) for p in perms])
s3mult=s3chars.T@natural/6
assert np.allclose(s3chars.T@s3chars/6,np.eye(3)) and np.allclose(s3mult,[1,0,1])
print('S3 permutación natural: multiplicidades',s3mult.astype(int).tolist())
# La DFT unitaria diagonaliza el desplazamiento cíclico y toda matriz circulante.
n=8;shift=np.roll(np.eye(n),1,axis=0)
F=np.exp(-2j*np.pi*np.outer(np.arange(n),np.arange(n))/n)/np.sqrt(n)
diagonal=F@[email protected]().T
assert np.allclose(diagonal,np.diag(np.diag(diagonal)))
kernel=np.array([1.,2.,-1.,0.,0.,0.,0.,0.]);C=sum(kernel[k]*np.linalg.matrix_power(shift,k) for k in range(n))
assert np.allclose(F@[email protected]().T,np.diag(np.diag(F@[email protected]().T)))
print('DFT: desplazamiento y convolución circular diagonalizados')
Inertia tensor: custom solver and EMLP
The next local experiment generates synthetic five-point clouds and predicts the inertia tensor about the origin, with equal masses and normalized by point count. Clouds are not centered: the task is equivariant to rotations and reflections about the origin, not arbitrary translations. Train uses anisotropic clouds with small rotations about one axis; test uses random rotations and reflections. The target tensor is calculated directly from points.
The custom network forms outer products of each point and uses solver-computed bases for tensor-to-tensor maps; scalar gates depend on norm. We compare SO(3) and O(3) versions, a conventional MLP with O(3) augmentation and SO(3) and O(3) EMLP versions. The custom implementation starts from quadratic features already containing target structure; MLP and EMLP receive coordinates without that lifting. Parameter counts also differ, so the table is not a capacity-matched comparison.
| Train | Custom SO(3) | Custom O(3) | Augmented MLP | EMLP SO(3) | EMLP O(3) |
|---|---|---|---|---|---|
| 32 | 0.2094 | 0.1880 | 0.3781 | 0.9123 | 0.9120 |
| 128 | 0.1904 | 0.1699 | 0.1620 | 0.9130 | 0.9170 |
Figures are mean squared error per component on 128 test clouds, one seed and 100 full-batch CPU training steps. There is no hyperparameter selection or multiple seeds; EMLP has one hidden layer of 16 channels and does not converge well in this short test. These are not paper results and cannot generally rank architectures.
For train size 128, equivariance residual under O(3) transformations was approximately for both custom versions, 0.273 for the augmented MLP, for SO(3) EMLP and for O(3) EMLP. It is computed as mean difference norm divided by mean reference norm. Both custom versions are also reflection equivariant on this particular task because their inputs are products of two polar vectors; this does not make every SO(3) network O(3)-equivariant.
The custom network stores 31 parameters, the MLP 5769 and EMLP 537 unprojected parameters; the latter include redundancy from equivariant projections. Printed timing excludes initial basis construction and may include JAX compilation, so it is not a clean latency comparison. Code downloads or reads packages only, no external data. EMLP 1.0.3 ran with NumPy 2.2.6, SciPy 1.15.3, JAX and jaxlib 0.4.38, Objax 1.8.0, Optax 0.2.5 and Plum 1.7.4; install those dependencies and PyTorch 2.11 in an isolated environment. The displayed run uses JAX and PyTorch on CPU. Code environment variables can change samples and steps.
import os,time,json,math
os.environ['JAX_PLATFORMS']='cpu' # Coincide con el dispositivo PyTorch usado en este proceso.
import numpy as np
import torch
from torch import nn
from emlp.groups import SO,O
from emlp.reps import T
from emlp.nn.pytorch import EMLP
torch.set_num_threads(1)
torch.manual_seed(17);np.random.seed(17)
device=torch.device('cpu') # La versión PyTorch de EMLP usa JAX CPU en este entorno.
sizes=[int(n) for n in os.environ.get('INERTIA_SIZES','32,128').split(',')]
epochs=int(os.environ.get('INERTIA_EPOCHS','100'));test_n=int(os.environ.get('INERTIA_TEST','128'))
points=5
def solve(gin,gout):
n=gin[0].shape[0];m=gout[0].shape[0]
a=np.concatenate([np.kron(x.T,np.eye(m))-np.kron(np.eye(n),y) for x,y in zip(gin,gout)])
_,s,vh=np.linalg.svd(a,full_matrices=True);rank=int((s>1e-9*max(a.shape)*s[0]).sum())
return np.array([v.reshape((m,n),order='F') for v in vh[rank:]])
Lx=np.array([[0,0,0],[0,0,-1],[0,1,0]],float);Ly=np.array([[0,0,1],[0,0,0],[-1,0,0]],float);Lz=np.array([[0,-1,0],[1,0,0],[0,0,0]],float)
lie=[Lx,Ly,Lz];I3=np.eye(3);K=lambda a:np.kron(a,I3)+np.kron(I3,a)
reflection=np.diag([-1.,1.,1.]);F3=np.kron(reflection,reflection)
def basis(group):
generators=[K(a) for a in lie]
return solve(generators+([F3] if group=='O3' else []),generators+([F3] if group=='O3' else []))
Q_SO=basis('SO3');Q_O=basis('O3');assert len(Q_SO)==len(Q_O)==3
print('Dimensiones de bases SO3 y O3:',len(Q_SO),len(Q_O),flush=True)
class Own(nn.Module):
def __init__(self,base):
super().__init__();self.register_buffer('B',torch.tensor(base,dtype=torch.float32));self.coeff=nn.Parameter(torch.randn(points,len(base))*.1);self.gate=nn.Parameter(torch.randn(points,len(base))*.1);self.bias=nn.Parameter(torch.zeros(()))
def forward(self,x):
x=x.reshape(-1,points,3);outer=(x[:,:,:,None]*x[:,:,None,:]).reshape(-1,points,9);radius=x.square().sum(-1)
weights=self.coeff[None,:,:]+self.gate[None,:,:]*torch.tanh(radius[:,:,None])
y=torch.einsum('bpj,kij,bpk->bi',outer,self.B,weights)/points
return y+self.bias*torch.eye(3).reshape(1,9)
class Ordinary(nn.Module):
def __init__(self):super().__init__();self.net=nn.Sequential(nn.Linear(points*3,64),nn.ReLU(),nn.Linear(64,64),nn.ReLU(),nn.Linear(64,9))
def forward(self,x):return self.net(x.reshape(-1,points*3))
def haar(n,generator,reflections=False):
q=torch.randn(n,4,generator=generator);q=q/q.norm(dim=1,keepdim=True);w,x,y,z=q.unbind(1)
R=torch.stack([1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w),2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w),2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)],dim=1).reshape(n,3,3)
if reflections:
sign=torch.where(torch.rand(n,generator=generator)<.5,-1.,1.);R[:,:,0]*=sign[:,None]
return R
def rotate(x,R):return torch.einsum('bij,bpj->bpi',R,x)
def inertia(x):
outer=torch.einsum('bpi,bpj->bij',x,x)/points
return (torch.eye(3)[None]*outer.diagonal(dim1=1,dim2=2).sum(1)[:,None,None]-outer).reshape(-1,9)
def dataset(n,seed,train):
gen=torch.Generator().manual_seed(seed);x=torch.randn(n,points,3,generator=gen)*torch.tensor([1.5,.7,.3])
if train:
angle=(torch.rand(n,generator=gen)*2-1)*.3;c,s=angle.cos(),angle.sin();zero=torch.zeros(n);one=torch.ones(n)
rotations=torch.stack([c,-s,zero,s,c,zero,zero,zero,one],1).reshape(n,3,3)
else: rotations=haar(n,gen,reflections=True)
x=rotate(x,rotations);return x,inertia(x)
def transform_tensor(y,R):
a=y.reshape(-1,3,3);return (R@[email protected](1,2)).reshape(-1,9)
test_x,test_y=dataset(test_n,91,False);gen=torch.Generator().manual_seed(93)
test_rot=haar(test_n,gen,False);test_orth=haar(test_n,gen,True)
results={}
for n in sizes:
train_x,train_y=dataset(n,11,True);results[n]={}
for kind in ('propia_SO3','propia_O3','mlp_aumentada','emlp_SO3','emlp_O3'):
torch.manual_seed(17);gen=torch.Generator().manual_seed(37)
if kind=='propia_SO3':model=Own(Q_SO)
elif kind=='propia_O3':model=Own(Q_O)
elif kind=='mlp_aumentada':model=Ordinary()
else:model=EMLP(5*T(1),T(2),SO(3) if kind=='emlp_SO3' else O(3),ch=16,num_layers=1)
model=model.to(device);opt=torch.optim.Adam(model.parameters(),lr=.01);start=time.perf_counter()
for _ in range(epochs):
x=train_x
if kind=='mlp_aumentada':x=rotate(x,haar(n,gen,True))
target=inertia(x);pred=model(x.reshape(n,-1));loss=(pred-target).square().mean()
opt.zero_grad();loss.backward();opt.step()
train_seconds=time.perf_counter()-start;model.eval()
with torch.no_grad():
y=model(test_x.reshape(test_n,-1)); mse=float((y-test_y).square().mean())
residual=[]
for R in (test_rot,test_orth):
yr=model(rotate(test_x,R).reshape(test_n,-1));expected=transform_tensor(y,R)
residual.append(float((yr-expected).norm(dim=1).mean()/expected.norm(dim=1).mean().clamp_min(1e-12)))
rec={'test_mse':mse,'residuo_SO3':residual[0],'residuo_O3':residual[1],
'train_seconds':round(train_seconds,3),'parameters':sum(p.numel() for p in model.parameters())}
results[n][kind]=rec;print(n,kind,rec,flush=True)
out=os.environ.get('INERTIA_OUTPUT','inertia_results.json')
with open(out,'w',encoding='utf8') as f:json.dump({'sizes':sizes,'test':test_n,'epochs':epochs,'device':str(device),'results':results},f,indent=2)npm run lab and open the connection link.Exercises
Step 1 of 3. Why is ker W invariant?
Step 1 of 3. What happens for a product gh?
def multiplicities(rho, irreps, group_elements):
pass