Spatial Mixture-of-Experts
Abstract
Many data have an underlying dependence on spatial location; it may be weather on the Earth, a simulation on a mesh, or a registered image.
Yet this feature is rarely taken advantage of, and violates common assumptions made by many neural network layers, such as translation equivariance.
Further, many works that do incorporate locality fail to capture fine-grained structure.
To address this, we introduce the Spatial Mixture-of-Experts (SM O E) layer, a sparsely-gated layer that learns spatial structure in the input domain and routes experts at a fine-grained level to utilize it.
We also develop new techniques to train SM O Es, including a self-supervised routing loss and damping expert errors.
Finally, we show strong results for SM O Es on numerous tasks, and set new state-of-the-art results for medium-range weather prediction and post-processing ensemble weather forecasts.
Introduction
Many datasets exhibit an underlying, location-based structure, where the value at a point depends on where that point is.
For example, weather predictions [78] depend on their location on Earth; many scientific simulations are parameterized on an underlying mesh [9]; data (e.g., faces) may be specifically aligned [91]; or it may approximately hold, as in natural images with centered objects.
Further, tasks on such data are often dense regression tasks, such as predicting weather several days in the future.
Numerous architectures have been successfully applied to such tasks.
Convolutional neural networks (CNNs) [80] and transformers [74] show promise for medium-range weather prediction.
Locally-connected networks (LCNs), which use independent, rather than shared, filters at each point, have been applied to weather post-processing [38], face recognition [46, 77, 91], and other tasks [18, 71], specifically to learn local features.
Low-rank local connectivity (LRLCN) [30] relaxes the translation equivariance of CNNs while requiring fewer parameters than LCNs.
Other approaches, such as CoordConv [65], add an additional inductive bias by providing explicit input coordinates.
However, for tasks on data with location-based structure, prior approaches suffer from various limitations.
Convolution assumes that data is translation equivariant, which does not hold for such tasks [46, 91].
Approaches like LCNs require many parameters.
Many architectures have been designed for classification tasks and fail to perform well on regression because they opererate at too coarse granularity and are unable to capture key details.
This limits their applicability to important tasks, such as medium-range weather prediction or climate simulations.
Indeed, on a simple heat diffusion task with location-dependent diffusivities (see §3.1), many approaches do not learn the location dependence at all and instead converge to an “average” diffusivity.
To address this, we introduce a novel neural network layer, the Spatial Mixture-of-Experts (SM O E) layer (§2).
An SM O E uses a learned gating function to sparsely select and route from a shared set of experts to each spatial location (e.g., pixel) in an input sample.
This enables experts to specialize to the unique characteristics of different “regions” within the data and easy interpretability by analyzing the gate.
SM O Es require the assumption that all samples in the dataset have a similar underlying spatial structure, but this often holds (at least approximately) for many datasets, such as weather, where each example is on the same latitude/longitude grid.
For the SM O E gating function, we introduce tensor routing , a simple and cheap routing function that effectively learns this spatial
I ndu c
t i v e
b
i a s
Parameters Fully-connected
Convolution
CoordConv
Locally connected
Spatial Mixture-of-Experts (this work)
T il e d L C N
Low-rank locally connected
SMoEwith same experts at every location
SMoEwith different experts at every location (Not to scale)
Convolution:
Locally-connected:
Low-rank locally-connected:
Spatial Mixture-of-Experts:
Filters
Filters 𝛼 ! 𝛼 " 𝛼 # 𝛼 $ 𝛼 % 𝛼 & 𝛽 !
𝛽 " 𝛽 # 𝛽 $ 𝛽 % 𝛽 &
Basis filters
Learnedcombiners 𝛼 # and 𝛽 #
Experts Learned gate
SMoEslearn fine-grained routing to locations
Mixture-of-Experts:
Spatial Mixture-of-Experts:
Experts
G a t e
G a t e
Experts • Coarse-grain routing • >Capacity for constant compute • Classification • Fine-grain routing • Learn location- dependent functions • Regression
Inputs
Input structure (§2.1).
We also find that end-to-end training approaches, as in standard mixture-of-experts (MoEs) [82, 86], do not capture location-dependence well.
Instead, we introduce a separate routing classification loss (§2.2) to train the gate, a self-supervised loss which provides a better learning signal to the gate about incorrect routings.
We also introduce expert error damping (§2.3), which limits expert updates from misroutings, and further improves performance.
Both methods rely on extracting information from the error signal (gradient of the layer output) which would otherwise be uninformative.
Figure 1 provides an overview of SM O Es and a qualitative comparison to important related work.
With these methods, SM O Es are able to learn fine-grain, location-dependent structure which other architectures miss, and consequentially deliver much better performance.
SM O Es are related to and inspired by prior work in MoEs (e.g., [82, 86, 102]), but there are key differences.
Existing MoEs use coarse-grained routing at the sample [99], token [86], or patch [82] level, and experts produce coarse output (e.g., entire samples or channels) while SM O Es route at a fine-grained, per-pixel level.
Fine-grained routing is important for enabling experts to specialize to fine-scale information, which may be crucial [74, 84].
Such MoEs also typically aim to increase model capacity while keeping compute costs constant, whereas the goal of SM O Es is to capture spatial dependencies.
Other work has aimed to incorporate spatial dependence, such as LRLCNs [30], which learn content- and location-dependent weights to combine a set of basis filters.
However, we found that these prior methods failed to capture the fine-grained features necessary for good performance on dense regression tasks (§3.1).
We conduct experiments on several benchmark datasets with SM O Es and conduct extensive ablation studies of SM O E design decisions (§3).
Using a simple heat diffusion dataset, we showcase the limitations of other models and the power of SM O Es in a controlled situation.
We then apply
SM O Es to medium-range weather prediction and outperform the state-of-the-art [53, 80] on WeatherBench [78]; and set a new state-of-the-art for post-processing ensemble weather forecasts on the
ENS-10 dataset [8].
Finally, we show that SM O Es can also be applied to image classification tasks, where we match or outperform LRLCNs while using fewer parameters. Our code is available at https://github.com/spcl/smoe .
1.1 Related Work
Mixture-of-Experts and conditional computation.
While MoEs have long been used [15, 49, 52], since the advent of deep learning, there has been much work in applying MoEs, conditional computation, and dynamic routing to DNNs [1, 4, 5, 7, 10–12, 19–21, 23, 25, 27, 29, 33, 34, 39, 51, 59, 60, 70, 75, 76, 82, 83, 86, 99, 102, 107].
Often, the goal is to increase model capacity without a corresponding increase in compute costs and models use coarse-grained routing.
Notably, MoEs route at the sample (e.g., [25, 29, 70, 83]), token (e.g., [33, 59, 86]), or patch (e.g., [82]) level; are typically trained with extensive auxiliary losses; and often target classification tasks.
This coarse routing, in particular, means there is limited opportunity for experts to specialize.
MoEs specifically for vision tasks also typically operate at a sample-level (e.g., [1, 4, 39, 99, 102]) and use experts to specialize filter or channel choices.
In contrast, our SM O Es induce an inductive bias via finegrained, location-dependent routing for problems with such underlying structure; typically do not need auxiliary losses beyond the routing classification loss; and work well for dense regression tasks.
Local spatial structure.
Locally connected networks (i.e., convolution filters without weight sharing) were historically successful in vision tasks such as facial recognition [18, 46, 77, 91].
Further
Input
Experts ℰ 𝐻 𝑊
Gate 𝐺 , tensor routing 𝒟 ∼ ℰ ×𝐻×𝑊 ( §2.1 )
Select 𝐸 = 1 experts per pixel
Apply experts at locations top $ sparse routing (§2)
MSE loss 𝐿 = 1 𝑁% 𝑋 − 𝑌 !
Error signal 𝑑𝐿 𝑑𝑋 = 2 𝑁(𝑋 − 𝑌)
Routing Classification Loss ( §2.2 )
Identify incorrect routings with error signal magnitude ✓ ✘ ✓ ✓
Construct labels {+1001- 
+}
Compute Loss
Binary crossentropy
Expert Error Damping ( §2.3 )
Incorrect routings ✓ ✘ ✓ ✓
Damp error signals for incorrect routings {+𝛼 
+}
Forward
Backward 𝐶 = 1 input channels 𝐸 ⋅ 𝐹 = 1 output channels ❶ ❷ ❸ work incorporated periodic or tiled weight sharing [37, 71, 105].
However, more recent work often exclusively uses convolution, which has been found to perform better [72] while requiring significantly fewer parameters.
CoordConv [65] explicitly provides pixel coordinates as input.
Because of their structure, a single convolution or CoordConv layer cannot learn location-dependent sparse activations as SM O Es do, and multi-layer networks give limited improvements in practice.
Low-rank locally connected networks [30] learn to combine a small number of basis filters in a location- and inputdependent manner.
These combiners lack sparsity and apply all basis filters at each point, and are softmax-normalized, which can result in a few filters dominating, limiting diversity.
Separate work has used attention to provide position-dependent scaling or integrate context [35, 50, 64, 93, 95, 100].
This has culminated in vision transformers [26] and variants [28, 62, 67, 96, 97], which use specialized attention mechanisms to integrate spatial information.
Other work uses Markov [61, 66] or conditional random fields [16, 43, 106], or graph-based methods [17, 98, 104], to learn long-range dependencies. Additional work has studied incorporating equivariance properties into neural networks (e.g., [13]).
Sparsity.
Our use of sparse routing resembles work on sparsity in DNNs in general [45].
Many approaches learn a fine-grained mask to identify which weights to keep or prune (e.g., [63, 90]), while other approaches sparsify activations (e.g., [3, 47, 56, 68, 69]).
These works use sparsity to improve runtime performance, typically at inference time.
Weather prediction.
Medium-range weather prediction, or forecasting roughly three to seven days in advance [6], is of broad societal import [57].
There has been much interest in applying deep learning to this task [85], and WeatherBench [78] serves as a community benchmark.
Deep learning has also been successfully applied to the related tasks of ensemble post-processing [38, 79] and now-casting (forecasting a few hours in advance) [2, 31, 81, 87–89].
Standard CNNs are currently state-of-the-art on WeatherBench [80] (although graph neural networks show promise on similar data [53]) and are competitive on post-processing tasks [8].
SM O Es can take advantage of the extensive fine-grained, location dependent structure in weather data for improved performance.
Spatial Mixture of Experts
We now introduce the Spatial Mixture-of-Experts (SM O E) layer.
An SM O E uses a learned gating function (§2.1) to select specific experts from a shared set to apply at each point (e.g., pixel) in an input.
The gate learns the underlying spatial structure of the data, and routes specific experts to different “regions”, allowing them to specialize.
An SM O E is predicated on the assumption that the spatial structure is similar across all samples in a dataset.
We also assume data are on a Cartesian mesh (i.e., grid), although this could be generalized.
To train SM O Es, we introduce a self-supervised routing classification loss (§2.2) and expert error damping (§2.3), which we found essential for achieving the best performance.
Figure 2 provides an overview of SM O Es and their training.
We first define the SM O E layer in full generality, then discuss the particular implementation we use. (See §3.1 for ablations.)
Let x ∈ R C × H × W be an input sample (we assume 2D data for simplicity).
The SM O E layer consists of a set E of experts, of which E ≤ |E| will be selected at each point, and a gating function G : R C × H × W
→ R |E|× H × W .
The gating function has exactly E nonzeros at each spatial point ( H × W ), which correspond to the selected experts at that point.
Each expert e ∈ E is applied at the points in x where it has been selected, and may include additional context from x (e.g., surrounding points if e is convolution), and produces an output of size F .
The outputs of each expert at a point are then concatenated to form the output channel dimension (of size E · F ) of the SM O E.
More precisely, let gather I ( · ) select only the input entries where I is nonzero.
Then an SM O E is:
[Equation]
where · is element-wise multiplication, [ e ; . .
stacks tensors, and y ∈ R EF × H × W .
When E ≪ |E| , the gating function induces significant sparsity; this allows an SM O E to compute experts only at the points where they are to be applied, avoiding most computation.
This formulation yields a weighted SM O E, where the expert outputs are scaled by the gating function.
An alternative, which is slightly more efficient and can be more readily interpretable, is an unweighted
SM O E, in which case experts are not scaled, and the gather only uses G ( x ) to select experts.
In this work, we focus on a simple, yet powerful, SM O E layer using convolution filters as experts:
[Equation]
where ⋆ is cross-correlation, i ∈ [ |E| ] , and we have elided the gather for simplicity.
2.1 Gating Functions
The gating function G in an SM O E is critical for learning the underlying location-dependence of the data.
While G can be any function, a good gate should be relatively cheap.
We follow prior work on MoEs (e.g., [82, 86]) and use top- E routing to select experts and sparsify the gate:
G ( x ) =
top E ( g ( x )) , where g ( x ) ∈ R |E|× H × W is a learnable gating layer and top E selects the E largest entries along the first (expert) dimension and sets the remaining entries to 0.
However, we found that normalizing the gating function using softmax, as is typically done, was not necessary.
There are many options for the gating layer.
Many MoE works have used MLPs [82, 86], but we found this did not perform well.
Convolution or CoordConv [65] also did not perform well (§3.1).
Instead, we find that a simple tensor routing gating layer worked best.
With this, g ( x ) = D ∈ R |E|× H × W , where D is a learnable tensor that directly encodes the underlying location dependence and routing structure without depending on the input.
Further, D uses one parameter per expert per location and requires no computation beyond optimizer updates, making it an efficient choice.
We initialize D using a uniform distribution over [ − 3 |E| / EF , 3 |E| / EF ] , which corresponds to a Kaiming uniform initialization with fan-in EF / |E| [41].
However, in many practical cases, some data about locations may be known (e.g., whether it is land or sea when doing weather prediction).
In such cases,
D can be initialized based on this data to assign groups of experts in advance.
This allows the gating function to benefit from prior knowledge while still being able to adjust the routing.
Additionally, a network may contain many SM O E layers, in which case we can share D between layers that have the same spatial dimensions and number of experts, which reduces the overhead of the gate.
Finally, many MoE formulations use a number of auxiliary losses to ensure gates learn good routing policies and avoid mode collapse (e.g., [10, 82, 86]).
When training with the routing classification loss we propose, we did not find additional auxiliary losses to be necessary.
2.2 Training and the Routing Classification Loss
Training MoEs is typically done end-to-end, with the experts and gate learning simultaneously, and sparse gradients based on the routing.
We found this did not lead to good performance with
SM O Es and tensor routing, particularly on regression tasks, as the gate did not learn well: it rarely changed its routing decisions from initialization.
We hypothesize that this is due to a “mismatch” in the gradients on regression tasks, where they are informative for experts but not the gate, because regression aims to make a continuous prediction over both positive and negative values, whereas selecting an expert requires a threshold (see §B).
To address this, we train the gate with a separate, self-supervised loss function, the routing classification (RC) loss.
The key idea is to consider routing as a dense, multi-label classification task: selecting the “correct” experts at each point (cf. semantic segmentation).
The RC loss does exactly this, and trains the gate by constructing appropriate labels.
This also helps avoid mode collapse, where only a small number of experts are selected (see §3.2).
In order to construct these labels, we need to determine whether the gate selected the correct set of experts at each point.
However, such information is not directly available.
Instead, we use the error signal into the SM O E layer (i.e., the gradient of the layer output w.r.t.
the loss) as a proxy, and say that the routing was incorrect when the error signal has a large magnitude for the expert at that point, as this will imply a correspondingly large gradient update.
Further, in the case of a mean-square error loss L (commonly used for regression), the error signal can directly encode the prediction error.
Let
X be the predictions, Y the true values, and N the number of elements in X .
Then the error signal is:
[Equation]
Hence, the error signal is simply the (scaled, signed) error of the predictions.
While this exact relation ceases to hold as backpropagation proceeds, the intuition behind the error signal magnitude remains.
We now define the routing classification loss.
Given the error signal ε into an SM O E layer, and an error quantile q (a hyperparameter), we say that selecting an expert at a point was incorrect if ε at that expert and point is greater than the q th quantile of ε , and correct otherwise.
We use quantiles as they are independent of ε ’s scale, which may be hard to determine and change during training.
We then construct the labels for each point as follows:
Unselected experts start with label 0 .
A correctly selected expert has label 1 .
Finally, if an expert was incorrectly selected, its label is 0 and we add/ ( |E| − E ) to the label value of each unselected expert (note |E| − E is the number of unselected experts).
This corresponds to a uniform prior that the correct expert could be any unselected expert.
With these labels, the RC loss for a gate is then the binary cross-entropy loss of the gate output.
2.3 Expert Error Damping
While the RC loss enables an SM O E gate to be trained directly based on whether it routed correctly, experts that were incorrectly routed to still perform gradient updates based on this routing.
This results in experts updating to improve their performance for locations they may not be applied at in future training iterations after routing changes.
To mitigate this, we propose expert error damping , where the portion of an error signal that corresponds to incorrect routings is damped to limit incorrect updates.
We find that this can improve SM O E performance and reduce convergence time.
Expert error damping is similar to the RC loss, and we classify incorrect routings in the same way.
We then scale the error signal into the experts by a constant factor at each point where the routing was incorrect.
This will limit the magnitude of the update made in response to the misrouting.
2.4 Practical Implementation
We now discuss the implementation of an SM O E layer, primarily focusing on the simple SM O E with convolution filters we use.
In an ideal implementation, the flop cost of an SM O E is the cost of the gate plus the cost of applying the selected experts.
When using a tensor routing gate, there are no flops in the gate.
The flops from applying the selected convolutional experts is equivalent to a standard convolutional layer with a number of filters equal to the number of selected experts.
Hence, SM O Es are quite efficient flop-wise.
However, recent work has shown that data movement is also critical to performance [48].
Because of this, we do not expect even well-optimized implementations to match the runtime of a convolution layer due to the sparse routing, limited locality in accessing expert filters, and other operations, although work on hardware-accelerated sparsity [22] should offer benefits.
Despite this, during inference additional optimizations may be available because the tensor routing gate does not depend on the input and computations could be reordered to maximize locality.
Unfortunately, efficiently implementing the irregular access patterns in an SM O E is challenging in standard Python frameworks, and likely requires custom compute kernels.
Instead we opt for a naïve implementation in PyTorch [73] where we apply all experts at all points and then use gather and scatter operations to implement sparse routing.
Experts are concatenated in sorted routing score
[Figure]
order (i.e., as given by G ( x ) ); while this can result in channel orders changing during training, we find it has little impact (see §3.2).
We find this implementation sufficient even for large-scale tasks.
Experiments
We now present experimental results using SM O Es and a variety of baseline models, as well as ablations of different SM O E components.
First, we describe a simple location-dependent heat diffusion dataset, which we use to study the ability of different architectures to learn location dependence in a controlled environment (§3.1).
We then present results on the WeatherBench [78] medium-range weather forecasting challenge (§3.2) and the ENS-10 [8] dataset for post-processing ensemble weather forecasts (§3.3), where SM O Es set new state-of-the-art performance results.
Lastly, we show results on several image classification tasks, illustrating the breadth of SM O E applicability even in situations without strict location-dependence (§3.4).
All results were run using PyTorch [73] version 1.11 on a large cluster with 16 GB V100 GPUs.
We summarize training details throughout this section, and provide full details in §A.
We use existing
PyTorch implementations when available, and implemented methods ourselves otherwise.
Unless noted, all SM O E results used 3 × 3 convolution kernel experts, unweighted tensor routing gates, RC loss, expert error damping, error quantile q = 0 .
7 , and damping factor 0 .
We report the mean and standard deviation (mean ± std ) over ten runs for all experiments, except for WeatherBench and
ImageNet, which used three runs.
In total, we used about 30k GPU hours for experiments.
3.1 Location-Dependent Heat Diffusion
To study location-dependence in a controlled manner, we generated a heat diffusion dataset with location-dependent diffusivities.
The task is to predict what the heat will be at the next timestep, given the current heat at each point.
Because we know the exact diffusivities and their distribution in the data, it is easy to identify how well a model has learned this task.
We first describe the dataset and its generation in detail, then discuss results and ablation studies on SM O E components.
Dataset.
The dataset consists of a region map, where each location is assigned a type, and each type corresponds to a different heat diffusivity.
The region map and diffusivity assignment are then fixed for the dataset.
We generate the region map randomly using a simple preferential attachment method.
This defines the location-dependence that we wish to learn.
To generate samples, we first randomly distribute drops of heat across the domain, then apply five-point diffusion stencils at each point, using the diffusivity of the region type for each point.
For simplicity, we use zero boundary conditions.
This process is iterated to generate many timesteps from the given starting state.
The dataset then consists of the generated timesteps for many different starting states.
If a model is able to learn the diffusion stencils and the location-diffusivity correspondence, it can exactly predict the next timestep.
Further, the diffusivity stencils are also simple, and exactly correspond to a 3 × 3 convolution kernel with no nonlinearity.
The particular dataset we use consists of 100 , 000 64 × 64 samples, with 1 , 000 initial states evolved for 100 timesteps each.
Adding more samples did not significantly change results.
There are three region types, with diffusivities 0 .
25 , 0 . 025 , and 0 .
Figure 3 (center) shows the region map and [Table] [Table] diffusion stencils.
We report results using “% within 1%”, the percentage of locations in a sample that are within 1% relative error of the true value, as this is more interpretable than a mean-square error.
Results.
Figure 3 (left) shows results on the heat diffusion dataset for SM O Es and a number of baselines: CNNs, LCNs, fully-connected (FC) layers, CoordConv [65], CondConv [102], LRLCNs [30], vision transformers (ViT) [26], and vision MoEs (V-MoE)
For the LCN and FC layers, we use only a single layer as additional ones showed no benefit.
Convolution, CoordConv, CondConv, and LRLCN are the best network found among a set with up to three layers, 3 × 3 kernels, 12 filters per layer, batchnorm, and ReLU activations.
ViT and V-MoE use one transformer block with a patch size of 4 × 4 , an embedding dimension of 128 , and four heads.
LRLCNs use three basis filters and an input-dependent combiner.
We also tried unshared combining weights with no input dependence (LRLCN-ND).
V-MoEs select one expert from a set of three.
Our SM O Es use a single layer with three experts and select E = 1 expert per point.
All models were trained with batch size 32 , Adam [54] with a learning rate of 0 .
001 (decayed by 10 × after no validation improvement forepochs), and early stopping after no improvement for 30 epochs.
Additional hyperparameter tuning did not significantly improve results.
We report SM O E parameters as expert + gate parameters.
SM O Es achieve perfect performance on this dataset.
Further, by examining the learned routing and experts (Fig. 3, right), we can see that it has indeed correctly learned the diffusion stencils and location-dependence.
LCNs also achieve this, but require 3 × more parameters, and requireepochs to converge (versus 8 for SM O Es).
Fully-connected layers failed to learn the data well, likely due to the challenge of optimizing so many parameters.
Other methods all converge to betweenand 94% within 1%.
Examining their predictions and weights, we observe that they do not appear to have learned the location-dependence of the diffusivities, and instead converged to predicting with an “average” diffusivity across the domain.
We also tried larger (deeper and/or wider) convolutional networks, but performance did not improve.
MoE methods (CondConv and V-MoE) also fail in this manner, as their coarse-grained experts are unable to specialize.
Further, the LRLCN-ND fails in this manner, despite its architecture being similar to an SM O E when there is one output channel (a location-dependent, softmax-weighted combination of three basis kernels).
We believe the LRLCN-ND exhibits a similar gradient “mismatch” as discussed earlier (§2.2).
We now discuss a number of different ablations of the SM O E architecture and design.
What if the “right” expert configuration is not known?
While in the above experiments, we were able to select the SM O E expert configuration (number of experts, number of selected experts, expert filter size) so that it is both necessary and sufficient to learn the task, in many situations this information may not be available.
We considered alternative SM O E configurations varying each of these parameters: ❶ using six experts; ❷ experts with 5 × 5 kernels; ❸ and selecting two experts per location from six total.
For case ❸ , we summed the two SM O E output channels together.
In all three cases, the SM O E achieved 100.0 ± 0 % within 1% on the heat diffusion task.
In ❶ , we found that they learned duplicate diffusion stencils and still routed them appropriately.
❷ learned the five-point stencil plus a boundary of near-zero values, thus being nearly identical to the 3 × 3 kernel.
Finally, ❸ learned diffusion stencils that summed together to produce the correct diffusivity.
Thus, we can see that SM O Es are robust and adapt well to these sorts of architecture choices.
RC loss and expert error damping.
Table 1 shows results for training SM O Es with and without our routing classification loss (§2.2) and expert error damping (§2.3).
Without the RC loss, SM O E performance is at par with other baselines in Fig.
3, but once it is added, performance improves significantly as the gating function now learns the location-dependency in the data.
Adding expert error damping further improves performance and convergence by limiting the impact of gate misroutings
[Table] [Table]
on expert learning.
However, damping on its own offers little benefit, as it does not improve gate learning.
These results show that these refinements are critical for good performance.
Gating function.
Table 2 shows the performance of different gating functions (§2.1) on the SM O E.
We consider six options: A single fully-connected layer (as is commonly used in MoEs [82, 86]); a single 3 × 3 convolution, CoordConv [65], or LCN layer; a gate with three CoordConv layers with batchnorm and ReLU; and our tensor routing gate.
When training, we also considered auxiliary losses and other methods for improving performance (see §C) and report the best result.
Our tensor routing offers the best performance.
An LCN performs second-best, likely because it also uses separate parameters per location, but uses 9 × as many parameters and requires significant computation.
Other methods do not appear able to effectively capture location-dependence.
Other ablations.
We conduct a number of additional ablation studies in §C, including using auxiliary losses and routing noise during training, routing normalizations, and expert functions.
3.2 Medium-Range Weather Prediction
We now discuss results on the WeatherBench [78] medium-range weather forecasting benchmark.
This benchmark uses the ERA5 reanalysis dataset [44], with hourly global weather data for 1979– 2018.
We use the data subset suggested by Rasp et al.
[78] at 5.625° resolution ( 32 × 64 grid points) and train on data from 1979–2015, validate on 2016, and report test results for 2017–2018.
We otherwise follow the training methodology of Rasp and Thuerey [80].
The target quantities to predict are geopotential at 500 hPa (Z500) and temperature at 850 hPa (T850) with a three- and five-day lead time.
We report results using latitude-weighted root-mean-square error (RMSE).
As a baseline, we use the ResNet architecture [42] introduced by Rasp and Thuerey [80], which currently reports the best results on WeatherBench.
This architecture consists of 19 residual blocks each with two [ 3 × 3 convolution → LeakyReLU → batchnorm → dropout] layers, plus an initial 7 × 7 convolution layer.
All convolutions but the last have 128 filters.
We consider three additional baselines.
The first is identical to the above, but with twice as many filters (256) in each convolution.
Second, we replace 3 × 3 convolutions with LRLCN [30] layers.
Finally, we use a four-layer ViT [26] with patch size 2 × 2 , hidden dimension 1024, and eight heads (the best performing configuration).
We adapt the Rasp and Thuerey ResNet to use SM O Es with three configurations: adding an SM O E layer after the first convolution; adding an SM O E layer after the final convolution; and replacing all 3 × 3 convolutions with SM O E layers.
Each SM O E selects the same number of experts as the original layer had filters, and has twice as many experts (i.e., |E| = 256 , E = 128 ).
We also share the tensor routing gate across all SM O E layers with the same number of experts, so its overhead is minimal.
Because the weather data is on a fixed grid with underlying location-dependence (the Earth), we expect SM O Es to convey some benefit by specializing to the characteristics of different regions.
In
Table 3, we observe that this is indeed the case. Adding SM O Es improves results in all situations, with the most significant improvement coming through replacing all 3 × 3 convolutions with SM O Es.
This showcases the advantage of incorporating appropriate location-dependent biases.
Wider ResNets [Table] offer limited improvement (in line with results reported by Rasp and Thuerey [80]).
The locationdependent filters of LRLCNs improve over ResNets, but fail to match SM O Es.
We were unable to achieve good performance with ViTs [Table] but did observe that they are highly sensitive to patch size.
Incorporating prior knowledge into gates.
While the exact nature of the location-dependence of this data is unknown, we do have a broad prior on some aspects of it, such as whether a point is land or sea.
This information can be incorporated into an SM O E by initializing the tensor routing gate to bias routing to different experts.
To this end, we use the land-sea mask from ERA5 to initialize the gate to route land locations to half the experts and sea locations to the other half.
Note this does not fix the routing, as the gate is able to adjust as it learns.
Further, the land-sea mask is already included in the input data, so all models already had access to this information.
Results with this are in the “ + gate prior” line of Table 3, and perform best.
This configuration sets a new state-of-the-art for WeatherBench when not using additional data.
Indeed, it nearly matches the performance of a ResNet with 150 years of additional pretraining data from climate simulations [80].
We also tried a configuration where the gate was initialized randomly and fixed rather than learned (“rand fixed gate init”).
This performs worse than our baseline, as the network cannot adapt its routing choices, and each expert sees even fewer points in each sample than a standard network, resulting in less learning.
Thus, learning the routing function is critically important to good performance. Additional data.
Following Rasp and Thuerey [80], we use 150 years of data from the MPI-ESSMHR climate model from the CMIP6 archive [32] to pretrain our best SM O E configuration, which was then fine-tuned on ERA5 data as above. This significantly outperforms both our SM O Es without pretraining and Rasp and Thuerey’s pretrained ResNet. We incorporated more data to further push the performance by adding ERA5 data from the most recent back extension (1959–1979), increasing the dataset size by about 50%. This shows improved results; however, we suspect performance is saturating due to the coarse spatial resolution of the data.
We therefore trained a final configuration with higher resolution ( 1 . 4 ◦ ) data.
Using this, our SM O Es significantly outperform the state-of-the-art on WeatherBench ; indeed, its performance on T850 is very close to that of the operational Integrated
Forecast System [78].
Our results are also competitive with those of Keisler [53], although they are not directly comparable (due to, e.g., different data resolutions).
Mode collapse. Many MoEs suffer from expert or mode collapse (e.g., [10, 82, 86]), where only a small number of experts are selected.
This is typically avoided with routing noise and/or auxiliary “load balance” losses.
On the heat diffusion dataset, we found these losses to offer no benefit (§C).
We also did not observe mode collapse in SM O Es on WeatherBench.
With the RC loss, we directly train the gate, updating routing weights toward other experts after mistakes, and so avoid such issues.
Expert selection order.
During training, the order experts are concatenated may change (due to changes in relative routing scores, or selecting different experts), which will impact the order of channels seen by subsequent layers.
When training on WeatherBench, we found this not to have a significant impact: expert order stabilizes early, allowing layers to operate on stable representations.
Further, most “swapping” occurs among low-confidence experts, so is limited to a subset of channels. 3.3 Post-Processing Ensemble Weather Forecasts
Numerical weather prediction systems typically utilize ensembles of simulations in order to quantify uncertainty and improve forecast quality [14].
However, such ensembles typically exhibit systematic biases [92], and correcting them improves forecast skill [14, 85, 101], a task for which deep learning has shown promise [38, 79].
We use the ENS-10 dataset [8], which consists of twenty years (1998–
2017) of global reforecast [40] data at 0 .
5 ◦ spatial resolution. We follow the benchmarking setup of Ashkboos et al. [8], and correct predictions for Z500, T850, and 2 meter temperature (T2m) at ahour lead-time using both five and ten ensemble members.
We report results using continuous ranked probability score (CRPS) and extreme event weighted CRPS (EECRPS).
We adapt the U-Net model from the ENS-10 baselines, as it delivers good performance and operates on global data (other methods use patches).
Similar to our approach for WeatherBench, we replace each 3 × 3 convolution with an SM O E with four times as many experts as the original layer, and select the same number of experts as the original layer had filters.
We share tensor routing gates between all layers with the same spatial dimensions and number of experts, with the exception that the encoder and decoder trunks also use separate gates.
As baselines, we use the original U-Net architecture and
Ensemble Model Output Statistics (EMOS) [36], a standard post-processing method.
We observe in Table 5 that, similar to WeatherBench, SM O Es offer significant improvements in forecast skill across all situations, and set a new state-of-the-art for prediction correction on the
ENS-10 dataset. This also demonstrates that SM O Es are able to scale to the very large spatial domain used by the ENS-10 data and still learn the appropriate location dependence. 3.4 Image Classification Lastly, we present results on several image classification tasks; we focus here on ImageNet-1k [24] and discuss results on additional datasets in §D. While these datasets do not have a strict locationdependent structure, relaxing the strict translation equivariance of convolutions can bring benefits, and enables a direct comparison with Elsayed et al.
We follow their experimental methodology and train using the recipe of Vryniotis [94].
We either insert an SM O E layer after the first or last convolutional layer of ResNet-50 [42] or replace all 3 × 3 convolutions with SM O E layers.
Our
SM O Es have twice as many experts as the original convolution layer and select half of them, to keep output dimensions constant.
Gating layers are shared among all equally-sized blocks.
For comparison, we also train ResNet-50 with all 3 × 3 convolutions replaced by LRLCN [30] layers; and a Wide ResNet-50-2 [103], which has comparable parameters to SM O Es.
Table 4 shows that SM O Es outperform LRLCNs when we replace all 3 × 3 convolutions, while using 56% of the parameters.
However, a wide ResNet performs best overall.
Nevertheless, this shows that
ImageNet classification does indeed benefit from relaxing translation equivariance.
Discussion
We presented the Spatial Mixture-of-Experts layer, a novel layer that learns underlying location dependencies in data and then uses fine-grained routing to specialize experts to different areas.
We also introduce a routing classification loss and expert error damping, which enable SM O Es to perform well on dense regression tasks.
Prior work shows limited effectiveness on these tasks: Either it does not capture location-dependence (e.g., convolutions) or it operates at a coarse-grained level (e.g., standard MoEs).
By overcoming these challenges, we show a new capability for neural networks, and set new state-of-the-arts for medium-range weather prediction and ensemble post-processing.
Many other problems of broad societal import have a similar spatial structure, particularly in scientific domains [9], and we expect SM O Es to be applicable to them.
However, tasks such as facial recognition and surveillance have also historically shown benefit from such improvements [91] and
SM O Es should therefore be used with care.
SM O Es show that learning location-dependence is a powerful inductive bias for certain types of data, and there are many avenues for further study.
Two key areas of particular interest are to develop improved implementations for fine-grained, sparse routing; and to generalize SM O Es from operating on grids to general graphs, which would enable them to be applied to many additional tasks.
Acknowledgements and Disclosure of Funding
We thank the members of SPCL at ETH Zürich , and Peter Dueben and Mat Chantry of ECMWF, for helpful discussions; and the anonymous reviewers for their suggestions and feedback.
This work has received funding from the European High-Performance Computing Joint Undertaking (JU) under grant agreement No.(MAELSTROM), and from Huawei.
N.D. received support from the ETH Postdoctoral Fellowship. We thank the Swiss National Supercomputing Center (CSCS) and Livermore Computing for computing infrastructure. A Training Details Here we provide additional details on the training setups for experiments in §3.
A.1 Medium-Range Weather Prediction
We follow the training setup of Rasp and Thuerey [80].
We use a batch size of 64 , the Adam [54] optimizer with an initial learning rate of of 0 .
001 , which we divide by a factor of 10 if the validation loss has not improved for two epochs to a minimum learning rate of 1e-6, and early stopping if the validation loss does not improve for five epochs.
Data consists of geoptential, temperature, the u - v component of wind, specific humidity, top-ofatmosphere incident solar radiation, 2-meter temperature, 6-hourly accumulated precipitation, a land-sea mask, orography, and the latitude/longitude.
Multi-level variables are given at seven vertical levels (50, 250, 500, 600, 700, 800, and 925 hPa ).
We use three timesteps as input context, consisting of ( t − 12 , t − 6 , t − 0) hours.
Data are concatenated together channel-wise to form network input.
A.2 Post-Processing Ensemble Weather Forecasts
We follow the training setup of Ashkboos et al.
All models were trained for ten epochs with
Adam [54] with a learning rate of 10 − 5 and a batch size of 8 for the U-Net and SM O E, and batch size 1 for EMOS.
The ENS-10 data consists of temperature, geopotential, specific humidity, vertical velocity, divergence, and the u and v wind components at eleven vertical levels (10, 50, 100, 200, 300, 400, 500, 700, 850, 925, and 1000 hPa ); and the sea surface temperature, total column water, total column water vapor, convective precipitation, mean sea level pressure, total cloud cover, 10 m u and v wind components, 2 m temperature, total precipitation, and skin temperature at surface on a single surface level.
The ground truth data used is ERA5 data specified similarly to the ENS-10 reforecast data.
A.3 Image Classification
Our ResNet training recipe is adapted directly from that of Vryniotis [94].
We use a batch size ofper GPU (and a total batch size of 8192) and trained for 600 epochs using the SGD optimizer with a learning rate of 0.5 (and a linear warmup over five epochs) and momentum (factor 0.9), a cosine annealing learning rate schedule, weight decay factor 2e-5, and elastic model averaging.
B Routing Challenges
We have empirically observed that, without using the routing classification loss (§2.2) and instead training a gate and experts with the same loss, good gating functions are challenging to learn, particularly for regression tasks.
We hypothesize that this is due to a gradient “mismatch”, where gradients are informative for experts but not the gate.
Here we first present a simple ablation that gives some evidence that this is the case, then discuss a possible explanation.
In Table B.1, we show results for training an SM O E on the heat diffusion task, with a setup identical to that of §3.1, but without the RC loss or expert error damping, when initializing the gate and/or experts to be either random or to a perfect, correct initialization.
(Note that such an initialization is
[Table]
[Table]
[Table]
known because of how the heat diffusion dataset is generated.)
We can see that a random initialization for both does not perform well, while a perfect initialization achieves perfect accuracy.
However, a perfect initialization of the experts alone does not result in good performance.
Indeed, freezing expert weights at their perfect initialization performs worse , as the gate is unable to learn to route each location to the correct expert.
Initializing the gate perfectly results in better performance, but with continued training, the quality of the gate degrades; if the gate is instead frozen, the SM O E easily converges to perfect accuracy.
We thus see that the gating function appears to be harder to learn and that when training end-to-end with a single loss, the gradients result in bad gate updates.
We hypothesize that this occurs because the gate is attempting to learn a classification task (“which expert(s) should be selected at a point?”), but the experts are learning a regression task with meansquare error.
In such a setting, the sign of a gradient is not informative about whether a routing decision was correct, as there is no thresholding for the experts, but there is for the gate (due to the top- E routing).
Hence, training an SM O E with a single loss is likely to lead to poor performance.
C Additional SM O E Ablation Studies
Here we present additional ablations on SM O E configurations.
All results use the standard configuration in §3 except where noted.
We also tried gating functions other than tensor routing, but did not see improved performance.
Routing normalization.
We compare different approaches for normalizing the gating function (i.e., normalizing g ( x ) , see §2.1) in Table C.1.
We use no normalization, as that is both simplest and performs the best.
Auxiliary losses.
We compare different MoE auxiliary routing losses, plus using routing noise, in Table C.2.
We define these auxiliary losses precisely in §C.1.
We can see that auxiliary losses neither help nor hurt SM O E performance; however, adding noise results in significant performance degradation.
In Table C.3, we show SM O E training with different auxiliary losses and routing noise when not using the RC loss and expert error damping.
Auxiliary losses in this setting offer no improvement over baseline performance, showing they cannot replace the RC loss.
Expert function.
We compare between using standard convolution and CoordConv [65] as the
SM O E experts in Table C.4.
Weighted SM O Es.
We compare between weighted and unweighted SM O Es in Table C.5.
Both formulations perform the same, so we prefer the simpler, unweighted version; however, on other tasks, weighted SM O Es may perform better.
[Table]
[Table]
C.1 Auxiliary Losses
Here we describe the auxiliary losses we explored.
The importance and load losses follow the formulation of Riquelme et al.
[82]; the spatial agreement loss is a novel auxiliary loss we explored.
Note that these losses typically aim to enforce a balanced usage of experts; while this may be appropriate for other MoEs, it is not necessarily useful for SM O Es, which may have experts that specialize to rare location types. C.1.1 Importance Loss The importance loss encourages the gate to assign equal importance to each expert, where the importance is the (normalized) routing weight for an expert e over a batch X : [Equation]
Then the importance loss is the square of the coefficient of variation of the expert importances:
[Equation]
C.1.2 Load Loss
The load loss attempts to further encourage balanced usage of experts.
However, as this quantity is not differentiable, we instead use the probability of an expert e being selected if only the routing noise were resampled.
Let T be the threshold above which experts were selected at a point (i.e., the
E th maximum routing score) during the original forward pass.
Then the probability of expert e being above this threshold if we resample the original noise ε to be ε ′ is
[Equation]
We then define the load over a batch X as
[Equation]
and finally the load loss as the squared coefficient of variation:
[Equation]
[Table]
C.1.3 Spatial Agreement Loss
We introduce the spatial agreement loss, which is conceptually similar to the above losses, to encourage the gate to select the same experts at a given location across samples in a batch.
This loss, L SA , is the standard deviation of the routing weights for each expert at each point, averaged across each point, and then summed over experts.
We considered using the coefficient of variation rather than standard deviation for this, but found that the mean was often very close to zero, making optimization challenging.
C.1.4 Final Auxiliary Loss
We weight each used auxiliary loss equally, then add them to the final network loss, scaled by 0 .
01 , as done in Riquelme et al.
We did not find the final performance to be sensitive to the choice of scaling factor.
D Additional Image Classification Results
We report image classification results for SM O Es on two additional tasks, MNIST [58] (Table D.1) and CIFAR10 [55] (Table D.2).
We follow the experimental setup of Elsayed et al.
[30] for these
[Table]
[Table]
datasets, and use a network of three convolution layers, 64 channels per layer, and 3 × 3 filters, with batch normalization and ReLU activations.
The final classification layer consists of global average pooling followed by a linear layer.
Models used a mini-batch size of 512 and otherwise followed our standard training setup.
For our SM O E, we replaced all convolution layers with SM O Es with shared gates and 128 experts per layer (selecting 64).
For the LRLCN, we replaced all layers with LRLCNs with spatial rank 4, which we found to perform best.
The LCN network consisted of two convolutions followed by a third
LCN layer, which performed best in Elsayed et al.