We prove a general form of the regularity theorem for uniformity norms, and deduce a generalization of the Green-Tao-Ziegler inverse theorem, extending it to a class of compact nilspaces including all compact abelian groups and nilmanifolds. We derive these results from a structure theorem for cubic couplings, thereby unifying these results with the ergodic structure theorem of Host and Kra. The proofs also involve new results on nilspaces. In particular, we obtain a new stability result for nilspace morphisms. We also strengthen a result of Gutman, Manners and Varju, by proving that a k-step compact nilspace of finite rank is a toral nilspace (in particular, a connected nilmanifold) if and only if its k-dimensional cube set is connected. We also prove that if a morphism from a cyclic group of prime order into a compact finite-rank nilspace is sufficiently balanced (a quantitative form of multidimensional equidistribution), then the nilspace is toral.