Module contents
Lesson 22 of 30Advanced 115 min

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

Turning symmetry into linear algebra

Suppose you know how each input and output channel transforms under a group. A linear layer WW 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 ρin\rho_{\rm in} and ρout\rho_{\rm out} contains matrices satisfying

Wρin(g)=ρout(g)Wpara todo g∈G.W\rho_{\rm in}(g)=\rho_{\rm out}(g)W\qquad\text{para todo }g\in G.

It is a subspace: a linear combination of solutions is also a solution. If a basis B1,…,BdB_1,\ldots,B_d is found, only its coefficients need be learned and one can write W=∑iθiBiW=\sum_i\theta_iB_i. An affine layer also has a bias that must be invariant under the output representation; not every bias vector is allowed.

For WW of size m×nm\times n, stack its columns in vec⁡(W)\operatorname{vec}(W). Identity vec⁡(AWB)=(B⊤⊗A)vec⁡(W)\operatorname{vec}(AWB)=(B\T\otimes A)\operatorname{vec}(W) gives a constraint with mnmn columns:

Ag=ρin(g)⊤⊗Im−In⊗ρout(g),A_g=\rho_{\rm in}(g)\T\otimes I_m-I_n\otimes\rho_{\rm out}(g),

Agvec⁡(W)=0.A_g\operatorname{vec}(W)=0.

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.

InteractiveSolve symmetry as a linear system

Rotation or cycle generator; the control adds a discrete generator. The natural S₃ representation permutes three coordinates; for C₄ and SO(2) it acts on planar vectors. The trivial representation is scalar.

Singular values: 2.0000 · 2.0000 · 0.0000 · 0.0000

Base 1
0.00-0.71
0.710.00
Base 2
0.710.00
0.000.71

AᵀA is diagonalized to obtain these singular values and vectors, an illustrative technique that loses precision near zero. For real problems use SVD of A and a spectrum-relative tolerance. Bases can rotate within the null space without changing it.

Group
Input representation
Output representation
Generated groupC₄
Null-space dimension2
Shape of W2 × 2
Threshold2.0e-7
Choose input and output representations separately, construct the constraint matrix and diagonalize AᵀA. Singular values, tolerance and bases are shown.

If equalities hold for generators they also hold for products and inverses: WA=BWW A=B W with invertible matrices implies WA−1=B−1WW A^{-1}=B^{-1}W. A very large finite group need not be enumerated. Adding a reflection to rotations of C4C_4 imposes D4D_4 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 A⊤AA\T A to illustrate small dimensions: forming that matrix amplifies conditioning problems, so it does not replace stable SVD of AA.

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 C4C_4 planar-representation example there are two independent directions; adding reflection D4D_4 leaves one. That reduction should not be interpreted as losing a valid D4D_4 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 x↦Wx+bx\mapsto Wx+b, the same reasoning requires ρout(g)b=b\rho_{\rm out}(g)b=b. For example, a trivial scalar output allows a free bias; one SO(3)SO(3) 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 g(t)=exp⁡(tA)g(t)=\exp(tA) differentiate the condition at t=0t=0. If dρ(A)d\rho(A) denotes the representation generator, this gives

W dρin(A)=dρout(A) W.W\,d\rho_{\rm in}(A)=d\rho_{\rm out}(A)\,W.

In SO(2)SO(2) generator J=[0−110]J=\bigl[\begin{smallmatrix}0&-1\\1&0\end{smallmatrix}\bigr] suffices. Real solutions commuting with it are aI+bJaI+bJ. An additional reflection eliminates term bJbJ and leaves only aIaI for O(2)O(2). In SO(3)SO(3) 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 O(3)O(3), discrete generators must be added.

The distinction appears when transforming a vector into an order-two tensor. For SO(3)SO(3) 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 O(3)O(3). In the lab nullity is one for SO(3)SO(3) 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 R⊗RR\otimes R. Its infinitesimal generator is A⊗I+I⊗AA\otimes I+I\otimes A, obtained by differentiating (exp⁡tA)⊗(exp⁡tA)(\exp tA)\otimes(\exp tA). That Kronecker sum must not be confused with A⊗AA\otimes A. 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 C\mathbb C, 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 C\mathbb C, choosing eigenvalue λ\lambda of an irrep endomorphism makes W−λIW-\lambda I 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 miinm_i^{\rm in} times in input and mioutm_i^{\rm out} times in output, its copies can mix with a matrix of that size. The number of complex parameters is ∑imiinmiout\sum_i m_i^{\rm in}m_i^{\rm out}. Identity on each irrep’s internal space repeats in every mixing block. Inequivalent types cannot be mixed by an equivariant linear layer.

InteractiveSchur makes blocks

Input: 2A₁ ⊕ A₂ ⊕ 2E. Output: A₁ ⊕ 2A₂ ⊕ E. Each E has dimension 2 and its block is a scalar mixture repeated across both coordinates.

0.70-0.01-0.30-0.15-0.020.040.00
0.35-0.190.270.380.05-0.10-0.01
0.02-0.050.11-0.17-0.100.200.02
-0.060.15-0.300.210.17-0.34-0.04
-0.010.03-0.060.090.470.36-0.20

Blue indicates positive sign and orange negative. In the adapted basis zeros appear between types; A₁, A₂ and E blocks contribute 2 + 2 + 2 parameters. Orthogonal basis change visually mixes types without changing the layer.

Base
0.6
Shape5 × 7
Free parameters6
Real D₄ example with irreps A₁, A₂ and E. The same matrix is calculated in two orthogonal bases; the control changes an E-block coefficient.

Over R\mathbb R 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 SO(2)SO(2), aI+bJaI+bJ gives dimension two. Thus two input and three output copies allow 2⋅3⋅2=122\cdot3\cdot2=12 real parameters, not six. By contrast, planar irrep E of D4D_4 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 D4D_4 example, input has dimensions 2+1+4=72+1+4=7 and output 1+2+2=51+2+2=5. 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 W′=QoutWQin−1W'=Q_{\rm out}WQ_{\rm in}^{-1}, input and output matrices transform with their respective QQ. 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 χ(g)=tr⁡ρ(g)\chi(g)=\operatorname{tr}\rho(g). Trace is unchanged by basis change and constant on each conjugacy class. For finite groups the complex character inner product averages χi(g)‾χ(g)\overline{\chi_i(g)}\chi(g) over the group; its value is the multiplicity of irrep ii.

InteractiveBuild the character table

Conjugacy groups elements with the same character. Sizes sum to the group order:

  • e: 1 element
  • transp.: 3 elements
  • 3-cycle: 2 elements

In S₃ classes are distinguished by cycle. In D₄ reflections form two classes.

Group
Representation
Step
Group order6
Input dimension4
Explore classes, traces and inner products of S₃ or D₄. Calculate multiplicities of an unknown representation and check your answer.

Classes allow one sum per type multiplied by class size. In S3S_3, classes have sizes 1, 3 and 2; the natural three-coordinate representation decomposes into trivial plus two-dimensional standard. In D4D_4, 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 4+2⋅2=84+2\cdot2=8.

In the figure, the unknown S3S_3 representation combines permutation of three letters with a coordinate changing by parity. The D4D_4 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 did_i is Pi=(di/∣G∣)∑gχi(g)‾ρ(g)P_i=(d_i/|G|)\sum_g\overline{\chi_i(g)}\rho(g). 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 D4D_4, 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 C3C_3 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 S3S_3 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 CnC_n 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 rr generates CnC_n, one character-table convention is χk(rj)=exp⁡(2πikj/n)\chi_k(r^j)=\exp(2\pi\mathrm{i}kj/n), with k,j=0,…,n−1k,j=0,\ldots,n-1. 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 C8C_8 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 CnC_n 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.

[ ]Intertwiners, characters and DFTBrowser
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.

TrainCustom SO(3)Custom O(3)Augmented MLPEMLP SO(3)EMLP O(3)
320.20940.18800.37810.91230.9120
1280.19040.16990.16200.91300.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 1,8⋅10−71{,}8\cdot10^{-7} for both custom versions, 0.273 for the augmented MLP, 3,3⋅10−53{,}3\cdot10^{-5} for SO(3) EMLP and 1,6⋅10−71{,}6\cdot10^{-7} 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.

[ ]Inertia with custom solver and EMLPLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
What is the real dimension of the equivariant endomorphism space of the real regular representation of C₈?
Numeric
The real standard representation of SO(2) appears twice in input and three times in output. How many real parameters does an intertwiner have?
Proof
Prove: An intertwiner between irreps is zero or an isomorphism; over ℂ an irrep endomorphism is scalar.
0
Let W be a linear map satisfying Wρin(g)=ρout(g)W for every g.

Step 1 of 3. Why is ker W invariant?

Proof
Prove: Checking group generators suffices to check the full intertwiner.
0
Suppose Wρin(gᵢ)=ρout(gᵢ)W for each generator and invertible matrix representations.

Step 1 of 3. What happens for a product gh?

Quiz
Why does the real planar frequency-k≥1 irrep of SO(2) admit two independent endomorphisms I and J?
Code
Implement multiplicities(rho, irreps, group_elements). rho and each element of irreps are functions taking an element and returning a complex or real NumPy matrix. Return a list of integer multiplicities using the average of conj(χᵢ)χ. Reject an empty group and results more than 10⁻⁸ away from a real integer.
def multiplicities(rho, irreps, group_elements):
  pass
Shift+Enter to run
Key idea
An equivariant layer is a point in the null space of constraints. Irrep theory explains its structure, but counting depends on the field and specific representations.