\section{Introduction}

Unnormalized probability models have drawn significant attention over the years. These models arise, for example, in energy based models, where the normalization constant is intractable to compute, and are thus relevant to numerous settings. Particularly, they have been extensively used in the context of restricted Boltzmann machines \citep{smolensky1986information,hinton2002training}, deep belief networks \citep{hinton2006fast,salakhutdinov2009deep}, Markov random fields \citep{carreira2005contrastive,hinton2006reducing}, and recently also with deep neural networks \citep{xie2016theory,song2019generative,du2019implicit,grathwohl2019your,nijkamp2019learning}.

Fitting an unnormalized density model to a dataset is challenging due to the missing normalization constant of the distribution. A naive approach is to employ approximate maximum likelihood estimation (MLE). This approach relies on the fact that the likelihood's gradient can be approximated using samples from the model, generated using Markov Chain Monte Carlo (MCMC) techniques. However, a good approximation requires using very long chains and is thus impractical. This difficulty motivated the development of a plethora of more practical approaches, like score matching \citep{hyvarinen2005estimation}, noise contrastive estimation (NCE) \citep{gutmann2010noise}, and conditional NCE (CNCE) \citep{ceylan2018conditional}, which replace the log-likelihood loss with objectives that do not require the computation of the normalization constant or its gradient.

Perhaps the most popular method for learning unnormalized models is contrastive divergence (CD) \citep{hinton2002training}. CD's advantage over MLE stems from its use of short Markov chains initialized at the data samples. CD has been successfully used in a wide range of domains, including modeling images \citep{hinton2006fast}, speech \citep{mohamed2010phone}, documents \citep{hinton2009replicated}, and movie ratings \citep{salakhutdinov2007restricted}, and is continuing to attract significant research attention \citep{liu2017learning,gao2018learning,qiu2019unbiased}.

Despite CD's popularity and empirical success, there still remain open questions regarding its theoretical properties. The primary source of difficulty is an unjustified approximation used to derive its objective's gradient, which biases its update steps \citep{carreira2005contrastive,bengio2009justifying}. The difficulty is exacerbated by the fact that CD's update steps cannot be expressed as the gradients of any fixed objective \citep{tieleman2007some,sutskever2010convergence}.


In this paper, we present an alternative derivation of CD, which relies on completely different principles and requires no approximations. Specifically, we show that CD's update steps are the gradients of an adversarial game in which a discriminator attempts to classify whether a Markov chain generated from the model is presented to it in its original or a time-reversed order (see Fig.~\ref{fig:adverserial_cd}). Thus, our derivation sheds new light on CD's success: Similarly to modern generative adversarial methods \citep{goodfellow2014generative}, CD's discrimination task becomes more challenging as the model approaches the true distribution. This keeps the update steps effective throughout the entire training process and prevents early saturation as often happens in non-adaptive methods like NCE and CNCE. In fact, we derive CD as a natural extension of the CNCE method, replacing the fixed distribution of the contrastive examples with an adversarial adaptive distribution. 

\begin{figure}[t]
    \centering
    \includegraphics[width=\textwidth]{adverserial_cd.pdf}
    \caption{
        Contrastive divergence as an adversarial process. In the first step, the distribution model is used to generate an MCMC process which is used to generate a chain of samples. In the second step the distribution model is updated using a gradient descent step, using the MCMC transition rule.
    }
    \label{fig:adverserial_cd}
\end{figure}

CD requires that the underlying MCMC be exact, which is not the case for popular methods like Langevin dynamics. This commonly requires using Metropolis-Hastings (MH) rejection, which ignores some of the generated samples. Interestingly, our derivation reveals an alternative correction method for inexact chains, which does not require rejection.


\section{Background}

\subsection{The Classical Derivation of CD}

Assume we have an unnormalized distribution model $p_\theta$. Given a dataset of samples $\{x_i\}$ independently drawn from some unknown distribution $p$, CD attempts to determine the parameters $\theta$ with which $p_\theta$ best explains the dataset. Rather than using the log-likelihood loss, CD's objective involves distributions of samples along finite Markov chains initialized at~$\{x_i\}$. When based on chains of length $k$, the algorithm is usually referred to as CD-$k$.

Concretely, let $q_\theta(x'|x)$ denote the transition rule of a Markov chain with stationary distribution $p_\theta$, and let $r^m_\theta$ denote the distribution of samples after $m$ steps of the chain. As the Markov chain is initialized from the dataset distribution and converges to $p_\theta$, we have that $r_\theta^0=p$ and $r_\theta^\infty=p_\theta$. The CD algorithm then attempts to minimize the loss
\begin{align}
\label{eq:cd_loss}
\ell_{\text{CD-}k}
&=D_{\mathrm{KL}}(r^0_\theta||r^{\infty}_\theta)-D_{\mathrm{KL}}(r^k_\theta||r^{\infty}_\theta)\nonumber\\ 
&=D_{\mathrm{KL}}(p||p_{\theta})-D_{\mathrm{KL}}(r^{k}_\theta||p_{\theta}),
\end{align}
where $D_{\mathrm{KL}}$ is the Kullback-Leibler divergence. Under mild conditions on $q_\theta$ \citep{cover1994processes} this loss is guaranteed to be positive, and it vanishes when $p_{\theta}=p$ (in which case $r^{k}_\theta=p_\theta$). 

To allow the minimization of (\ref{eq:cd_loss}) using gradient-based methods, one can write
\begin{align}
\label{eq:cd_grad}
\nabla_{\theta}\ell_{\text{CD-}k}=
&\mathbb{E}_{\tilde{X}\sim r^k_{\theta}} [\nabla_{\theta}\log p_{\theta}(\tilde{X})]
-\mathbb{E}_{X\sim p} [\nabla_{\theta}\log p_{\theta}(X)] +\frac{dD_{\mathrm{KL}}(r^k_{\theta}||p_{\theta})}{d r^k_{\theta}}\nabla_{\theta}r^k_{\theta}.
\end{align}
Here, the first two terms can be approximated using two batches of samples, one drawn from $p$ and one from $r^k_\theta$. The third term is the derivative of the loss with respect only to the $\theta$ that appears in $r_{\theta}^k$, ignoring the dependence of $p_{\theta}$ on $\theta$. This is the original notation from \citep{hinton2002training}; an alternative way to write this term would be $\nabla_{\tilde{\theta}}D_{\mathrm{KL}}(r^{k}_{\tilde{\theta}}||p_{\theta})$. This term turns out to be intractable and in the original derivation, it is argued to be small and thus neglected, leading to the approximation
\begin{equation}
\label{eq:cd_grad_approx}
\nabla_{\theta}\ell_{\text{CD-}k}\approx
\frac{1}{n}\sum_i\left(
\nabla_{\theta}\log p_{\theta}(\tilde{x}_i)
-\nabla_{\theta}\log p_{\theta}(x_i)
\right)
\end{equation}
Here $\{x_i\}$ is a batch of $n$ samples from the dataset and~$\{\tilde{x}_i\}$ are $n$ samples generated by applying $k$ MCMC steps to each of the samples in that batch. The intuition behind the resulting algorithm (summarized in App.~\ref{appendix:algo}) is therefore simple. In each gradient step $\theta\leftarrow\theta-\eta\nabla_{\theta}\ell_{\text{CD-}k}$, the log-likelihood of samples from the dataset is increased on the expense of the log-likelihood of the contrastive samples $\{\tilde{x}_i\}$, which are closer to the current learned distribution~$p_\theta$.

Despite the simple intuition, it has been shown that without the third term, CD's update rule (\ref{eq:cd_grad}) generally cannot be the gradient of any fixed objective \citep{tieleman2007some,sutskever2010convergence} except for some very specific cases. For example, \cite{hyvarinen2007connections} has shown that when the Markov chain is based on Langevin dynamics with a step size that approaches zero, the update rule of CD-1 coincides with that of score-matching \cite{hyvarinen2005estimation}. Similarly, the probability flow method of \cite{sohl2011minimum} has been shown to be equivalent to CD with a very unique Markov chain. Here, we show that regardless of the selection of the Markov chain, the update rule is in fact the exact gradient of a particular adversarial objective, which adapts to the current learned model in each step.


\subsection{Conditional Noise Contrastive Estimation}
\label{sec:cnce}

Our derivation views CD as an extension of the CNCE method, which itself is an extension of NCE. We therefore start by briefly reviewing those two methods.

In NCE, the unsupervised density learning problem is transformed into a supervised one. This is done by training a discriminator $D_\theta(x)$ to distinguish between samples drawn from $p$ and samples drawn from some preselected contrastive distribution $p_\text{ref}$. Specifically, let the random variable $Y$ denote the label of the class from which the variable $X$ has been drawn, so that $X|(Y=1)\sim p$ and $X|(Y=0)\sim p_\text{ref}$. Then it is well known that the discriminator minimizing the binary cross-entropy (BCE) loss is given by
\begin{equation}
D_\text{opt}(x)=\mathbb{P}(Y=1|X=x)=\frac{p(x)}{p(x)+p_{\text{ref}}(x)}.
\end{equation}
Therefore, letting our parametric discriminator have the form
\begin{equation}
D_\theta(x)=\frac{p_{\theta}(x)}{p_{\theta}(x)+p_{\text{ref}}(x)},
\end{equation}
and training it with the BCE loss, should in theory lead to $D_\theta(x)=D_\text{opt}(x)$ and thus to $p_\theta(x)=p(x)$. In practice, however, the convergence of NCE highly depends on the selection of $p_{\text{ref}}$. If it significantly deviates from $p$, then the two distributions can be easily discriminated even when the learned distribution $p_{\theta}$ is still very far from~$p$. At this point, the optimization essentially stops updating the model, which can result in a very inaccurate estimate for $p$. In the next section we provide a precise mathematical explanation for this behavior.

The CNCE method attempts to alleviate this problem by drawing the contrastive samples based on the dataset samples. Specifically, each dataset sample $x$ is paired with a contrastive sample~$\tilde{x}$ that is drawn conditioned on $x$ from some predetermined conditional distribution $q(\tilde{x}|x)$ (\emph{e.g.} $\mathcal{N}(x,\sigma^2I)$). The pair is then concatenated in a random order, and a discriminator is trained to predict the correct order. This is illustrated in Fig.~\ref{fig:cnce}. Specifically, here the two classes are of pairs $(A,B)$ corresponding to $(A,B)=(X,\tilde{X})$ for $Y=1$, and $(A,B)=(\tilde{X},X)$ for $Y=0$, and the discriminator minimizing the BCE loss is given by 
\begin{align}
D_\text{opt}(a,b)&=\mathbb{P}(Y=1|A=a,B=b) =\frac{q(b|a)p(a)}{q(b|a)p(a)+q(a|b)p(b)}.
\end{align}
Therefore, constructing a parametric discriminator of the form
\begin{equation}\label{eq:cnce_discriminator}
D_{\theta}(a,b)
=\frac{q(b|a)p_\theta(a)}{q(b|a)p_\theta(a)+q(a|b)p_\theta(b)}
=\left(1+\frac {q(a|b)p_{\theta}(b)}{q(b|a)p_{\theta}(a)}\right)^{-1},
\end{equation}
and training it with the BCE loss, should lead to $p_\theta\propto p$. Note that here $D_{\theta}$ is indifferent to a scaling of $p_{\theta}$, which is thus determined only up to an arbitrary multiplicative constant.

\begin{figure}
    \centering
    \begin{subfigure}[b]{0.5\textwidth}\centering
        \includegraphics[width=0.95\textwidth]{cnce.pdf}
        \caption{CNCE}\label{fig:cnce}
    \end{subfigure
    \begin{subfigure}[b]{0.5\textwidth}\centering
        \includegraphics[width=0.95\textwidth]{cnce_mcmc.pdf}
        \caption{CD-$1$}\label{fig:cnce_mcmc}
    \end{subfigure}
    \caption{\textbf{From CNCE to CD-$1$.} 
        (a) In CNCE, each contrastive sample is generated using a fixed conditional distribution $q(\cdot|\cdot)$ (which usually corresponds to additive noise). The real and fake samples are then concatenated and presented to a discriminator in a random order, which is trained to predict the correct order. (b) CD-$1$ can be viewed as CNCE with a $q(\cdot|\cdot)$ that corresponds to the transition rule of a Markov chain with stationary distribution~$p_\theta$. Since~$q$ depends on $p_\theta$ (hence the subscript $\theta$), during training the distribution of contrastive samples becomes more similar to that of the real samples, making the discrimination task harder.
    }
    \label{fig:cnce_CD1}
\end{figure}

CNCE improves upon NCE, as it allows working with contrastive samples whose distribution is closer to $p$. However, it does not completely eliminate the problem, especially when $p$ exhibits different scales of variation in different directions. This is the case, for example, with natural images, which are known to lie close to a low-dimensional manifold. Indeed if the conditional distribution $q(\cdot|\cdot)$ is chosen to have a small variance, then CNCE fails to capture the global structure of $p$. And if $q(\cdot|\cdot)$ is taken to have a large variance, then CNCE fails to capture the intricate features of $p$ (see Fig.~\ref{fig:toy_experiment}). The latter case can be easily understood in the context of images (see Fig.~\ref{fig:cnce}). Here, the discriminator can easily distinguish which of its pair of input images is the noisy one, without having learned an accurate model for the distribution of natural images (\emph{e.g.,}  simply by comparing their smoothness). When this point is reached, the optimization essentially stops. 

In the next section we show that CD is in fact an adaptive version of CNCE, in which the contrastive distribution is constantly updated in order to keep the discrimination task hard. This explains why CD is less prone to early saturation than NCE and CNCE.

\begin{figure}[tb!]
    \centering
    \begin{subfigure}[t]{0.19\textwidth}
        \centering
        \includegraphics[scale=0.5, trim=0cm -2.8inch 0cm 0cm]{media/spiral_3d.pdf}
        \caption{The toy model}
        \label{fig:toy_model}
    \end{subfigure}
   
    \begin{subfigure}[t]{0.76\textwidth}
        \centering
        \includegraphics[scale=0.5]{media/spiral_cnce_vs_acd.pdf}
        \caption{Comparing CNCE with CD}
        \label{fig:cnce_vs_acd}
    \end{subfigure}
    \caption{
        A toy example illustrating the importance of the adversarial nature of CD. Here, the data lies close to a 2D spiral embedded in a 10-dimensional space. (a)~The training samples in the first~3 dimensions. (b)~Three different approaches for learning the distribution: CNCE with large contrastive variance (top), CNCE with small contrastive variance (middle), and CD based on Langevin dynamics MCMC with the weight adjustment described in Sec.~\ref{sec:ACD} (bottom). As can be seen in the first two columns, CD adapts the contrastive samples according to the data distribution, whereas CNCE does not. Therefore, CNCE with large variance fails to learn the distribution because the vast majority of its contrastive samples are far from the manifold and quickly become irrelevant (as indicated by the weights $\alpha_\theta$ in the third column). And CNCE with small variance fails to learn the global structure of the distribution because its contrastive samples are extremely close to the dataset samples. CD, on the other hand, adjusts the contrastive distribution during training, so as to generate samples that are close to the manifold yet traverse large distances along it.
    }\label{fig:toy_experiment}
\end{figure}


\section{An Alternative Derivation of CD}

We now present our alternative derivation of CD. In Sec.~\ref{sec:decom} we identify a decomposition of the CNCE loss, which reveals the term that is responsible for early saturation. In Sec.~\ref{sec:CD1}, we then present a method for adapting the contrastive distribution in a way that provably keeps this term bounded away from zero. Surprisingly, the resulting update step turns out to precisely match that of CD-$1$, thus providing a new perspective on CD learning. In Sec.~\ref{sec:CDk}, we extend our derivation to include CD-$k$ (with $k\geq1$).

\subsection{Reinterpreting CNCE}
\label{sec:decom}

Let us denote 
\begin{equation}\label{eq:W1}
w_{\theta}(a,b)\triangleq\frac{q(a|b)p_{\theta}(b)}{q(b|a)p_{\theta}(a)},
\end{equation}
so that we can write CNCE's discriminator (\ref{eq:cnce_discriminator}) as
\begin{equation}\label{eq:CNCEdiscrimnator}
D_{\theta}(a,b)=\left(1+w_{\theta}(a,b)\right)^{-1}.
\end{equation}
Then we have the following observation (see proof in App.~\ref{appendix:cnce_grad}).

\begin{observation}
\label{obs:CNCEgrad}
The gradient of the CNCE loss can be expressed as
\begin{align}
\label{eq:cnce_grad}
\nabla_{\theta}\ell_{\text{CNCE}}=\mathbb{E}\!_{\substack{X\sim p \\ \tilde{X}|X\sim q}}\!\left[\alpha_\theta(X,\tilde{X})\left(\nabla_{\theta}\log p_{\theta}(\tilde{X})-\nabla_{\theta}\log p_{\theta}(X)\right)\right],
\end{align}
where
\begin{equation}\label{eq:weight}
\alpha_\theta(x,\tilde{x})\triangleq (1+w_\theta(x,\tilde{x})^{-1})^{-1}.
\end{equation}
\end{observation}

Note that (\ref{eq:cnce_grad}) is similar in nature to the (approximate) gradient of the CD loss~(\ref{eq:cd_grad_approx}). Particularly, as in CD, the term $\nabla_{\theta}\log p_{\theta}(\tilde{X})-\nabla_{\theta}\log p_{\theta}(X)$ causes each gradient step to increase  the log-likelihood of samples from the dataset on the expense of the log-likelihood of the contrastive samples. However, as opposed to CD, here we also have the coefficient $\alpha_{\theta}(x,\tilde{x})$, which assigns a weight between $0$ and $1$ to each pair of samples $(x,\tilde{x})$. To understand its effect, observe that
\begin{equation}
\alpha_\theta(x,\tilde{x})=1-D_\theta(x,\tilde{x})=D_{\theta}(\tilde{x},x).
\end{equation}
Namely, this coefficient is precisely the probability that the discriminator assigns to the incorrect order of the pair. Therefore, this term gives a low weight to ``easy'' pairs (\emph{i.e.,}  for which $D_\theta(x,\tilde{x})$ is close to $1$) and a high weight to ``hard'' ones.

This weighting coefficient is of course essential for ensuring convergence to $p$. For example, it prevents  $\log p_{\theta}$ from diverging to $\pm\infty$ when the discriminator is presented with the same samples over and over again. The problem is that a discriminator can often correctly discriminate all training pairs, even with a $p_\theta$ that is still far from $p$. In such cases, $\alpha_\theta$ becomes practically zero for all pairs and the model stops updating. This shows that a good contrastive distribution is one which keeps the discrimination task hard throughout the training. As we show next, there is a particular choice which provably prevents $\alpha_\theta$ from converging to zero, and that choice results in the CD method.


\subsection{From CNCE to CD-\(1\)}
\label{sec:CD1}

To bound $\alpha_\theta$ away from $0$, and thus avoid the early stopping of the training process, we now extend the original CNCE algorithm by allowing the conditional distribution $q$ to depend on $p_\theta$ (and thus to change from one step to the next). Our next key observation is that in this setting there exists a particular choice that keeps $\alpha_\theta$ constant.

\begin{observation}
If $q$ is chosen to be the transition probability of a reversible Markov chain with stationary distribution $p_\theta$, then
\begin{equation}
\alpha_{\theta}(x,\tilde{x})=\frac{1}{2}, \quad\forall x,\tilde{x}.
\end{equation}
\end{observation}
\begin{proof}
A reversible chain with transition $q$ and stationary distribution $p_\theta$, satisfies the detailed balance property
\begin{equation}\label{eq:detailed_balance}
    q(\tilde{x}|x)p_{\theta}(x)=q(x|\tilde{x})p_{\theta}(\tilde{x}),\quad \forall x,\tilde{x}.
\end{equation}
Substituting (\ref{eq:detailed_balance}) into (\ref{eq:W1}) leads to $w_{\theta}(x,\tilde{x})=1$, which from (\ref{eq:weight}) implies $\alpha_\theta(x,\tilde{x})=\tfrac{1}{2}$.
\end{proof}

This observation directly links CNCE to CD. First, the suggested method for generating the contrastive samples is precisely the one used in CD-$1$. Second, as this choice of $q$ leads to $\alpha_\theta(x,\tilde{x})=\tfrac{1}{2}$, it causes the gradient of the CNCE loss (\ref{eq:cnce_grad}) to become
\begin{equation}
\label{eq:cnce_mcmc_grad_exact}
\nabla_{\theta}\ell_{\text{CNCE}}=\tfrac{1}{2}\mathbb{E}_{\substack{X\sim p \\ \tilde{X}|X\sim q}}
\left[\nabla_{\theta}\log p_{\theta}(\tilde{X})-\nabla_{\theta}\log p_{\theta}(X)\right],
\end{equation}
which is exactly proportional to the CD-$1$ update (\ref{eq:cd_grad_approx}). We have thus obtained an alternative derivation of CD-$1$. Namely, rather than viewing CD-$1$ learning as an \emph{approximate} gradient descent process for the loss (\ref{eq:cd_loss}), we can view each step as the \emph{exact} gradient of the CNCE discrimination loss, where the reference distribution $q$ is adapted to the current learned model $p_\theta$. This is illustrated in Fig.~\ref{fig:cnce_mcmc}.

Since $q$ is chosen based on $p_\theta$, the overall process is in fact an adversarial game. Namely, the optimization alternates between updating $q$, which acts as a generator, and updating $p_{\theta}$, which defines the discriminator. As $p_{\theta}$ approaches $p$, the distribution of samples generated from the MCMC also becomes closer to $p$, which makes the discriminator's task harder and thus prevents early saturation.

It should be noted that formally, since $q$ depends on $p_\theta$, it also indirectly depends on $\theta$, so that a more appropriate notation would be $q_\theta$. However, during the update of $p_{\theta}$ we fix $q_{\theta}$ (and vise versa), so that the gradient in the discriminator update does not consider the dependence of $q_\theta$ on $\theta$. This is why (\ref{eq:cnce_mcmc_grad_exact}) does not involve the gradient of $\tilde{X}$ which depends on $q_{\theta}$. 

The reason for fixing $q_{\theta}$ comes from the adversarial nature of the learning process. Being part of the chain generation process, the goal of the transition rule $q_{\theta}$ is to generate chains that appear to be time-reversible, while the goal of the classifier, which is based on the model $p_{\theta}$, is to correctly classify whether the chains were reversed. Therefore, we do not want the optimization of the classifier to affect~$q_{\theta}$. This is just like in GANs, where the generator and discriminator have different objectives, and so when updating the discriminator the generator is kept fixed.

\begin{comment}
\begin{figure}
    \centering
    \includegraphics[width=0.4\textwidth]{cnce_mcmc.pdf}
    \caption{
        CD-$1$ viewed as CNCE with a single MCMC step. Each contrastive sample is generated by taking a single step in an MCMC process starting with a real sample from dataset. The two samples are then concatenated in a random order, and a discriminator is trained to predict the correct order. As the training advances, the distribution of contrastive samples becomes more similar to that of real samples, and thus the discrimination task becomes harder.
    }
    \label{fig:cnce_mcmc}
\end{figure}
\end{comment}


\subsection{From CD-\(1\) to CD-\(k\)}
\label{sec:CDk}

To extend our derivation to CD-$k$ with an arbitrary $k\geq1$, let us now view the discrimination problem of the previous section as a special case of a more general setting. Specifically, the pairs of samples presented to the discriminator in Sec.~\ref{sec:CD1}, can be viewed as Markov chains of length two (comprising the initial sample from the dataset and one extra generated sample). It is therefore natural to consider also Markov chains of arbitrary lengths. That is, assume we initialize the MCMC at a sample $x_i$ from the dataset and run it for $k$ steps to obtain a sequence $(x^{(0)},x^{(1)},\ldots,x^{(k)})$, where  $x^{(0)}=x_i$. We can then present this sequence to a discriminator either in its original order, or time-reversed, and train the discriminator to classify the correct order. We coin this a \emph{time-reversal classification task}. Interestingly, in this setting, we have the following.

\begin{observation}\label{obv:cdk}
When using a reversible Markov chain of length $k+1$ with stationary distribution $p_\theta$, the gradient of the BCE loss of the time-reversal classification task is given by
\begin{equation}\label{eq:CDkgrad}
\nabla_{\theta}\ell_{\text{CNCE}}=\tfrac{1}{2}\mathbb{E}\left[\nabla_{\theta}\log p_{\theta}(X^{(k)})-\nabla_{\theta}\log p_{\theta}(X^{(0)})\right],
\end{equation}
which is exactly identical to the CD-$k$ update (\ref{eq:cd_grad_approx}) up to a multiplicative factor of $\tfrac{1}{2}$.
\end{observation}

This constitutes an alternative interpretation of CD-$k$. That is, CD-$k$ can be viewed as a time-reversal adversarial game, where in each step, the model $p_\theta$ is updated so as to allow the discriminator to better distinguish MCMC chains from their time-reversed counterparts.

Two remarks are in order. First, it is interesting to note that although the discriminator's task is to classify the order of the whole chain, its optimal strategy is to examine only the endpoints of the chain, $x^{(0)}$ and $x^{(k)}$. Second, it is insightful to recall that the original motivation behind the CD-$k$ loss (\ref{eq:cd_loss}) was that when $p_\theta$ equals~$p$, the marginal probability of each individual step in the chain is also $p$. Our derivation, however, requires more than that. To make the chain indistinguishable from its time-reversed version, the joint probability of all samples in the chain must be invariant to a flip of the order. When $p_\theta=p$, this is indeed the case, due to the detailed balance property (\ref{eq:detailed_balance}).

\begin{proof}[Proof of Observation~\ref{obv:cdk}]
We provide the outline of the proof (see full derivation in App. \ref{appendix:cnce_chain_grad}). Let $(A^{(0)},A^{(1)},\ldots,A^{(k)})$ denote the input to the discriminator and let $Y$ indicate the order of the chain, with $Y=1$ corresponding to $(A^{(0)},A^{(1)},\ldots,A^{(k)})=(X^{(0)},X^{(1)},\ldots,X^{(k)})$ and $Y=0$ to $(A^{(0)},A^{(1)},\ldots,A^{(k)})=(X^{(k)},X^{(k-1)},\ldots,X^{(0)})$. The discriminator that minimizes the BCE loss is now given by
\begin{align}\label{eq:discriminator_long_chain}
D(a_0,a_1,\ldots,a_k)&=\mathbb{P}(Y=1|A^{(0)}=a_0,A^{(1)}=a_1,\ldots,A^{(k)}=a_k) \nonumber\\
&=\left(1+\frac
{q(a_0|a_1)\cdots q(a_{k-1}|a_k)p(a_k)}
{q(a_k|a_{k-1})\cdots q(a_1|a_0)p(a_0)}
\right)^{-1} \nonumber\\
&=\left(1+\prod_{i=1}^k w_{\theta}(a_{i-1},a_i)\right)^{-1}.
\end{align}
The CNCE paradigm thus defines a discriminator $D_\theta$ having the form of (\ref{eq:discriminator_long_chain}) but with $p$ replaced by~$p_\theta$. Recall that despite the dependence of the transition probability~$q$ on the current learned model~$p_\theta$, it is regarded as fixed within each discriminator update step. We therefore omit the subscript $\theta$ from $q$ here. Similarly to the derivation of (\ref{eq:cnce_grad}), explicitly writing the gradient of the BCE loss of our discriminatrion task, gives
\begin{align}
\label{eq:cnce_chain_grad}
\nabla_{\theta}\ell_{\text{chain}}
&=\mathbb{E}
\left[\left(1+\prod_{i=1}^k w_{\theta}(X^{(i-1)},X^{(i)})^{-1}\right)^{-1}\left(\nabla_{\theta}\log p_{\theta}(X^{(k)})-\nabla_{\theta}\log p_{\theta}(X^{(0)})\right)
\right]\nonumber \\
&=\mathbb{E}
\left[\alpha_\theta(X^{(0)},\ldots,X^{(k)})\left(\nabla_{\theta}\log p_{\theta}(X^{(k)})-\nabla_{\theta}\log p_{\theta}(X^{(0)})\right)
\right].
\end{align}
where we now defined
\begin{equation}\label{eq:weight_chain}
\alpha_\theta(a_0,\ldots,a_k)\triangleq \left(1+\prod_{i=1}^k w_{\theta}(a_{i-1},a_i)^{-1}\right)^{-1}.
\end{equation}
Note that (\ref{eq:cnce_grad}) is a special case of (\ref{eq:cnce_chain_grad}) corresponding to $k=1$, where $X$ and $\tilde{X}$ in (\ref{eq:cnce_grad}) are $X^{(0)}$ and $X^{(1)}$ in (\ref{eq:cnce_chain_grad}). As before, when $q$ satisfies the detailed balance property (\ref{eq:detailed_balance}), we obtain $w_{\theta}=1$ and consequently the weighting term $\alpha_\theta$ again equals $\tfrac{1}{2}$. Thus, the gradient (\ref{eq:cnce_chain_grad}) reduces to (\ref{eq:CDkgrad}), which is exactly proportional to the CD-$k$ update (\ref{eq:cd_grad_approx}).
\end{proof}


\subsection{MCMC Processes That do not Have Detailed Balance}
\label{sec:ACD}

In our derivation, we assumed that the MCMC process is reversible, and thus exactly satisfies the detailed balance property (\ref{eq:detailed_balance}). This assumption ensured that $w_{\theta}=1$ and thus $\alpha_\theta=\tfrac{1}{2}$. In practice, however, commonly used MCMC methods satisfy this property only approximately. For example, the popular discrete Langevin dynamics process obeys detailed balance only in the limit where the step size approaches zero. The common approach to overcome this is through Metropolis-Hastings (MH) rejection \citep{hastings1970monte}, which guarantees detailed balance by accepting only a portion of the proposed MCMC transitions. In this approach, the probability of accepting a transition from $x$ to $\tilde{x}$ is closely related to the weighing term $w_{\theta}$, and is given by
\begin{equation}
A(x,\tilde{x})=\min\left(1,w_{\theta}(x,\tilde{x})\right).
\end{equation}
Interestingly, our derivation reveals an alternative method for accounting for lack of detailed balance.

Concretely, we saw that the general expression  for the gradient of the BCE loss (before assuming detailed balance) is given by (\ref{eq:cnce_chain_grad}). This expression differs from the original update step of CD-$k$ only in the weighting term $\alpha_\theta(x^{(0)},\ldots,x^{(k)})$. Therefore, all that is required for maintaining correctness in the absence of detailed balance, is to weigh each chain by its ``hardness''  $\alpha_\theta(x^{(0)},\ldots,x^{(k)})$ (see Alg.~\ref{algo:acd} in App.~\ref{appendix:algo}). Note that in this case, the update depends not only on the end-points of the chains, but rather also on their intermediate steps. As can be seen in Fig. \ref{fig:cd_flavors}, this method performs just as well as MH, and significantly better than vanilla CD without correction.

\begin{figure}[t]
    \centering
    \includegraphics[scale=0.5]{media/spiral_cd_variants_2d.pdf}
    \caption{
        Here, we use different CD configurations for learning the model of Fig.~\ref{fig:toy_experiment}. All configurations use Langevin dynamics as their MCMC process, but with different ways of compensating for the lack of detailed balance. From left to right we have the ground-truth density, CD w/o any correction, CD with Metropolis-Hastings rejection, and CD with our proposed adjustment.
        }
    \label{fig:cd_flavors}
\end{figure}


\section{Illustration Through a Toy Example}
To illustrate our observations, we now conclude with a simple toy example (see Fig.~\ref{fig:toy_experiment}). Our goal here is not to draw general conclusions regarding the performance of CNCE and CD, but rather merely to highlight the adversarial nature of CD and its importance when the data density exhibits different scales of variation along different directions.

We take data concentrated around a 2-dimensional manifold embedded in 10-dimensional space. Specifically, let $e^{(1)},\dots,e^{(10)}$ denote the standard basis in $\mathbb{R}^{10}$. Then each data sample is generated by adding Gaussian noise to a random point along a 2D spiral lying in the $e^{(1)}$-$e^{(2)}$ plane. The STD of the noise in the $e^{(1)}$ and $e^{(2)}$ directions is 5 times larger than that in the other 8 axes. Figure \ref{fig:toy_model} shows the projections of the the data samples onto the the first 3 dimensions. Here, we use a multi-layer perceptron (MLP) as our parametric model, $\log p_\theta$, and train it using several different learning configurations (for the full details see App.~\ref{appendix:experiment_details}).

Figure~\ref{fig:cnce_vs_acd} visualizes the training as well as the final result achieved by each configuration. The first two rows show CNCE with Gaussian contrastive distributions of two different STDs. The third row shows the adjusted CD described in Sec.~\ref{sec:ACD} with Langevin Dynamics as its MCMC process. As can be seen, for CNCE with a large STD, the contrastive samples are able to explore large areas around the original samples, but this causes their majority to lie relatively far from the manifold (see their projections onto the $e^{(1)}$-$e^{(3)}$ plane). In this case, $\alpha_\theta$ decreases quickly, causing the learning process to ignore most samples at a very early stage of the training. When using CNCE with a small STD, the samples remain relevant throughout the training, but this comes at the price of inability to capture the global structure of the distribution. CD, on the other hand, is able to enjoy the best of both worlds as it adapts the contrastive distribution over time. Indeed, as the learning progresses, the contrastive samples move closer to the manifold to maintain their relevance. Note that since we use the adjusted version of CD, the weights in this configuration are not precisely $1$. We chose the step size of the Langevin Dynamics so that the median of the weights is approximately $10^{-2}$.

Figure~\ref{fig:cd_flavors} shows the results achieved by different variants of CD. As can be seen, without correcting for the lack of detailed balance, CD fails to estimate the density correctly. When using MH rejection to correct the MCMC, or our adaptive CD (ADC) to correct the update steps, the estimate is significantly improved.

\section{Conclusion}
The classical CD method has seen many uses and theoretical analyses over the years. The original derivation presented the algorithm as an approximate gradient descent process for a certain loss. However, the accuracy of the approximation has been a matter of much dispute, leaving it unclear what objective the algorithm minimizes in practice. Here, we presented an alternative derivation of CD's update steps, which involves no approximations. Our analysis shows that CD is in essence an adversarial learning procedure, where a discriminator is trained to distinguish whether a Markov chain generated from the learned model has been time-flipped or not. Therefore, although predating GANs by more than a decade, CD in fact belongs to the same family of techniques. This provides a possible explanation for its empirical success.

\paragraph{Acknowledgement} This research was supported by the Technion
Ollendorff Minerva Center. 



