SO(3) in depth: spherical harmonics, Clebsch-Gordan and tensor field networks
Use SO(3) irreps, spherical harmonics and Clebsch-Gordan products to build equivariant tensor field networks and analyze their computational cost.
After this lesson you can
- Describe SO(3) irreps, Wigner matrices and O(3) parity.
- Compute and transform real spherical harmonics through degree two.
- Apply Clebsch-Gordan coupling rules and multiplicity counts.
- Explain tensor field convolution, higher body order and SO(2) reduction.
- Interpret measured molecular-force experiments with explicit resource limits.
Before you start
- 25Schur's lemmaIrreducible representationsCharacters and isotypic decompositionSteerable kernelsE(n)-equivariant graph neural networkVector feature networksGeometric graphsForces as gradients of an invariant energy
- 03Polar, cylindrical and spherical coordinatesLaplace equation and harmonic functions
- 02Tensor product and multilinear mapsOrthonormal basisChange of basis
- 18Multi-head attentionAttention as soft dictionary lookup
Beyond a vector
Energy is a scalar; a dipole has three components rotating together; a quadrupole or stress tensor contains higher-order directional information. Treating each component as an independent scalar channel would lose the rule linking them under rotation. The previous lesson built vector channels; now we generalize that idea while retaining equivariance.
SO(3) irreducible representations and Wigner matrices classify the integer types appearing here: for each , space has dimension and a rotation acts through . In a real orthonormal basis those matrices are real and orthogonal. is scalar, vectorial and corresponds to symmetric traceless matrices of dimension five. A network can have multiple copies of each type; coefficients of one copy mix under rotation, but different degrees do not mix.
For , parity is added, the sign under spatial inversion. A position vector is (odd), angular momentum is (axial, even) and a pseudoscalar is . Restricted to SO(3), both parity types of the same have the same rotational action; under reflection they are no longer interchangeable. Chirality requires retaining this distinction.
Parity refers to simultaneous coordinate inversion, not the sign of one component. Any reflection with negative determinant can be written with . Its action on type is then . Thus knowing the rotation representation and inversion sign suffices to reconstruct the action of all . Absolute position also shifts when translating the origin, so relative edge vectors rather than raw positions are normally coupled.
Multiplicity is not an extra spatial dimension. A state with copies of contains numbers: each block of five transforms by the same matrix , while an equivariant linear map can freely mix copies with a channel matrix. An arbitrary matrix on the numbers, however, could treat orientations unequally and break the transformation law. Counting copies, components and weights separately is essential for interpreting cost and capacity.
Harmonics as direction coordinates
Spherical harmonics of degree form a basis of the angular-function space transforming as . For unit direction , vector satisfies
The equality depends on a coherent basis, ordering and normalization convention. A convenient real basis for is ; for five polynomials result, where is an orthonormal basis of symmetric traceless matrices. In the lab integral normalization multiplies those polynomials by ; the interactive uses the same basis up to a common factor per degree. Basis-change coefficients do not change when every function of one degree is multiplied by the same constant.
For , identify a five-coefficient vector with matrix . Under rotation and entry of is . Orthogonal conjugation preserves the Frobenius product, so is orthogonal. This construction avoids confusing one library’s convention with another; an orthogonal basis change conjugates every matrix and also transforms coupling coefficients.
The group law is also checked in this representation. With two rotations and , applying first and then takes to . By uniqueness of coordinates in basis , . Orthogonality alone does not define a representation: an arbitrary family of orthogonal matrices might not respect composition.
Integral normalization allows comparing functions of different degrees without depending on arbitrary polynomial amplitude. On the unit sphere, and rotational symmetry also fixes fourth-order moments. This gives the and factors used below. If one package normalizes to constant sum of squares per direction and another to unit integral, outputs differ by a known factor; equivariance is unchanged if the same convention is used throughout.
A useful check integrates each function’s square over the sphere: with this normalization it should be one, and the product integral of distinct functions zero. For example, has square integral one because the sphere’s area is . The three degree-one functions are proportional to direction coordinates; their sphere average is zero. A zero direction has no corresponding sphere point, so the lab rejects it instead of inventing an orientation.
To distinguish a function from a representation, take . Actively rotating the pattern gives . Because is orthogonal, rotated-pattern coefficients are . By contrast, changing axes without moving the object introduces the inverse. This difference explains many apparently contradictory signs in harmonic visualizations.
Clebsch-Gordan: which products are allowed
The Clebsch-Gordan tensor product decomposes two SO(3) irreps without multiplicities:
For the output must also have parity . Thus can produce , and : dot product, axial cross product and symmetric traceless part. Their dimensions match . If there are copies of input and output types, each allowed triple of copies admits a scalar weight, yielding weights for that path. This counts mixing parameters; it does not automatically equal implementation operation count.
By Schur’s lemma, an equivariant linear map between two irreducible copies of the same type is a scalar multiple of identity in this real case. Since each appears once in the preceding decomposition, bilinear projection is unique up to scale when the path is allowed, and zero otherwise. The claim assumes integer SO(3) irreps and one copy of each input and output; multiplicities introduce weight matrices between copies.
This uniqueness does not say a numerical coefficient table has identical signs in every library. If input bases change by invertible matrices and output basis by , the intertwiner in new coordinates transforms as . Wigner matrices also change by conjugation. A table from one convention and rotation matrix from another can yield a large residual even if each is separately correct. The exercise therefore fits and checks everything in the same basis and the e3nn cell uses only e3nn conventions.
For two ordinary vectors you can see the three pieces without a table. The scalar part is . The antisymmetric part corresponds to and is axial: inverting both vectors leaves their cross product unchanged. The degree-two part is the symmetric traceless matrix
Its projection onto the five gives five numbers. The three pieces are orthogonal in the Frobenius product and reconstruct tensor . Each piece’s scaling factor depends on the chosen intertwiner convention; changing it does not change type or parity. These products turn an abstract angular description into familiar geometric operations.
As a second example, allows outputs , and . Their dimensions sum to , equal to , and all have odd parity. If the architecture retains only degrees through , it discards degree-three output: it remains equivariant because a whole decomposition block is removed, although that information is lost. Truncating individual components of one irrep, however, generally does not respect rotation action.
Tensor field networks
A tensor field network (TFN) converts each edge into direction and distance, computes harmonic , multiplies by learned radial functions and couples that type with neighbor channels using Clebsch-Gordan. Sum aggregation preserves permutations. Radial coefficients are scalars and introduce no preferred orientation. Thomas et al. use harmonic filters to build layers transforming as scalars, vectors and higher-order tensors.
A steerable kernel condition is . If both edge direction and input state are transformed, the two input factors cancel and output rotates by . Radial functions depend only on and harmonics supply angular dependence; intertwiners let those parts satisfy the condition. At zero edge length unit direction is undefined, so coincidences must be excluded or a compatible extension defined and its derivatives checked.
A numerical test must transform all involved objects in the same direction: relative positions, input features and expected output. For convolution over an edge set, jointly permute indices and features when renumbering nodes too. Compare absolute and relative error and test multiple rotations, reflections if included in the group, and configurations near cutoff. Tolerance depends on numeric type and output magnitude: small rounding error does not prove the law for all group elements, but can reveal an implementation mixing conventions.
A componentwise nonlinearity on generally does not commute with . Scalar gates, norms and tensor products are compatible ways to introduce nonlinearity. NequIP uses equivariant convolutions for interatomic potentials and forces derived from energy. Its published accuracy depends on data, training and architecture; this lesson’s small potential is illustrative and does not reproduce that evaluation.
For example, with polar vector and even scalar gate , operation remains polar. Scalar function may be sigmoid because its input does not change under rotation; it is not applied independently to the three coordinates of . Conversely, multiplying an odd pseudoscalar gate by a polar vector gives an axial vector: its parity changes. A norm is an even scalar, but its derivative near zero needs numerical treatment when training forces.
When building energy, internal channels may have many degrees, but final readout must produce an even scalar if energy is reflection invariant. For a vector property the head must have appropriate type and parity; for a chiral response an odd channel may be needed. These rules do not replace examining the physical environment: an external field, for example, must also transform as input or breaks the symmetry being imposed.
Body order and cost
The higher body order of MACE is built by combining symmetric tensor products of an atomic-environment basis. Multiplying several neighbor sums introduces correlations among multiple neighbors at once, without explicitly enumerating every tuple in naive form. In MACE, four-body messages permit two iterations in the described experiments. This does not prove two layers suffice for every task or data distribution.
The idea can be seen without expanding all Clebsch-Gordan indices. Form local descriptor . Its cubic product contains terms : combining three neighbors with center produces correlations of up to four bodies. Some indices can coincide, so the product also contains lower-order terms. Atomic cluster expansion (ACE) couples these bases with symmetrization and representation rules; MACE incorporates those correlations into learned messages. “Up to four bodies” does not mean four layers or require every term to contain four distinct atoms.
The SO(3)-to-SO(2) convolution reduction aligns an edge with axis . The group fixing that direction consists of rotations about ; in a complex basis an operator commuting with them connects only components with the same . After operating in that frame it transforms back. Alignment rotation is not unique, but SO(2) equivariance makes the result independent of residual rotation around the edge.
With one copy per degree through there are components. A dense matrix has entries; an SO(2) intertwiner matrix in this case has allowed entries, growing as . This simple count alone is not full convolution cost. Passaro and Zitnick reduce dominant tensor-product formulation cost from to under their analysis conventions; alignment, channels, radial functions and memory count too.
Block count follows from each frequency’s multiplicity. For there are possible degrees, hence a block of entries. For each there are degrees for both and , yielding factor two. In a real basis each opposite-frequency pair is represented by a two-dimensional real block; the pattern is written differently but describes the same action.
For example, has modes and . Zero frequency forms an block and each nonzero frequency an block: six allowed entries versus sixteen in a dense matrix. This counts a generic complex SO(2) intertwiner with one copy per degree. Additional reality, parity or specific-kernel restrictions can reduce independent parameters; the counter is not GPU time or a universal learnable-weight count.
Three-dimensional equivariant attention combines invariant scalar attention weights with values transforming as irreps and geometric kernels. If score is an invariant scalar, is too. If every value transforms as the same irrep, transforms as it because factors out of the sum. Normalization must permute with neighbors and values must be built without absolute orientation. This derivation does not imply every score obtained from raw coordinates is invariant.
SE(3)-Transformer combines attention with equivariant kernels for point clouds and graphs. Equiformer uses irreps, tensor products and an attention variant with nonlinear messages for atomistic graphs. Both are specific families: group, parity, neighborhood and output still need choosing. In particular, guaranteeing proper-rotation equivariance does not automatically add reflection invariance.
Lab: real irreps through degree two
Lab functions use an orthonormal matrix basis . To normalize harmonics with respect to sphere area measure, factors , and are used for respectively. In code vectors are stored as rows, so active rotation is x @ R.T.
import numpy as np
from scipy.spatial.transform import Rotation
sqrt=np.sqrt
E=np.array([[[1/sqrt(2),0,0],[0,-1/sqrt(2),0],[0,0,0]],
[[1/sqrt(6),0,0],[0,1/sqrt(6),0],[0,0,-2/sqrt(6)]],
[[0,1/sqrt(2),0],[1/sqrt(2),0,0],[0,0,0]],
[[0,0,1/sqrt(2)],[0,0,0],[1/sqrt(2),0,0]],
[[0,0,0],[0,0,1/sqrt(2)],[0,1/sqrt(2),0]]])
def real_sph_harm(l,xyz):
xyz=np.asarray(xyz,float);r=np.linalg.norm(xyz,axis=-1,keepdims=True)
if np.any(r==0): raise ValueError('dirección nula')
x=xyz/r
if l==0: return np.ones(x.shape[:-1]+(1,))/sqrt(4*np.pi)
if l==1: return x*sqrt(3/(4*np.pi))
if l==2: return np.einsum('...i,kij,...j->...k',x,E,x)*sqrt(15/(8*np.pi))
raise ValueError('solo grados 0, 1 y 2')
def wigner(l,R):
if l==0:return np.ones((1,1))
if l==1:return R
if l==2:return np.einsum('iab,ac,jcd,bd->ij',E,R,E,R)
raise ValueError('solo grados 0, 1 y 2')
R=Rotation.from_euler('xyz',[.4,.2,-.7]).as_matrix();rng=np.random.default_rng(25);x=rng.normal(size=(30,3))
for l in range(3):
D=wigner(l,R);err=np.max(np.abs(real_sph_harm(l,x@R.T)-real_sph_harm(l,x)@D.T))
print('l',l,'equivariancia',err,'ortogonalidad',np.max(np.abs(D.T@D-np.eye(2*l+1))))
assert err<1e-12 and np.allclose(D.T@D,np.eye(2*l+1))We can also recover by least squares from directions and check agreement with the geometric construction. This is a numerical test for the chosen rotation, not an independent definition of every Wigner matrix.
for l in range(3):
Y=real_sph_harm(l,x);Yr=real_sph_harm(l,x@R.T)
Dfit=np.linalg.lstsq(Y,Yr,rcond=None)[0].T
print('l',l,'diferencia D',np.max(np.abs(Dfit-wigner(l,R))))
assert np.allclose(Dfit,wigner(l,R),atol=1e-12)To obtain an intertwiner without memorizing coefficients, solve for several rotations. Numerical nullity is evaluated with tolerance; a finite rotation set is a check, while the Clebsch-Gordan rule is the general result.
rotations=[Rotation.from_euler('xyz',v).as_matrix() for v in ([.2,.5,-.3],[-.7,.1,.4],[.9,-.6,.2])]
def solve_intertwiner(l):
out=2*l+1; cols=out*9; blocks=[]
for R in rotations:
D=wigner(l,R);K=np.kron(R,R); M=np.empty((out*9,cols))
for j in range(cols):
C=np.zeros((out,9));C.flat[j]=1
M[:,j]=(D@C-C@K).ravel()
blocks.append(M)
_,s,Vh=np.linalg.svd(np.vstack(blocks),full_matrices=False)
return s,Vh[-1].reshape(out,9)
for l in range(3):
s,C=solve_intertwiner(l);print('salida',l,'nulidad',int(np.sum(s<1e-10)),'residuo',s[-1])
assert np.sum(s<1e-10)==1
Rtest=Rotation.from_euler('xyz',[.6,-.3,.8]).as_matrix()
assert np.linalg.norm(wigner(l,Rtest)@C-C@np.kron(Rtest,Rtest))<1e-10A minimal convolution applies a radial weight to each coupled product and sums neighbors. Here we combine an input vector with an edge harmonic ; direction is kept away from zero.
_,C=solve_intertwiner(2)
direction=np.array([.4,-.2,.8]);direction/=np.linalg.norm(direction)
v=np.array([.2,.7,-.3]); radial_weight=np.exp(-1.2)
out=radial_weight*(C@np.kron(v,direction))
rotated=radial_weight*(C@np.kron(R@v,R@direction))
print('error convolución',np.max(np.abs(rotated-wigner(2,R)@out)))
assert np.allclose(rotated,wigner(2,R)@out,atol=1e-10)The next count bounds a deliberately dense contraction: it multiplies even Clebsch-Gordan coefficients that could be zero. The filter has one copy per degree and input and output have 32 channels per degree. The SO(2) count is for a generic block matrix at that width; it excludes rotations aligning edges and does not prove an implementation achieves that time ratio.
L=4;channels=32
paths=[(a,b,c) for a in range(L+1) for b in range(L+1) for c in range(L+1) if abs(a-b)<=c<=a+b]
dense=sum((2*a+1)*(2*b+1)*(2*c+1) for a,b,c in paths)*channels**2
local=((L+1)**2+2*sum(k*k for k in range(1,L+1)))*channels**2
print('caminos SO(3)',len(paths),'productos densos',dense,'productos bloques SO(2)',local)
assert (len(paths),dense,local)==(65,13388800,87040)Local lab: e3nn and rMD17
In this cell the library uses its own real basis and normalization. Never mix its or coefficients with the preceding Cartesian basis without the corresponding basis change.
import torch
from e3nn import o3
torch.manual_seed(25)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
irreps=o3.Irreps('1x0e + 1x1o + 1x2e')
Rcpu=o3.rand_matrix();R=Rcpu.to(device);x=torch.randn(16,3,device=device)
Y=o3.spherical_harmonics(irreps,x,normalize=True,normalization='component')
YR=o3.spherical_harmonics(irreps,x@R.T,normalize=True,normalization='component')
D=irreps.D_from_matrix(Rcpu).to(device)
error_y=(YR-Y@D.T).abs().max().item()
out_ir=o3.Irreps('1x0e + 1x1e + 1x2e')
tp=o3.FullyConnectedTensorProduct('1x1o','1x1o',out_ir).to(device)
a=torch.randn(16,3,device=device);b=torch.randn(16,3,device=device)
out=tp(a,b);rotated=tp(a@R.T,b@R.T);expected=out@out_ir.D_from_matrix(Rcpu).to(device).T
error_tp=(rotated-expected).abs().max().item()
print('dispositivo',device,'dimensión armónicos',irreps.dim,'pesos producto',tp.weight_numel)
print('errores armónicos y producto',error_y,error_tp)
assert error_y<1e-4 and error_tp<1e-4npm run lab and open the connection link.Download so3_potencial.py, potenciales.py and checkpoint.py into the same folder. The first requires PyTorch, e3nn and NumPy; the second manages downloading and checking the aspirin split described in the preceding lesson. The small model uses two layers, four channels per irrep, radial filters and FullyConnectedTensorProduct. It is a teaching TFN with energy and forces, not full NequIP or MACE.
In this implementation internal channels have natural parity : , , and, if included, . Increasing adds degrees but not automatically opposite parities, such as axial vector ; energy output is an even scalar. SiLU activation applies only to even scalar channels, while higher-degree channels update through tensor products and residual connections. Energy is invariant under reflections as well as rotations, and forces are calculated as : respecting symmetry alone does not guarantee potential accuracy.
As a numerical check the model trained with and 200 configurations was evaluated on eight test conformations and five transformations combining rotation, translation, permutation and sometimes reflection. In float32 maximum discrepancies were kcal/mol for energy and kcal/mol/Å for forces. With the same weights converted to float64 they were and in those units. Precision and magnitude scale affect numerical-test tolerance; this sample does not show all possible errors are equally small.
python so3_potencial.py --root rmd17 --sizes 50 200 800 --lmax 1 2 3 --epochs 100 --output so3-results.json
The program uses the same splits, loss and validation selection as the preceding lesson’s potentials. It saves energy and force errors, time and maximum allocated memory for each . Compare result files carefully: channel sizes and architecture parameter counts differ. Hardware available for this run may differ from any reference budget; record its actual GPU and do not attribute measurements to another card model.
With seed 42 the original 1000 training configurations are permuted: the first 50, 200 or 800 are used to fit and the last 200 for validation; the test file supplies another 1000. Loss sums mean squared energy error centered on training mean and one hundred times mean squared force error per component. Factor 100 is a weighting choice for these units, not a physical constant. Best epoch is chosen by validation force MAE; energy MAE in kcal/mol and force MAE in kcal/mol/Å are reported on test. Since conformations come from trajectories, a random configuration split is not a test on independent molecules or trajectories.
The following experiment ran all nine combinations of three sizes and for 100 epochs each, comparing them with EGNN and the preceding lesson’s teaching PaiNN variant under the same data protocol. TFN results and baseline results include individual errors and times. One seed and one molecule cannot establish a general ranking; architectures differ in parameters, operations and structure.
With 800 configurations TFN obtains MAE 4.7682, 3.9358 and 3.3182 kcal/mol/Å for , while EGNN gets 3.5515 and PaiNN 1.6053 in these runs. Results for 50 and 200 examples do not retain that ordering across every degree; increasing cannot be inferred to always improve accuracy. TFN has 5905, 13 297 and 25 969 parameters respectively, so increasing degree also changes capacity.
The three runs used an NVIDIA GeForce RTX 3060. with 50 examples combined 65 GPU and 35 CPU epochs after interruption; other TFN runs with and used one-thread CPU. For 800 examples, recorded times were 1001.1 s on GPU for , 1554.5 s on CPU for and 4593.4 s on CPU for . These are not a same-hardware speed comparison across degrees; time excludes waiting and work lost to interruption. Its peak allocated CUDA memory was 35.9 MiB. As a separate reference, one training step with batch eight on that GPU reached 108.9 MiB allocated and 136.0 MiB reserved: a brief measurement, not a full campaign or global memory. CPU-only runs do not measure CUDA peak.
Each epoch saves a checkpoint per degree and size beside JSON with weights, optimizer and random generators. If interrupted, repeat the same command to continue from the last complete epoch. To continue on CPU add --device cpu --threads 1: the checkpoint retains CUDA state and separately records GPU and CPU segments. Arithmetic differences between devices can slightly alter numerical trajectory. Accumulated time resumes from the last saved epoch: it excludes waiting and work in an interrupted epoch, so it is not elapsed wall time from first start to finish. Completed results remain in JSON; use a new path to change budget, seed or batch. Option --telemetry records process allocated and reserved memory and a global sample at each epoch end and on errors; these points need not capture peaks between samples and global values include other processes.
Exercises
Step 1 of 3. How is a bilinear map converted into a linear one?
import numpy as np
def real_sph_harm(l,xyz):
pass