SlowGuess/NeurIPS_2023_OCR huggingface dataset:
In distribution alignment, it is a common practice to directly leverage the ground-truth data samples by introducing a regularizer term in the optimization function. To encourage the diversity of latent dynamics after alignment, here we further compute and penalize the Sinkhorn Divergence [43] between the latent dynamics samples of source domain  $\mathbf{Z}^{(s)}\sim q(\cdot \mid \mathbf{X}^{(s)};\phi_s)$  and that of target domain  $\mathbf{Z}^{(t)}\sim q(\cdot \mid \mathbf{X}^{(t)};\phi)$ :
$$
\min  _ {\gamma} \langle \gamma , \mathbf {C} \rangle_ {F} + \lambda \mathbb {H} (\gamma), \tag {13}
$$
where each value  $\mathbf{C}[i][j] = \left\| \mathbf{Z}_i^{(s)} - \mathbf{Z}_j^{(t)}\right\|_2^2$  in matrix  $\mathbf{C}$  denotes the squared Euclidean cost to move a probability mass from  $\mathbf{Z}_i^{(s)}$  to  $\mathbf{Z}_j^{(t)}$ , and  $\mathbb{H}(\gamma)$  computes the entropy of transport plan  $\gamma$ . The total loss for distribution alignment is composed of the term in (13) and the latter two terms on the right side of (12). We note that the total loss is minimized only with respect to the probabilistic encoder parameter set  $\phi$ . (see Appendix C for the total loss formula and the detailed algorithm of ERDiff.)
Datasets. We first train and evaluate ERDiff with a synthetic dataset. Then we apply ERDiff to a non-human primate (NHP) dataset with neural recordings from the primary motor cortex (M1), in which the primates are performing a center-out reaching task in 8 different directions. The NHP dataset contains rich cross-day and inter-subject settings that provide us with an ideal test bed.
Baselines for comparison. We compare ERDiff against the following two strong baselines proposed for the neural distribution alignment task:
- JSDM [24]: a metric-based method that leverages discrete samples from both the source and target domains. The alignment is performed through the symmetric Jensen-Shannon divergence [44].
- Cycle-GAN [21]: a state-of-the-art GAN-based method that uses cycle-consistent adversarial networks to align the distributions of latent dynamics.
Considering the neural observations and latent dynamics are in the format of multi-variate time series, we also compare ERDiff with the following methods aiming at distribution alignment for general time series data:
- SASA [45]: a metric-based distribution alignment method for time series data regression task through the extraction of domain-invariant representation.
- DANN [46]: an adversarial learning framework in which a domain classifier is followed by a feature extractor through a gradient reversal layer. This layer adjusts the gradient by multiplying it with a predefined negative constant during the training process.
- RDA-MMD [47]: a distribution alignment method via minimizing MMD Loss between the latent dynamics extracted from LSTM.
- DAF [48]: an adversarial learning framework that uses a transformer-based shared module with a domain discriminator. During the adaptation step, the domain-invariant features are invariant (Q, K of self-attention); the domain-specific features (V of self-attention) keep tuning.
Data synthesis and evaluation metrics. We first generate a simulated latent dynamics dataset to illustrate the effect of our ERDiff method on spatio-temporal structure-preserving and distribution alignment performance. In this setting, we consider modeling the nonlinear latent dynamics to follow conditionally Continuous Bernoulli (CB) [49] distribution. For each single-trial latent dynamics, we generate 2-dimensional latent variables  $\mathbf{Z} = \{\mathbf{z}_{1:L}\}$  and their 32-dimensional observations  $\mathbf{X} = \{\mathbf{x}_{1:L}\}$ , where  $L = 32$ . We use the following synthesis process and parameter settings to generate samples for the source and target domains, respectively:
$$
p \left(\mathbf {z} _ {l + 1} ^ {(s)} \mid \mathbf {z} _ {l} ^ {(s)}\right) = \prod_ {d} \mathcal {C B} \left(\mathbf {z} _ {l + 1, d} ^ {(s)} \mid \mathbf {W} ^ {(s)} \tanh (\mathbf {z} _ {l, d} ^ {(s)})\right), \quad p \left(\mathbf {x} _ {l} ^ {(s)} \mid \mathbf {z} _ {l} ^ {(s)}\right) = \mathcal {N} \left(\mathbf {x} _ {l} ^ {(s)} \mid \mathbf {R} ^ {(s)} \mathbf {z} _ {l} ^ {(s)}, \mathbf {K}\right),
$$
$$
p \left(\mathbf {z} _ {l + 1} ^ {(t)} \mid \mathbf {z} _ {l} ^ {(t)}\right) = \prod_ {d} \mathcal {C B} \left(\mathbf {z} _ {l + 1, d} ^ {(t)} \mid \mathbf {W} ^ {(t)} \operatorname {t a n h} \left(\mathbf {z} _ {l, d} ^ {(t)}\right)\right), \quad p \left(\mathbf {x} _ {l} ^ {(t)} \mid \mathbf {z} _ {l} ^ {(t)}\right) = \mathcal {N} \left(\mathbf {x} _ {l} ^ {(t)} \mid \mathbf {R} ^ {(t)} \mathbf {z} _ {l} ^ {(t)}, \mathbf {K}\right), \tag {14}
$$
where  $l \in \{1, \dots, L\}$ , and  $\{\mathbf{W}^{(s)}, \mathbf{R}^{(s)}\}, \{\mathbf{W}^{(t)}, \mathbf{R}^{(t)}\}$  are the specific parameter sets of the source and target domains. To compare and evaluate the latent dynamics alignment performance, we estimate the trial-average log density of the aligned latent dynamics evaluated at the optimal generation
Figure 3: Experimental results on the synthetic dataset. (A) Performance comparison on trial-average negative log-likelihood (NLL) and KL Divergence (KLD).  $\downarrow$  means the lower the better. ERDiff achieves the second-lowest NLL and the lowest KLD. (B) True continuous Bernoulli dynamics in the source domain compared to the latent dynamics aligned by ERDiff and JSDM in the target domain (blue dots denote the fixed points). ERDiff preserves the spatio-temporal structure of latent dynamics much better.
distribution:  $1 / L\sum_{l = 0}^{L - 1}\log q^{*}\left(\mathbf{z}_{l}^{(t)}\right)$ , and the trial-averaged KL Divergence to the optimal latent dynamics distribution:  $1 / L\sum_{l = 0}^{L - 1}\mathbb{D}_{\mathrm{KL}}\left(p_{\phi^{*}}(\mathbf{z}_{l + 1}^{(t)}\mid \mathbf{z}_{l}^{(t)})\| p_{\phi^{(t)}}(\mathbf{z}_{l + 1}^{(t)}\mid \mathbf{z}_{l}^{(t)})\right)$ .
Results on synthetic dataset. We repeat the simulation experiment five times and report the mean and standard deviation of each method in the above two quantitative evaluation metrics, shown in Figure 3(A). We observe that ERDiff achieves higher alignment performance on both two evaluation metrics compared to baseline methods. For further analysis, we plot the phase portrait of the true source domain and those inferred by ERDiff and JSDM in Figure 3(B). Compared to JSDM, ERDiff can extract and recover the spatio-temporal structure of the synthetic latent dynamics more precisely and be much closer to the ground truth. These results mainly due to the fact that ERDiff obtains structure-aware alignment signals from the DM while JSDM neglects this structural information.
4.2 Neural datasets
We conduct extensive experiments on two real-world neural datasets: the non-human-primate (NHP) primary motor cortex (M1) [8] and Rat hippocampal CA1 [27]. Experiments on these two datasets use a nearly identical setup. Here we primarily discuss the experimental approach and results related to the NHP motor cortex dataset. (See Appendix D for the detailed results on the rat hippocampal CA1 dataset.)
Motor cortex dataset description. We conduct experiments with datasets collected from the primary motor cortex (M1) of two non-human primates ('C' & 'M') [8]. The primates have been trained to reach one of eight targets at different angles (Figure 4A). Neural recordings from these two primates have been widely studied [20, 50]. During such a process, their neural spike activities (signals) in the primary motor cortex (M1) along with the reaching behavior velocity were recorded. They performed the center-out reaching task multiple times in each direction and only successful trials were saved. For our experimental evaluation purpose, we select the trials from three recording sessions for each primate per day. In total, we have 3 days for each primate. We will perform cross-day (recordings of the same primate performing the task on different days) and inter-subject (recordings of different primates) experiments.
Data processing and evaluation metrics. The neural recordings of each day and each primate consist of about 180-220 trials across 3 sessions. For each trial, about 200 neurons are recorded and the number of time bins is 39 with 20ms intervals. We also bin the velocity of the primate's behavior into 39 bins. Therefore, we have time-aligned neural data and behavioral data. When training with the source data, we optimize the VAE model together with the DM. One thing we need to emphasize here is that we also include a velocity-decoding loss to the VAE loss. The decoder maps the neural latent to the velocity values, which is a ridge regression model. Therefore, the inferred latent contains a rich amount of velocity information. During testing, we align the test neural data to the training neural data so that we can directly apply the velocity decoder to the latent in the test data without performance degradation. In the training session, the ratio of training and validation set is split as  $80\%$ : $20\%$  through 5-fold cross-validation. The post-processed dataset of primate 'C' contains 586 trials in total while that of primate 'M' contains 632 trials. For the evaluation protocol, since
JSDM
$R^2 = -0.032$
Figure 4: Motor cortex dataset and experimental results. (A) Illustration of the center-out reaching task of non-human primates. (B) The 3D visualization of trial-averaged latent dynamics corresponding to each reaching direction in the source domain. (C) The 3D visualization of trial-averaged latent dynamics corresponding to each reaching direction aligned by ERDiff, DAF, and JSDM given the target distribution from cross-day and inter-subject settings. We observe that ERDiff preserves the spatio-temporal structure of latent dynamics well.
$R^2 = 0.062$
the ground-truth source domain distribution of latent dynamics is inaccessible, we use the behavior decoding performance to evaluate the performance of latent dynamics alignment. Here we compare the true behavior velocity with the decoded one in the test data using coefficient of determination values  $(R^2$ , in  $\%)$  and root-mean-square error (RMSE). To verify the generalization of each method in latent dynamics alignment, we make full use of the dataset collected in chronological order. We perform 6 sets of cross-day experiments and 10 sets of inter-subject experiments, all repeated over 5 different random seeds.
Experimental setup. The VAE is based on a sequential architecture [51], in which recurrent units are applied in both the probabilistic encoder and decoder. We also add domain knowledge of our alignment task into the model structure: a behavior regression decoder is cooperatively trained from the latent dynamics so that the behavior semantics information is complementarily provided during the neural manifold learning. Poisson negative log-likelihood loss is used for firing rate reconstruction and mean squared error is used for behavior regression. We use the Adam Optimizer [52] for optimization and the learning rate is chosen among  $\{0.005, 0.01\}$ . The batch size is uniformly set as 64. Despite the varying size of the input dimension (due to the varying number of recorded neurons in different sessions), the latent space dimension size is set as 8 for all the methods for a fair comparison. We use the dropout technique [53] and the ELU activation function [54] between layers in our probabilistic encoder and decoder architectures. During latent dynamics alignment, we perform linear probing only on the read-in layer of the probabilistic encoder while keeping the remaining layers fixed.
Neural manifold analysis. Considering the interpretability [50] and strong latent semantics contained in neural manifold [8], we conduct a case study based on the visualization of neural manifolds to verify the spatio-temporal structure preserving capability and alignment performance of ERDiff. In Figure 4(B), we plot the averaged latent dynamics of each direction in the source domain, which is based on one recording on primate 'C' using demixed Principle Component Analysis (dPCA) [55]. The parameters of dPCA fit with the source-domain latent dynamics while being fixed when applied to perform the transformation in the target domain. In Figure 4(C), we plot the averaged latent dynamics of each direction aligned by ERDiff and two representative baseline methods (DAF and JSDM) under both cross-day and inter-subject settings.
Under both experimental settings, the overall observation is that the spatio-temporal structure of the aligned results of ERDiff is much more coherent with that of the source domain. The results of DAF and JSDM roughly recover the direction of dynamics but fail to preserve the spatio-temporal
(A) Source
ERDiff (Ours)
JSDM
(B) Sampling Density
Figure 5: (A) True source-domain trial velocities and behavior decoding trajectories inferred from a ridge regression model given the latent dynamics aligned by ERDiff and JSDM, respectively. We can observe that ERDiff not only preserves the spatio-temporal structure but also decodes the direction more accurately. (B) We compare the decoding performance of ERDiff, DAF, and JSDM with a decrease in the sampling density of trials on the target domain. We can observe that ERDiff maintains a relatively high accuracy under low sampling densities.
Table 1: The R-squared values  $(R^2$ , in %) and RMSE of the methods on the motor cortex dataset. ERDiff w/o S is short for a variant of our proposed method that removes the spatial transformer layer in the DM. ERDiff w/o T is short for a variant of our proposed method that removes the temporal transformer layer in the DM. The boldface denotes the highest score. Each experiment condition is repeated with 5 runs, and their mean and standard deviation are listed.
Method	Cross-Day	Inter-Subject
R2(%) ↑	RMSE ↓	R2(%) ↑	RMSE ↓
Cycle-GAN	-24.83 (±3.91)	11.28 (±0.44)	-25.47 (±3.87)	12.23 (±0.46)
JSDM	-17.36 (±2.57)	9.01 (±0.38)	-19.59 (±2.77)	11.55 (±0.52)
SASA	-12.66 (±2.40)	8.36 (±0.32)	-14.33 (±3.05)	10.62 (±0.40)
DANN	-12.57 (±3.28)	8.28 (±0.32)	-18.37 (±3.24)	10.66 (±0.57)
RDA-MMD	-9.96 (±2.63)	8.51 (±0.31)	-6.31 (±2.19)	10.29 (±0.42)
DAF	-6.37 (±3.72)	8.17 (±0.48)	-11.26 (±3.64)	9.57(±0.58)
ERDiff w/o S	-12.69 (±2.64)	8.57 (±0.50)	-14.60 (±2.88)	10.85 (±0.57)
ERDiff w/o T	-14.61 (±2.33)	8.93 (±0.50)	-17.10 (±3.23)	10.94 (±0.59)
ERDiff (Ours)	18.81(±2.24)	7.99(±0.43)	10.29(±2.86)	9.78(±0.50)
structure tightly. That is because JSDM neglects the spatio-temporal structure during alignment and it is difficult for adversarial networks to capture such structure implicitly in DAF. Additionally, the averaged latent dynamics of each direction are much more clearly separated through ERDiff. We owe this outcome to the fact that providing extra guidance on the spatio-temporal structure would also facilitate the model to align directions properly. Additionally, without any mean offset alignment, the starting points (from the bottom center) and ending points of latent dynamics are also aligned well with the source domain, further verifying the structure recovering ability of ERDiff.
Decoding performance comparison. Table 1 shows a comparison of the r-squared value  $(R^2)$  and average RMSE on both the cross-day and inter-subject settings. While Figure 5(A) depicted the decoded velocity trajectories of a subset of trials on the cross-day setting given the method. We have the following observations: (1) Compared to traditional alignment methods specially designed for neural data, deep learning-based methods additionally model the sequential information of the latent dynamics, thus achieving better alignment results, which reflects the importance of spatio-temporal structure modeling. In most cases, ERDiff achieves the highest decoding accuracy and alignment performance among all methods. (2) From the ablation study shown at the bottom of Table 1, we find that both the Spatial Transformer layer and Temporal Transformer layer are key components in ERDiff, verifying the effectiveness of spatio-temporal structure modeling. (3) As shown in Figure 5(A), the spatio-temporal structure of the latent dynamics is well-preserved in the result of ERDiff. Compared to baselines, the smoothness and continuity of the trajectory decoded by ERDiff are also more satisfying.
Impact of sampling density in the target domain. We verify the consistent performance of ERDiff in few-shot target-sample circumstances. In Figure 5(B), we analyze the impact of the sampling density of the target domain on decoding performance. The setting is that we sample a portion
of target-domain data to learn the alignment and apply the alignment to the entire target domain. Despite the sampling density drops from  $50\%$  to  $10\%$ , our results demonstrate that ERDiff continues to produce fairly consistent decoding accuracy with a small drop. This result validates our argument that ERDiff both preserves the dynamics structure underlying neural activities and maintains the characteristics of the target domain. In comparison, the performance of baseline methods shrinks drastically because they lack prior knowledge of the spatio-temporal structure.
We can conclude that the DM in ERDiff is capable of extracting the spatio-temporal structure in the source domain latent dynamics, providing a valuable inductive bias in recovering such structure during distribution alignment.
In this work, we propose a new method named ERDiff, for solving the neural distribution alignment issue in real-world neuroscience applications (e.g., brain-computer interfaces). Firstly, with the source domain, we propose to use a diffusion model to extract the spatio-temporal structure within the latent dynamics of trials. Next, in the alignment phase with the target domain, the spatio-temporal structure of latent dynamics is recovered through the maximum likelihood alignment based on the diffusion model. Experimental results on synthetic and real-world motor cortex datasets verify the effectiveness of ERDiff in the enhancement of long-term robustness and behavior decoding performance from neural latent dynamics.
To be in line with the conventions of previous studies on neural distribution alignment [4, 16], the behavioral (velocity) signals of the source domain are present during the VAE training. These signals do help in learning a more interpretable neural latent space. However, we emphasize that ERDiff does not incorporate any behavioral signals of the target domain during the distribution alignment phase. Hence, ERDiff is entirely an unsupervised neural distribution alignment (i.e., test-time adaptation) method. As for the computational cost analysis, In the source domain training phase, the additional computation cost of ERDiff primarily comes from the diffusion model (DM) training. We note that the DM is trained in the latent space  $\mathbf{Z}$ , which is significantly lower in dimensionality than the raw neural spiking signal space  $\mathbf{X}$ . Therefore, the computational overhead of this one-time training phase is acceptable, especially given that it can be conducted offline in real-world BCI applications. In the alignment phase, we would like to emphasize that ERDiff maintains a comparable computational cost with baseline methods. Please refer to Appendix E for a comprehensive analysis of ERDiff's computational cost and time complexity.
Limitation and future work. (1) Currently, ERDiff can align well with a single source domain neural latent distribution. An intriguing direction for future work would be learning a unified latent space across multiple source domains using the diffusion model. Thus the method would be applicable to domain generalization problems. (2) Generalization on alternative latent variable models (LVM). In this paper, ERDiff identifies the latent variables of raw neural spiking signals with a canonical version of VAE. However, the architecture of the LVM within ERDiff is actually disentangled from the diffusion model training or MLA procedure. Future work includes validating ERDiff given more advanced implementations of LVM, e.g., LFADS [56], STNDT [32].
Broader impact. Not confined to practical applications in systems neuroscience, the maximum likelihood alignment (MLA) with diffusion model algorithm proposed in ERDiff has great potential to apply to broader domain adaptation tasks across general time-series datasets (e.g., weather forecasting, and seismology). We also expect that our method can be applied or extended to other real-world scenarios and the broader field of neuroscience/AI.
[1] F. Briggs, G. R. Mangun, and W. M. Usrey, “Attention enhances synaptic efficacy and the signal-to-noise ratio in neural circuits,” Nature, vol. 499, no. 7459, pp. 476–480, 2013.
[2] A. Fourtounas and S. J. Thomas, "Cognitive factors predicting checking, procrastination and other maladaptive behaviours: prospective versus inhibitory intolerance of uncertainty," Journal of Obsessive-Compulsive and Related Disorders, vol. 9, pp. 30-35, 2016.
[3] J. R. Manning, J. Jacobs, I. Fried, and M. J. Kahana, "Broadband shifts in local field potential power spectra are correlated with single-neuron spiking in humans," Journal of Neuroscience, vol. 29, no. 43, pp. 13613-13620, 2009.
Appendix to "Extraction and Recovery of Spatio-Temporal Structure in Latent Dynamics Alignment with Diffusion Model"
A Methodology details
A.1 DM architecture details
We adopt the architecture of DM mainly derived from Diffusion Transformer (DiT) [36]. The canonical DiT architecture is based on techniques like patchify [57] and transformer layer for tokens [58], which are well-suited for image feature extraction. This is because the above techniques focus on local feature extraction and the global feature can also be implicitly captured through the stacking of token-based Transformer layers. However, considering the neural observations and latent dynamics are in the format of multi-variate time series, patchify and local feature extraction loses their semantic meaning. There doesn't exist a theoretical guarantee or bio-plausible observation that adjacent latent dimensions of the data matrix have a stronger connection than far-apart latent dimensions. Thus, directly adopting the traditional DiT architecture into this setting may lead to sub-optimal solutions.
To fully utilize the domain knowledge of our task, we propose to use the Spatio-Temporal Transformer Block (STBlock). Each STBlock is mainly composed of a Spatio Transformer layer followed by a Temporal Transformer layer, which are 1-layer encoders based on multi-head self-attention. Since there exists underlying dependency and structure between latent state dimensions, the Spatio Transformer layer takes latent states of each time bin as inputs to extract their spatial structure. Whereas the Temporal Transformer layer takes the entire latent trajectory of each latent space dimension as inputs to extract its underlying temporal structure. We note that we use the sinusoidal position embeddings [59] to encode the timestep  $t$  (i.e., noise scale) into the deep neural network of DM. In each STBlock, the input sequentially goes through:
- Spatio Transformer: Layer Normalization  $\rightarrow$  Multi-head Self-attention Layer (along time bins)  $\rightarrow$  Point-wise Feed-forward.
- Temporal Transformer: Layer Normalization  $\rightarrow$  Multi-head Self-attention Layer (along latent space dimensions)  $\rightarrow$  Point-wise Feed-forward.
We illustrate the main architecture of DM in Figure 2(A), and implement the DM in Pytorch [60].
A.2 VAE and DM cooperative source domain learning details