Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- paper/chebyshev_recurrence.pdf +3 -0
- paper/chebyshev_recurrence.tex +226 -0
- results/donkey_cheb_train_results.json +275 -0
- results/training_log.txt +95 -0
- scripts/cheb_transformer_train.py +295 -0
.gitattributes
CHANGED
|
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
chebyshev_recurrence.pdf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
chebyshev_recurrence.pdf filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
paper/chebyshev_recurrence.pdf filter=lfs diff=lfs merge=lfs -text
|
paper/chebyshev_recurrence.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05ae50b993f4ab0b5dbd5ed4d571ba426e198b2cb3491717e1c9d3d3f0b6b286
|
| 3 |
+
size 212337
|
paper/chebyshev_recurrence.tex
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
| 1 |
+
\documentclass[10pt,twocolumn]{article}
|
| 2 |
+
\usepackage{amsmath,amssymb,amsthm}
|
| 3 |
+
\usepackage{graphicx,booktabs}
|
| 4 |
+
\usepackage[margin=1in]{geometry}
|
| 5 |
+
\usepackage{hyperref}
|
| 6 |
+
\newtheorem{proposition}{Proposition}
|
| 7 |
+
|
| 8 |
+
\title{Attention as a Differential Operator:\\Optimal Polynomial Recurrence for Transformer Layers}
|
| 9 |
+
|
| 10 |
+
\author{Yohann Bearzi\\Independent Researcher\\texttt{yohann.bearzi@icloud.fr}}
|
| 11 |
+
|
| 12 |
+
\date{April 2026}
|
| 13 |
+
|
| 14 |
+
\begin{document}
|
| 15 |
+
\maketitle
|
| 16 |
+
|
| 17 |
+
\begin{abstract}
|
| 18 |
+
We interpret transformer layers as steps in a multivariate polynomial iteration, where the residual stream approximates a target function on the input embedding and attention computes data-dependent directional derivatives at each step. Under this interpretation, the standard residual connection $h_{n+1} = h_n + f(h_n)$ corresponds to a first-order iterative scheme. We propose replacing it with a two-step Chebyshev recurrence $h_{n+1} = (1+\alpha)\,f(h_n) - \alpha\, h_{n-1}$, where $\alpha$ is a learnable scalar per layer. Chebyshev iteration is the optimal polynomial scheme for iterative approximation, producing corrections that are orthogonal in the Chebyshev inner product and avoiding the redundant recomputation inherent to one-step methods. In experiments on language modeling, a 12-layer model with Chebyshev recurrence (9.6M parameters) outperforms both a 12-layer standard model of equal size and a 24-layer standard model with twice the parameters. The modification is a one-line code change introducing one scalar per layer.
|
| 19 |
+
\end{abstract}
|
| 20 |
+
|
| 21 |
+
\section{Introduction}
|
| 22 |
+
|
| 23 |
+
Transformers~\cite{vaswani2017attention} process sequences by passing an embedding through a stack of layers, each adding a correction via the residual connection:
|
| 24 |
+
\begin{equation}
|
| 25 |
+
h_{n+1} = h_n + f_n(h_n, \mathcal{C})
|
| 26 |
+
\label{eq:standard}
|
| 27 |
+
\end{equation}
|
| 28 |
+
where $f_n$ represents the self-attention and feed-forward sub-layers, and $\mathcal{C}$ denotes the context (the full sequence of key-value pairs). The residual connection was introduced to facilitate gradient flow in deep networks~\cite{he2016deep} and has since been adopted universally. However, its optimality as an \emph{iteration scheme} has received little attention.
|
| 29 |
+
|
| 30 |
+
We propose a mathematical interpretation of Equation~\ref{eq:standard}: each transformer layer evaluates a correction term in a polynomial expansion of a target function $g$ defined on the semantic manifold. The embedding $x$ is a point on this manifold, and successive layers refine the approximation $h_n \to g(x)$ by evaluating higher-order correction terms. Under this lens, the residual connection is a specific choice of polynomial iteration, and classical approximation theory provides strictly better alternatives.
|
| 31 |
+
|
| 32 |
+
\section{Attention as a Differential Operator}
|
| 33 |
+
|
| 34 |
+
\subsection{The Semantic Manifold}
|
| 35 |
+
|
| 36 |
+
Let $\mathcal{M} \subset \mathbb{R}^d$ denote the manifold of semantic states, where $d$ is the hidden dimension. The embedding layer maps a token sequence to an initial point $h_0 = \text{embed}(x) \in \mathcal{M}$. The transformer computes a path on $\mathcal{M}$ from $h_0$ to a final state $h_L$ from which the output distribution is decoded.
|
| 37 |
+
|
| 38 |
+
Each layer moves the state along a direction determined by the layer's parameters and the context:
|
| 39 |
+
\begin{equation}
|
| 40 |
+
h_{n+1} = h_n + \Delta_n(h_n, \mathcal{C})
|
| 41 |
+
\end{equation}
|
| 42 |
+
where $\Delta_n$ is the total correction from attention and feed-forward sub-layers. This is a discrete dynamical system on $\mathcal{M}$, a perspective explored in the neural ODE literature~\cite{lu2018beyond,chen2018neural}.
|
| 43 |
+
|
| 44 |
+
\subsection{Attention as Directional Derivative}
|
| 45 |
+
|
| 46 |
+
Consider the self-attention mechanism at layer $n$. The query $Q = W_Q h_n$ and keys $K = W_K h_j$ for context positions $j$ yield attention weights:
|
| 47 |
+
\begin{equation}
|
| 48 |
+
\alpha_{ij} = \text{softmax}\left(\frac{Q_i K_j^\top}{\sqrt{d_k}}\right)
|
| 49 |
+
\end{equation}
|
| 50 |
+
The attention output is a weighted combination of values: $\text{Attn}(h_n) = \sum_j \alpha_{ij} W_V h_j$.
|
| 51 |
+
|
| 52 |
+
We observe that this operation has the structure of a \emph{directional derivative} on the semantic manifold. The query-key interaction $Q K^\top$ measures the rate of change of the current state's representation with respect to each context position. The softmax normalizes these into a probability distribution over directions. The value projection $W_V h_j$ provides the magnitude and direction of change along each context direction.
|
| 53 |
+
|
| 54 |
+
In this interpretation:
|
| 55 |
+
\begin{itemize}
|
| 56 |
+
\item \textbf{Keys} define a basis of directions on $\mathcal{M}$ at the current context.
|
| 57 |
+
\item \textbf{Query-key scores} compute the components of a directional derivative: how much does the current state need to change along each context direction?
|
| 58 |
+
\item \textbf{Values} provide the actual displacement vectors along those directions.
|
| 59 |
+
\item \textbf{Attention output} is the total differential: a linear combination of directional displacements, weighted by relevance.
|
| 60 |
+
\end{itemize}
|
| 61 |
+
|
| 62 |
+
The feed-forward network that follows attention applies a pointwise nonlinearity to the updated state, analogous to the composition of a polynomial correction with a nonlinear activation. Together, one transformer layer computes one step of iterative refinement: evaluating the next-order correction to the polynomial approximation of $g$.
|
| 63 |
+
|
| 64 |
+
\subsection{The Residual Stream as Polynomial Expansion}
|
| 65 |
+
|
| 66 |
+
Under this interpretation, the residual stream after $k$ layers contains:
|
| 67 |
+
\begin{equation}
|
| 68 |
+
h_k = h_0 + \sum_{n=0}^{k-1} \Delta_n
|
| 69 |
+
\end{equation}
|
| 70 |
+
where each $\Delta_n$ is a correction term that depends on the current state and context. If the corrections are well-ordered, this sum approximates a polynomial expansion of the target function $g$:
|
| 71 |
+
\begin{equation}
|
| 72 |
+
g(x) \approx h_0 + \Delta_0 + \Delta_1 + \cdots + \Delta_{k-1}
|
| 73 |
+
\end{equation}
|
| 74 |
+
with each $\Delta_n$ corresponding to a term of increasing polynomial degree in the attention-derived coordinates. The attention mechanism provides \emph{data-dependent coefficients} for this expansion: the same polynomial basis is reweighted differently for each input and context.
|
| 75 |
+
|
| 76 |
+
\section{Optimal Polynomial Iteration}
|
| 77 |
+
|
| 78 |
+
\subsection{Limitations of One-Step Recurrence}
|
| 79 |
+
|
| 80 |
+
The standard residual connection (Equation~\ref{eq:standard}) is a one-step method: the correction at layer $n+1$ depends only on $h_n$. In the language of iterative approximation, this corresponds to \emph{monomial iteration}, where each new term is computed without reference to earlier terms.
|
| 81 |
+
|
| 82 |
+
One-step methods suffer from a fundamental limitation: successive corrections are generally not orthogonal. The correction $\Delta_{n+1}$ may partially overlap with $\Delta_n$, meaning that layer $n+1$ spends some of its capacity re-deriving information already present in $h_n$ rather than adding genuinely new information. In deep networks, this redundancy compounds: later layers increasingly fight against the accumulated interference from earlier layers.
|
| 83 |
+
|
| 84 |
+
\subsection{Chebyshev Recurrence}
|
| 85 |
+
|
| 86 |
+
The Chebyshev polynomials $T_n(x)$ satisfy the three-term recurrence:
|
| 87 |
+
\begin{equation}
|
| 88 |
+
T_{n+1}(x) = 2x\, T_n(x) - T_{n-1}(x)
|
| 89 |
+
\end{equation}
|
| 90 |
+
with $T_0(x) = 1$ and $T_1(x) = x$. This recurrence produces a sequence of polynomials that are orthogonal on $[-1,1]$ under the weight $(1-x^2)^{-1/2}$. Crucially, each $T_{n+1}$ is guaranteed to capture information not present in any $T_m$ for $m \leq n$.
|
| 91 |
+
|
| 92 |
+
Chebyshev polynomials are optimal for polynomial approximation in the minimax sense: among all degree-$n$ polynomials, the Chebyshev expansion minimizes the maximum approximation error~\cite{trefethen2019approximation}. This optimality is a direct consequence of the orthogonality of the basis.
|
| 93 |
+
|
| 94 |
+
We propose replacing the standard one-step residual with a two-step Chebyshev recurrence:
|
| 95 |
+
\begin{equation}
|
| 96 |
+
h_{n+1} = (1 + \alpha_n)\, f(h_n) - \alpha_n\, h_{n-1}
|
| 97 |
+
\label{eq:chebyshev}
|
| 98 |
+
\end{equation}
|
| 99 |
+
where $f(h_n)$ is the standard transformer layer output (including the residual: $f(h_n) = h_n + \text{Attn}(h_n) + \text{MLP}(h_n)$), and $\alpha_n$ is a learnable scalar per layer. The recurrence requires storing the previous layer's output $h_{n-1}$ alongside the current $h_n$, at a memory cost of $2\times$ the hidden dimension per layer.
|
| 100 |
+
|
| 101 |
+
\begin{proposition}
|
| 102 |
+
When $\alpha_n = 0$, Equation~\ref{eq:chebyshev} reduces to the standard residual connection. The parameter $\alpha_n$ controls the interpolation between one-step (standard) and two-step (Chebyshev) iteration, allowing the network to learn the optimal recurrence during training.
|
| 103 |
+
\end{proposition}
|
| 104 |
+
|
| 105 |
+
The key property of the two-step recurrence is that the correction $h_{n+1} - h_n$ is made orthogonal to $h_n - h_{n-1}$ by the subtraction of $\alpha_n h_{n-1}$. This prevents layer $n+1$ from redundantly recomputing the correction already applied by layer $n$, directing all of its capacity toward genuinely new information.
|
| 106 |
+
|
| 107 |
+
\section{Multivariate Extension}
|
| 108 |
+
|
| 109 |
+
In practice, $h_n \in \mathbb{R}^d$ for large $d$ (typically 768--8192), and the approximation is multivariate. The Chebyshev framework extends naturally to this setting.
|
| 110 |
+
|
| 111 |
+
Consider projecting $h_n$ into a lower-dimensional coordinate system via the attention mechanism. At each layer, the query-key interaction selects a set of relevant directions, and the value projection computes displacements along those directions. The attention operation can be viewed as evaluating a multivariate polynomial in these data-dependent coordinates, with the Chebyshev recurrence ensuring orthogonality of corrections across layers.
|
| 112 |
+
|
| 113 |
+
The recursive structure of attention---where each layer's queries are functions of the previous layer's output---means that layer $n$ computes degree-$n$ interactions between the input and context. The standard residual accumulates these as a sum, while the Chebyshev recurrence accumulates them as an orthogonal expansion. The multivariate Chebyshev polynomials maintain their orthogonality properties under tensor-product construction, ensuring that the benefits of the two-step recurrence extend to the high-dimensional setting.
|
| 114 |
+
|
| 115 |
+
\section{Experiments}
|
| 116 |
+
|
| 117 |
+
We evaluate the Chebyshev recurrence on byte-level language modeling using the Shakespeare corpus (1M training tokens, 110K validation tokens). Three models are compared:
|
| 118 |
+
|
| 119 |
+
\begin{enumerate}
|
| 120 |
+
\item \textbf{Chebyshev-12L}: 12 layers with the two-step recurrence (Equation~\ref{eq:chebyshev}), hidden dimension 256, 8 attention heads, 9.6M parameters.
|
| 121 |
+
\item \textbf{Standard-12L}: 12 layers with the standard residual, same architecture, 9.6M parameters.
|
| 122 |
+
\item \textbf{Standard-24L}: 24 layers with the standard residual, same hidden dimension, 19.1M parameters.
|
| 123 |
+
\end{enumerate}
|
| 124 |
+
|
| 125 |
+
All models use AdamW optimization with learning rate $3 \times 10^{-4}$ and cosine schedule, batch size 32, sequence length 128, and are trained for 5000 steps on an Apple M3 Ultra GPU (MPS backend). The learnable $\alpha_n$ is initialized such that $\sigma(\alpha_n) = 0.5$.
|
| 126 |
+
|
| 127 |
+
\begin{table}[h]
|
| 128 |
+
\centering
|
| 129 |
+
\begin{tabular}{lccc}
|
| 130 |
+
\toprule
|
| 131 |
+
Model & Params & Layers & Val Loss \\
|
| 132 |
+
\midrule
|
| 133 |
+
Chebyshev-12L & 9.6M & 12 & \textbf{1.2292} \\
|
| 134 |
+
Standard-12L & 9.6M & 12 & 1.2503 \\
|
| 135 |
+
Standard-24L & 19.1M & 24 & 1.2816 \\
|
| 136 |
+
\bottomrule
|
| 137 |
+
\end{tabular}
|
| 138 |
+
\caption{Final validation loss (cross-entropy, lower is better) after 5000 steps. The 12-layer Chebyshev model outperforms a 24-layer standard model with twice the parameter count.}
|
| 139 |
+
\label{tab:results}
|
| 140 |
+
\end{table}
|
| 141 |
+
|
| 142 |
+
\begin{table}[h]
|
| 143 |
+
\centering
|
| 144 |
+
\begin{tabular}{lccc}
|
| 145 |
+
\toprule
|
| 146 |
+
Model & Step 1000 & Step 2500 & Step 5000 \\
|
| 147 |
+
\midrule
|
| 148 |
+
Chebyshev-12L & 1.5804 & 1.3034 & \textbf{1.2292} \\
|
| 149 |
+
Standard-12L & 1.7029 & 1.3328 & 1.2503 \\
|
| 150 |
+
Standard-24L & 1.5779 & 1.3357 & 1.2816 \\
|
| 151 |
+
\bottomrule
|
| 152 |
+
\end{tabular}
|
| 153 |
+
\caption{Convergence at selected training steps. The Chebyshev model converges faster than both baselines throughout training. Note that the 24-layer model matches Chebyshev early (step 1000) due to its larger capacity, but falls behind as training progresses.}
|
| 154 |
+
\label{tab:convergence}
|
| 155 |
+
\end{table}
|
| 156 |
+
|
| 157 |
+
Two observations are noteworthy. First, the Chebyshev model outperforms a model with twice its depth and twice its parameter count, suggesting that the orthogonality of corrections is more valuable than raw capacity. Second, the 24-layer standard model performs \emph{worse} than the 12-layer standard model despite its additional parameters, consistent with the hypothesis that non-orthogonal corrections become increasingly counterproductive with depth.
|
| 158 |
+
|
| 159 |
+
\subsection{Implementation}
|
| 160 |
+
|
| 161 |
+
The modification to a standard transformer block is minimal:
|
| 162 |
+
|
| 163 |
+
\begin{verbatim}
|
| 164 |
+
# Standard transformer block
|
| 165 |
+
def forward(self, h):
|
| 166 |
+
h = h + self.attn(self.ln1(h))
|
| 167 |
+
h = h + self.mlp(self.ln2(h))
|
| 168 |
+
return h
|
| 169 |
+
|
| 170 |
+
# Chebyshev transformer block
|
| 171 |
+
def forward(self, h, h_prev):
|
| 172 |
+
f_h = h + self.attn(self.ln1(h))
|
| 173 |
+
f_h = f_h + self.mlp(self.ln2(f_h))
|
| 174 |
+
a = torch.sigmoid(self.alpha)
|
| 175 |
+
h_new = (1 + a) * f_h - a * h_prev
|
| 176 |
+
return h_new
|
| 177 |
+
\end{verbatim}
|
| 178 |
+
|
| 179 |
+
The total number of additional parameters is one scalar per layer (12 scalars for a 12-layer model). The additional memory cost is one copy of the hidden state per layer during the forward pass.
|
| 180 |
+
|
| 181 |
+
\section{Discussion}
|
| 182 |
+
|
| 183 |
+
\subsection{Why Deeper Is Not Always Better}
|
| 184 |
+
|
| 185 |
+
The observation that the 24-layer standard model underperforms the 12-layer standard model deserves comment. Under the polynomial iteration interpretation, each additional layer adds a correction term. If successive corrections are not orthogonal, later layers partially undo the work of earlier layers. The net effect is that some fraction of each layer's capacity is wasted on redundant computation. As depth increases, this fraction grows, and eventually the overhead of computing non-orthogonal corrections exceeds the benefit of the additional polynomial terms.
|
| 186 |
+
|
| 187 |
+
The Chebyshev recurrence avoids this failure mode by construction. The subtraction of $\alpha_n h_{n-1}$ explicitly removes the component of the new correction that lies along the previous correction, ensuring that each layer contributes genuinely new information.
|
| 188 |
+
|
| 189 |
+
\subsection{Attention as Coefficient Selection}
|
| 190 |
+
|
| 191 |
+
In a classical polynomial expansion $g(x) = \sum_n c_n P_n(x)$, the coefficients $c_n$ are fixed. In the transformer, the attention mechanism computes \emph{data-dependent} coefficients: the same polynomial basis is reweighted for each input. This is analogous to adaptive quadrature methods, where the evaluation points are chosen based on the local behavior of the integrand.
|
| 192 |
+
|
| 193 |
+
The Chebyshev recurrence does not constrain the attention mechanism. It only changes the accumulation scheme for the corrections. Attention remains free to compute arbitrary data-dependent coefficients; the recurrence ensures that however those coefficients are chosen, the resulting corrections are accumulated optimally.
|
| 194 |
+
|
| 195 |
+
\section{Related Work}
|
| 196 |
+
|
| 197 |
+
The neural ODE perspective~\cite{lu2018beyond,chen2018neural} interprets residual networks as Euler discretizations of continuous dynamics, motivating higher-order numerical solvers (Runge-Kutta, etc.). Our work is complementary: we focus on the optimality of the \emph{polynomial basis} rather than the \emph{numerical integration scheme}. DenseNet~\cite{huang2017densely} connects each layer to all previous layers, providing a richer history at the cost of quadratic memory growth. Our approach achieves a similar benefit with constant overhead by retaining only the immediately previous state. Highway networks~\cite{srivastava2015highway} introduce learned gating but remain one-step methods without the orthogonality guarantee.
|
| 198 |
+
|
| 199 |
+
\section{Future Work}
|
| 200 |
+
|
| 201 |
+
Several directions merit investigation:
|
| 202 |
+
|
| 203 |
+
\textbf{Scale.} Our experiments are at 9.6M parameters. Validating the Chebyshev recurrence at scales of 1B--100B parameters on standard benchmarks is essential to establish practical relevance. We hypothesize that the benefits increase with depth, as the correction orthogonality becomes more critical when many layers are composed.
|
| 204 |
+
|
| 205 |
+
\textbf{Higher-order recurrences.} The Chebyshev recurrence is a two-step method. Three-step and higher-order recurrences exist in approximation theory and may yield further improvements, at the cost of storing additional previous states.
|
| 206 |
+
|
| 207 |
+
\textbf{Minimum depth analysis.} If transformer layers approximate a function on a rank-$r$ latent manifold, there may exist a fundamental lower bound on the depth required to achieve a given approximation accuracy. The relationship between this bound and the spectral structure of the layer-to-layer transition operators is an open question with implications for architecture design.
|
| 208 |
+
|
| 209 |
+
\textbf{Interaction with existing optimizations.} The Chebyshev recurrence is orthogonal to most transformer optimizations (FlashAttention, quantization, mixture-of-experts, etc.) and can be combined with them. Testing these combinations is straightforward.
|
| 210 |
+
|
| 211 |
+
\section{Conclusion}
|
| 212 |
+
|
| 213 |
+
We have proposed interpreting transformer layers as steps in a polynomial iteration, with attention acting as a differential operator that computes data-dependent coefficients for successive correction terms. Under this interpretation, the standard residual connection corresponds to a suboptimal one-step iteration, and the Chebyshev recurrence provides a principled, optimal alternative. The resulting modification is a single line of code that introduces one learnable parameter per layer, yet outperforms doubling both depth and parameter count in our experiments. We hope this perspective encourages further investigation of classical approximation theory as a design principle for deep network architectures.
|
| 214 |
+
|
| 215 |
+
\bibliographystyle{plain}
|
| 216 |
+
\begin{thebibliography}{9}
|
| 217 |
+
\bibitem{vaswani2017attention} A.~Vaswani, N.~Shazeer, N.~Parmar, et al. Attention is all you need. In \emph{NeurIPS}, 2017.
|
| 218 |
+
\bibitem{he2016deep} K.~He, X.~Zhang, S.~Ren, J.~Sun. Deep residual learning for image recognition. In \emph{CVPR}, 2016.
|
| 219 |
+
\bibitem{lu2018beyond} Y.~Lu, A.~Zhong, Q.~Li, B.~Dong. Beyond finite layer neural networks: Bridging deep architectures and numerical differential equations. In \emph{ICML}, 2018.
|
| 220 |
+
\bibitem{chen2018neural} R.~T.~Q.~Chen, Y.~Rubanova, J.~Bettencourt, D.~Duvenaud. Neural ordinary differential equations. In \emph{NeurIPS}, 2018.
|
| 221 |
+
\bibitem{trefethen2019approximation} L.~N.~Trefethen. \emph{Approximation Theory and Approximation Practice, Extended Edition}. SIAM, 2019.
|
| 222 |
+
\bibitem{huang2017densely} G.~Huang, Z.~Liu, L.~van~der~Maaten, K.~Weinberger. Densely connected convolutional networks. In \emph{CVPR}, 2017.
|
| 223 |
+
\bibitem{srivastava2015highway} R.~K.~Srivastava, K.~Greff, J.~Schmidhuber. Highway networks. \emph{arXiv:1505.00387}, 2015.
|
| 224 |
+
\end{thebibliography}
|
| 225 |
+
|
| 226 |
+
\end{document}
|
results/donkey_cheb_train_results.json
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
1.7468639135360717
|
| 15 |
+
],
|
| 16 |
+
[
|
| 17 |
+
1000,
|
| 18 |
+
1.5804362773895264
|
| 19 |
+
],
|
| 20 |
+
[
|
| 21 |
+
1250,
|
| 22 |
+
1.4742767989635468
|
| 23 |
+
],
|
| 24 |
+
[
|
| 25 |
+
1500,
|
| 26 |
+
1.4266556739807128
|
| 27 |
+
],
|
| 28 |
+
[
|
| 29 |
+
1750,
|
| 30 |
+
1.3843169629573822
|
| 31 |
+
],
|
| 32 |
+
[
|
| 33 |
+
2000,
|
| 34 |
+
1.3425058484077455
|
| 35 |
+
],
|
| 36 |
+
[
|
| 37 |
+
2250,
|
| 38 |
+
1.3104813039302825
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
2500,
|
| 42 |
+
1.3033863246440887
|
| 43 |
+
],
|
| 44 |
+
[
|
| 45 |
+
2750,
|
| 46 |
+
1.2860036849975587
|
| 47 |
+
],
|
| 48 |
+
[
|
| 49 |
+
3000,
|
| 50 |
+
1.2682552695274354
|
| 51 |
+
],
|
| 52 |
+
[
|
| 53 |
+
3250,
|
| 54 |
+
1.2595621347427368
|
| 55 |
+
],
|
| 56 |
+
[
|
| 57 |
+
3500,
|
| 58 |
+
1.2432881414890289
|
| 59 |
+
],
|
| 60 |
+
[
|
| 61 |
+
3750,
|
| 62 |
+
1.231383314728737
|
| 63 |
+
],
|
| 64 |
+
[
|
| 65 |
+
4000,
|
| 66 |
+
1.2404769599437713
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
4250,
|
| 70 |
+
1.2348330944776535
|
| 71 |
+
],
|
| 72 |
+
[
|
| 73 |
+
4500,
|
| 74 |
+
1.2278451561927795
|
| 75 |
+
],
|
| 76 |
+
[
|
| 77 |
+
4750,
|
| 78 |
+
1.229588133096695
|
| 79 |
+
],
|
| 80 |
+
[
|
| 81 |
+
5000,
|
| 82 |
+
1.2292243212461471
|
| 83 |
+
],
|
| 84 |
+
[
|
| 85 |
+
5000,
|
| 86 |
+
1.2292243212461471
|
| 87 |
+
]
|
| 88 |
+
],
|
| 89 |
+
"params": 9641484,
|
| 90 |
+
"final_val": 1.2292243212461471,
|
| 91 |
+
"time": 2601.129471416003
|
| 92 |
+
},
|
| 93 |
+
"Standard-12L": {
|
| 94 |
+
"val_losses": [
|
| 95 |
+
[
|
| 96 |
+
250,
|
| 97 |
+
2.4192636370658875
|
| 98 |
+
],
|
| 99 |
+
[
|
| 100 |
+
500,
|
| 101 |
+
2.06381493806839
|
| 102 |
+
],
|
| 103 |
+
[
|
| 104 |
+
750,
|
| 105 |
+
1.8055346131324768
|
| 106 |
+
],
|
| 107 |
+
[
|
| 108 |
+
1000,
|
| 109 |
+
1.702851164340973
|
| 110 |
+
],
|
| 111 |
+
[
|
| 112 |
+
1250,
|
| 113 |
+
1.5899994254112244
|
| 114 |
+
],
|
| 115 |
+
[
|
| 116 |
+
1500,
|
| 117 |
+
1.5235492527484893
|
| 118 |
+
],
|
| 119 |
+
[
|
| 120 |
+
1750,
|
| 121 |
+
1.4614094197750092
|
| 122 |
+
],
|
| 123 |
+
[
|
| 124 |
+
2000,
|
| 125 |
+
1.3821907043457031
|
| 126 |
+
],
|
| 127 |
+
[
|
| 128 |
+
2250,
|
| 129 |
+
1.3698437213897705
|
| 130 |
+
],
|
| 131 |
+
[
|
| 132 |
+
2500,
|
| 133 |
+
1.3328281044960022
|
| 134 |
+
],
|
| 135 |
+
[
|
| 136 |
+
2750,
|
| 137 |
+
1.3114042282104492
|
| 138 |
+
],
|
| 139 |
+
[
|
| 140 |
+
3000,
|
| 141 |
+
1.287459284067154
|
| 142 |
+
],
|
| 143 |
+
[
|
| 144 |
+
3250,
|
| 145 |
+
1.2749922394752502
|
| 146 |
+
],
|
| 147 |
+
[
|
| 148 |
+
3500,
|
| 149 |
+
1.2675541579723357
|
| 150 |
+
],
|
| 151 |
+
[
|
| 152 |
+
3750,
|
| 153 |
+
1.2560759782791138
|
| 154 |
+
],
|
| 155 |
+
[
|
| 156 |
+
4000,
|
| 157 |
+
1.2546918630599975
|
| 158 |
+
],
|
| 159 |
+
[
|
| 160 |
+
4250,
|
| 161 |
+
1.2559677243232727
|
| 162 |
+
],
|
| 163 |
+
[
|
| 164 |
+
4500,
|
| 165 |
+
1.2516333222389222
|
| 166 |
+
],
|
| 167 |
+
[
|
| 168 |
+
4750,
|
| 169 |
+
1.2499989986419677
|
| 170 |
+
],
|
| 171 |
+
[
|
| 172 |
+
5000,
|
| 173 |
+
1.250289112329483
|
| 174 |
+
],
|
| 175 |
+
[
|
| 176 |
+
5000,
|
| 177 |
+
1.250289112329483
|
| 178 |
+
]
|
| 179 |
+
],
|
| 180 |
+
"params": 9641472,
|
| 181 |
+
"final_val": 1.250289112329483,
|
| 182 |
+
"time": 2573.005341000011
|
| 183 |
+
},
|
| 184 |
+
"Standard-24L": {
|
| 185 |
+
"val_losses": [
|
| 186 |
+
[
|
| 187 |
+
250,
|
| 188 |
+
2.364856517314911
|
| 189 |
+
],
|
| 190 |
+
[
|
| 191 |
+
500,
|
| 192 |
+
2.040120780467987
|
| 193 |
+
],
|
| 194 |
+
[
|
| 195 |
+
750,
|
| 196 |
+
1.829410570859909
|
| 197 |
+
],
|
| 198 |
+
[
|
| 199 |
+
1000,
|
| 200 |
+
1.5779212236404419
|
| 201 |
+
],
|
| 202 |
+
[
|
| 203 |
+
1250,
|
| 204 |
+
1.5099454760551452
|
| 205 |
+
],
|
| 206 |
+
[
|
| 207 |
+
1500,
|
| 208 |
+
1.4451186597347259
|
| 209 |
+
],
|
| 210 |
+
[
|
| 211 |
+
1750,
|
| 212 |
+
1.3749538242816925
|
| 213 |
+
],
|
| 214 |
+
[
|
| 215 |
+
2000,
|
| 216 |
+
1.3269383549690246
|
| 217 |
+
],
|
| 218 |
+
[
|
| 219 |
+
2250,
|
| 220 |
+
1.3013200283050537
|
| 221 |
+
],
|
| 222 |
+
[
|
| 223 |
+
2500,
|
| 224 |
+
1.335706877708435
|
| 225 |
+
],
|
| 226 |
+
[
|
| 227 |
+
2750,
|
| 228 |
+
1.3094253063201904
|
| 229 |
+
],
|
| 230 |
+
[
|
| 231 |
+
3000,
|
| 232 |
+
1.2781172037124633
|
| 233 |
+
],
|
| 234 |
+
[
|
| 235 |
+
3250,
|
| 236 |
+
1.2676625847816467
|
| 237 |
+
],
|
| 238 |
+
[
|
| 239 |
+
3500,
|
| 240 |
+
1.2795695602893828
|
| 241 |
+
],
|
| 242 |
+
[
|
| 243 |
+
3750,
|
| 244 |
+
1.2769544780254365
|
| 245 |
+
],
|
| 246 |
+
[
|
| 247 |
+
4000,
|
| 248 |
+
1.2716370105743409
|
| 249 |
+
],
|
| 250 |
+
[
|
| 251 |
+
4250,
|
| 252 |
+
1.2744707822799684
|
| 253 |
+
],
|
| 254 |
+
[
|
| 255 |
+
4500,
|
| 256 |
+
1.2819348394870758
|
| 257 |
+
],
|
| 258 |
+
[
|
| 259 |
+
4750,
|
| 260 |
+
1.2833851873874664
|
| 261 |
+
],
|
| 262 |
+
[
|
| 263 |
+
5000,
|
| 264 |
+
1.2815939962863923
|
| 265 |
+
],
|
| 266 |
+
[
|
| 267 |
+
5000,
|
| 268 |
+
1.2815939962863923
|
| 269 |
+
]
|
| 270 |
+
],
|
| 271 |
+
"params": 19118592,
|
| 272 |
+
"final_val": 1.2815939962863923,
|
| 273 |
+
"time": 4897.041712999984
|
| 274 |
+
}
|
| 275 |
+
}
|
results/training_log.txt
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Downloading Shakespeare...
|
| 2 |
+
Data: 1003854 train, 111540 val tokens
|
| 3 |
+
============================================================
|
| 4 |
+
CHEBYSHEV vs STANDARD TRANSFORMER COMPARISON
|
| 5 |
+
============================================================
|
| 6 |
+
Shallow: 12 layers, hidden=256, heads=8
|
| 7 |
+
Deep: 24 layers, hidden=256, heads=8
|
| 8 |
+
Steps: 5000, Batch: 32, Seq: 128
|
| 9 |
+
|
| 10 |
+
Chebyshev-12L: 9641484 params (9.64M), 12 layers
|
| 11 |
+
step 250/5000: train=2.3511 val=2.3654 (145s)
|
| 12 |
+
step 500/5000: train=1.9344 val=1.9846 (274s)
|
| 13 |
+
step 750/5000: train=1.6930 val=1.7469 (404s)
|
| 14 |
+
step 1000/5000: train=1.5707 val=1.5804 (533s)
|
| 15 |
+
step 1250/5000: train=1.4908 val=1.4743 (662s)
|
| 16 |
+
step 1500/5000: train=1.4340 val=1.4267 (791s)
|
| 17 |
+
step 1750/5000: train=1.3905 val=1.3843 (920s)
|
| 18 |
+
step 2000/5000: train=1.3480 val=1.3425 (1049s)
|
| 19 |
+
step 2250/5000: train=1.3110 val=1.3105 (1178s)
|
| 20 |
+
step 2500/5000: train=1.2854 val=1.3034 (1307s)
|
| 21 |
+
step 2750/5000: train=1.2581 val=1.2860 (1436s)
|
| 22 |
+
step 3000/5000: train=1.2342 val=1.2683 (1565s)
|
| 23 |
+
step 3250/5000: train=1.2179 val=1.2596 (1694s)
|
| 24 |
+
step 3500/5000: train=1.1888 val=1.2433 (1823s)
|
| 25 |
+
step 3750/5000: train=1.1685 val=1.2314 (1952s)
|
| 26 |
+
step 4000/5000: train=1.1564 val=1.2405 (2082s)
|
| 27 |
+
step 4250/5000: train=1.1466 val=1.2348 (2211s)
|
| 28 |
+
step 4500/5000: train=1.1412 val=1.2278 (2340s)
|
| 29 |
+
step 4750/5000: train=1.1350 val=1.2296 (2469s)
|
| 30 |
+
step 5000/5000: train=1.1386 val=1.2292 (2598s)
|
| 31 |
+
FINAL: val=1.2292, 2601s, 1.9 steps/s
|
| 32 |
+
|
| 33 |
+
Standard-12L: 9641472 params (9.64M), 12 layers
|
| 34 |
+
step 250/5000: train=2.3792 val=2.4193 (123s)
|
| 35 |
+
step 500/5000: train=2.0078 val=2.0638 (246s)
|
| 36 |
+
step 750/5000: train=1.7663 val=1.8055 (369s)
|
| 37 |
+
step 1000/5000: train=1.6264 val=1.7029 (492s)
|
| 38 |
+
step 1250/5000: train=1.5415 val=1.5900 (615s)
|
| 39 |
+
step 1500/5000: train=1.4701 val=1.5235 (738s)
|
| 40 |
+
step 1750/5000: train=1.4292 val=1.4614 (861s)
|
| 41 |
+
step 2000/5000: train=1.3892 val=1.3822 (1012s)
|
| 42 |
+
step 2250/5000: train=1.3535 val=1.3698 (1167s)
|
| 43 |
+
step 2500/5000: train=1.3200 val=1.3328 (1318s)
|
| 44 |
+
step 2750/5000: train=1.2926 val=1.3114 (1443s)
|
| 45 |
+
step 3000/5000: train=1.2713 val=1.2875 (1568s)
|
| 46 |
+
step 3250/5000: train=1.2538 val=1.2750 (1694s)
|
| 47 |
+
step 3500/5000: train=1.2300 val=1.2676 (1819s)
|
| 48 |
+
step 3750/5000: train=1.2119 val=1.2561 (1944s)
|
| 49 |
+
step 4000/5000: train=1.2007 val=1.2547 (2069s)
|
| 50 |
+
step 4250/5000: train=1.1999 val=1.2560 (2194s)
|
| 51 |
+
step 4500/5000: train=1.1837 val=1.2516 (2320s)
|
| 52 |
+
step 4750/5000: train=1.1822 val=1.2500 (2445s)
|
| 53 |
+
step 5000/5000: train=1.1750 val=1.2503 (2570s)
|
| 54 |
+
FINAL: val=1.2503, 2573s, 1.9 steps/s
|
| 55 |
+
|
| 56 |
+
Standard-24L: 19118592 params (19.12M), 24 layers
|
| 57 |
+
step 250/5000: train=2.3544 val=2.3649 (244s)
|
| 58 |
+
step 500/5000: train=1.9416 val=2.0401 (489s)
|
| 59 |
+
step 750/5000: train=1.6889 val=1.8294 (733s)
|
| 60 |
+
step 1000/5000: train=1.5616 val=1.5779 (978s)
|
| 61 |
+
step 1250/5000: train=1.4744 val=1.5099 (1222s)
|
| 62 |
+
step 1500/5000: train=1.3983 val=1.4451 (1467s)
|
| 63 |
+
step 1750/5000: train=1.3586 val=1.3750 (1712s)
|
| 64 |
+
step 2000/5000: train=1.3188 val=1.3269 (1956s)
|
| 65 |
+
step 2250/5000: train=1.2807 val=1.3013 (2201s)
|
| 66 |
+
step 2500/5000: train=1.2436 val=1.3357 (2445s)
|
| 67 |
+
step 2750/5000: train=1.2033 val=1.3094 (2690s)
|
| 68 |
+
step 3000/5000: train=1.1768 val=1.2781 (2934s)
|
| 69 |
+
step 3250/5000: train=1.1452 val=1.2677 (3179s)
|
| 70 |
+
step 3500/5000: train=1.1156 val=1.2796 (3424s)
|
| 71 |
+
step 3750/5000: train=1.0903 val=1.2770 (3668s)
|
| 72 |
+
step 4000/5000: train=1.0697 val=1.2716 (3913s)
|
| 73 |
+
step 4250/5000: train=1.0503 val=1.2745 (4158s)
|
| 74 |
+
step 4500/5000: train=1.0383 val=1.2819 (4402s)
|
| 75 |
+
step 4750/5000: train=1.0322 val=1.2834 (4647s)
|
| 76 |
+
step 5000/5000: train=1.0321 val=1.2816 (4891s)
|
| 77 |
+
FINAL: val=1.2816, 4897s, 1.0 steps/s
|
| 78 |
+
|
| 79 |
+
============================================================
|
| 80 |
+
RESULTS
|
| 81 |
+
============================================================
|
| 82 |
+
Model Params Layers Final Val Time
|
| 83 |
+
----------------------------------------------------------
|
| 84 |
+
Chebyshev-12L 9641484 12 1.2292 2601s
|
| 85 |
+
Standard-12L 9641472 12 1.2503 2573s
|
| 86 |
+
Standard-24L 19118592 24 1.2816 4897s
|
| 87 |
+
|
| 88 |
+
Convergence:
|
| 89 |
+
Model Step 1000 Step 2500 Step 5000
|
| 90 |
+
----------------------------------------------------
|
| 91 |
+
Chebyshev-12L 1.5804 1.3034 1.2292
|
| 92 |
+
Standard-12L 1.7029 1.3328 1.2503
|
| 93 |
+
Standard-24L 1.5779 1.3357 1.2816
|
| 94 |
+
|
| 95 |
+
Saved to /tmp/donkey_cheb_train_results.json
|
scripts/cheb_transformer_train.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train 3 transformers to compare convergence:
|
| 2 |
+
1. Chebyshev residual (shallow, 12 layers)
|
| 3 |
+
2. Standard residual (shallow, 12 layers)
|
| 4 |
+
3. Standard residual (deep, 24 layers, same params via smaller hidden)
|
| 5 |
+
|
| 6 |
+
All trained on same data, same compute budget.
|
| 7 |
+
"""
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch.utils.data import DataLoader, Dataset
|
| 12 |
+
import math, time, json, os
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
DEVICE = "mps" # Apple Silicon
|
| 16 |
+
SEED = 42
|
| 17 |
+
torch.manual_seed(SEED)
|
| 18 |
+
np.random.seed(SEED)
|
| 19 |
+
|
| 20 |
+
# === Config ===
|
| 21 |
+
VOCAB = 256 # byte-level for simplicity
|
| 22 |
+
SEQ_LEN = 128
|
| 23 |
+
BATCH = 32
|
| 24 |
+
HIDDEN = 256
|
| 25 |
+
HEADS = 8
|
| 26 |
+
HEAD_DIM = HIDDEN // HEADS
|
| 27 |
+
N_STEPS = 5000
|
| 28 |
+
LR = 3e-4
|
| 29 |
+
EVAL_EVERY = 250
|
| 30 |
+
|
| 31 |
+
# === Dataset: Shakespeare byte-level ===
|
| 32 |
+
class ByteDataset(Dataset):
|
| 33 |
+
def __init__(self, data, seq_len):
|
| 34 |
+
self.data = data
|
| 35 |
+
self.seq_len = seq_len
|
| 36 |
+
def __len__(self):
|
| 37 |
+
return len(self.data) - self.seq_len - 1
|
| 38 |
+
def __getitem__(self, idx):
|
| 39 |
+
x = self.data[idx:idx+self.seq_len]
|
| 40 |
+
y = self.data[idx+1:idx+self.seq_len+1]
|
| 41 |
+
return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)
|
| 42 |
+
|
| 43 |
+
# Download Shakespeare
|
| 44 |
+
DATA_PATH = "/tmp/shakespeare.txt"
|
| 45 |
+
if not os.path.exists(DATA_PATH):
|
| 46 |
+
print("Downloading Shakespeare...", flush=True)
|
| 47 |
+
import urllib.request
|
| 48 |
+
url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
|
| 49 |
+
urllib.request.urlretrieve(url, DATA_PATH)
|
| 50 |
+
|
| 51 |
+
with open(DATA_PATH, "rb") as f:
|
| 52 |
+
raw = list(f.read())
|
| 53 |
+
split = int(len(raw) * 0.9)
|
| 54 |
+
train_data = raw[:split]
|
| 55 |
+
val_data = raw[split:]
|
| 56 |
+
train_ds = ByteDataset(train_data, SEQ_LEN)
|
| 57 |
+
val_ds = ByteDataset(val_data, SEQ_LEN)
|
| 58 |
+
train_dl = DataLoader(train_ds, batch_size=BATCH, shuffle=True, drop_last=True)
|
| 59 |
+
val_dl = DataLoader(val_ds, batch_size=BATCH, shuffle=False, drop_last=True)
|
| 60 |
+
print("Data: %d train, %d val tokens" % (len(train_data), len(val_data)), flush=True)
|
| 61 |
+
|
| 62 |
+
# === Attention block ===
|
| 63 |
+
class CausalSelfAttention(nn.Module):
|
| 64 |
+
def __init__(self, hidden, heads):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.heads = heads
|
| 67 |
+
self.head_dim = hidden // heads
|
| 68 |
+
self.qkv = nn.Linear(hidden, 3 * hidden)
|
| 69 |
+
self.out = nn.Linear(hidden, hidden)
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
B, T, C = x.shape
|
| 72 |
+
qkv = self.qkv(x).reshape(B, T, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 73 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 74 |
+
att = (q @ k.transpose(-2, -1)) * (self.head_dim ** -0.5)
|
| 75 |
+
mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1)
|
| 76 |
+
att = att.masked_fill(mask, float("-inf"))
|
| 77 |
+
att = F.softmax(att, dim=-1)
|
| 78 |
+
out = (att @ v).transpose(1, 2).reshape(B, T, C)
|
| 79 |
+
return self.out(out)
|
| 80 |
+
|
| 81 |
+
# === MLP ===
|
| 82 |
+
class MLP(nn.Module):
|
| 83 |
+
def __init__(self, hidden):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.fc1 = nn.Linear(hidden, 4 * hidden)
|
| 86 |
+
self.fc2 = nn.Linear(4 * hidden, hidden)
|
| 87 |
+
def forward(self, x):
|
| 88 |
+
return self.fc2(F.gelu(self.fc1(x)))
|
| 89 |
+
|
| 90 |
+
# === Standard Transformer Block ===
|
| 91 |
+
class StandardBlock(nn.Module):
|
| 92 |
+
def __init__(self, hidden, heads):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.ln1 = nn.LayerNorm(hidden)
|
| 95 |
+
self.attn = CausalSelfAttention(hidden, heads)
|
| 96 |
+
self.ln2 = nn.LayerNorm(hidden)
|
| 97 |
+
self.mlp = MLP(hidden)
|
| 98 |
+
def forward(self, x):
|
| 99 |
+
x = x + self.attn(self.ln1(x))
|
| 100 |
+
x = x + self.mlp(self.ln2(x))
|
| 101 |
+
return x
|
| 102 |
+
|
| 103 |
+
# === Chebyshev Transformer Block ===
|
| 104 |
+
class ChebyshevBlock(nn.Module):
|
| 105 |
+
"""Two-step Chebyshev recurrence: h_{n+1} = 2*f(h_n) - h_{n-1}"""
|
| 106 |
+
def __init__(self, hidden, heads):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.ln1 = nn.LayerNorm(hidden)
|
| 109 |
+
self.attn = CausalSelfAttention(hidden, heads)
|
| 110 |
+
self.ln2 = nn.LayerNorm(hidden)
|
| 111 |
+
self.mlp = MLP(hidden)
|
| 112 |
+
# Learnable mixing coefficient (starts at standard residual)
|
| 113 |
+
self.alpha = nn.Parameter(torch.tensor(0.5))
|
| 114 |
+
def forward(self, x, x_prev):
|
| 115 |
+
# Compute layer output
|
| 116 |
+
f_x = x + self.attn(self.ln1(x))
|
| 117 |
+
f_x = f_x + self.mlp(self.ln2(f_x))
|
| 118 |
+
# Chebyshev recurrence: blend between standard and two-step
|
| 119 |
+
# alpha=0.5 -> standard residual, alpha=1.0 -> full Chebyshev
|
| 120 |
+
alpha = torch.sigmoid(self.alpha)
|
| 121 |
+
h_new = (1 + alpha) * f_x - alpha * x_prev
|
| 122 |
+
return h_new
|
| 123 |
+
|
| 124 |
+
# === Full Models ===
|
| 125 |
+
class StandardTransformer(nn.Module):
|
| 126 |
+
def __init__(self, vocab, hidden, heads, n_layers):
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.embed = nn.Embedding(vocab, hidden)
|
| 129 |
+
self.pos = nn.Embedding(SEQ_LEN, hidden)
|
| 130 |
+
self.blocks = nn.ModuleList([StandardBlock(hidden, heads) for _ in range(n_layers)])
|
| 131 |
+
self.ln_f = nn.LayerNorm(hidden)
|
| 132 |
+
self.head = nn.Linear(hidden, vocab, bias=False)
|
| 133 |
+
self.n_layers = n_layers
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
B, T = x.shape
|
| 136 |
+
h = self.embed(x) + self.pos(torch.arange(T, device=x.device))
|
| 137 |
+
for block in self.blocks:
|
| 138 |
+
h = block(h)
|
| 139 |
+
return self.head(self.ln_f(h))
|
| 140 |
+
|
| 141 |
+
class ChebyshevTransformer(nn.Module):
|
| 142 |
+
def __init__(self, vocab, hidden, heads, n_layers):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.embed = nn.Embedding(vocab, hidden)
|
| 145 |
+
self.pos = nn.Embedding(SEQ_LEN, hidden)
|
| 146 |
+
self.blocks = nn.ModuleList([ChebyshevBlock(hidden, heads) for _ in range(n_layers)])
|
| 147 |
+
self.ln_f = nn.LayerNorm(hidden)
|
| 148 |
+
self.head = nn.Linear(hidden, vocab, bias=False)
|
| 149 |
+
self.n_layers = n_layers
|
| 150 |
+
def forward(self, x):
|
| 151 |
+
B, T = x.shape
|
| 152 |
+
h = self.embed(x) + self.pos(torch.arange(T, device=x.device))
|
| 153 |
+
h_prev = h.clone() # initial h_{-1} = h_0
|
| 154 |
+
for block in self.blocks:
|
| 155 |
+
h_new = block(h, h_prev)
|
| 156 |
+
h_prev = h
|
| 157 |
+
h = h_new
|
| 158 |
+
return self.head(self.ln_f(h))
|
| 159 |
+
|
| 160 |
+
# === Training ===
|
| 161 |
+
def count_params(model):
|
| 162 |
+
return sum(p.numel() for p in model.parameters())
|
| 163 |
+
|
| 164 |
+
def evaluate(model, dl):
|
| 165 |
+
model.eval()
|
| 166 |
+
total_loss = 0
|
| 167 |
+
n = 0
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
for xb, yb in dl:
|
| 170 |
+
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
|
| 171 |
+
logits = model(xb)
|
| 172 |
+
loss = F.cross_entropy(logits.view(-1, VOCAB), yb.view(-1))
|
| 173 |
+
total_loss += loss.item()
|
| 174 |
+
n += 1
|
| 175 |
+
if n >= 20:
|
| 176 |
+
break
|
| 177 |
+
model.train()
|
| 178 |
+
return total_loss / n
|
| 179 |
+
|
| 180 |
+
def train_model(name, model):
|
| 181 |
+
model = model.to(DEVICE)
|
| 182 |
+
params = count_params(model)
|
| 183 |
+
print("\n%s: %d params (%.2fM), %d layers" % (name, params, params/1e6, model.n_layers), flush=True)
|
| 184 |
+
|
| 185 |
+
opt = torch.optim.AdamW(model.parameters(), lr=LR)
|
| 186 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, N_STEPS)
|
| 187 |
+
|
| 188 |
+
losses = []
|
| 189 |
+
val_losses = []
|
| 190 |
+
step = 0
|
| 191 |
+
t0 = time.perf_counter()
|
| 192 |
+
|
| 193 |
+
while step < N_STEPS:
|
| 194 |
+
for xb, yb in train_dl:
|
| 195 |
+
if step >= N_STEPS:
|
| 196 |
+
break
|
| 197 |
+
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
|
| 198 |
+
logits = model(xb)
|
| 199 |
+
loss = F.cross_entropy(logits.view(-1, VOCAB), yb.view(-1))
|
| 200 |
+
opt.zero_grad()
|
| 201 |
+
loss.backward()
|
| 202 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 203 |
+
opt.step()
|
| 204 |
+
scheduler.step()
|
| 205 |
+
losses.append(loss.item())
|
| 206 |
+
step += 1
|
| 207 |
+
|
| 208 |
+
if step % EVAL_EVERY == 0:
|
| 209 |
+
vl = evaluate(model, val_dl)
|
| 210 |
+
val_losses.append((step, vl))
|
| 211 |
+
elapsed = time.perf_counter() - t0
|
| 212 |
+
print(" step %d/%d: train=%.4f val=%.4f (%.0fs)" % (
|
| 213 |
+
step, N_STEPS, np.mean(losses[-100:]), vl, elapsed), flush=True)
|
| 214 |
+
|
| 215 |
+
# Final eval
|
| 216 |
+
vl = evaluate(model, val_dl)
|
| 217 |
+
val_losses.append((step, vl))
|
| 218 |
+
elapsed = time.perf_counter() - t0
|
| 219 |
+
print(" FINAL: val=%.4f, %.0fs, %.1f steps/s" % (vl, elapsed, N_STEPS/elapsed), flush=True)
|
| 220 |
+
|
| 221 |
+
return {
|
| 222 |
+
"name": name,
|
| 223 |
+
"params": params,
|
| 224 |
+
"layers": model.n_layers,
|
| 225 |
+
"train_losses": losses,
|
| 226 |
+
"val_losses": val_losses,
|
| 227 |
+
"time": elapsed,
|
| 228 |
+
"final_val": vl,
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
# === Deep standard: SAME hidden, MORE params (2x layers = ~2x params) ===
|
| 232 |
+
HIDDEN_DEEP = HIDDEN # same width
|
| 233 |
+
HEADS_DEEP = HEADS # same heads
|
| 234 |
+
|
| 235 |
+
print("=" * 60, flush=True)
|
| 236 |
+
print("CHEBYSHEV vs STANDARD TRANSFORMER COMPARISON", flush=True)
|
| 237 |
+
print("=" * 60, flush=True)
|
| 238 |
+
print("Shallow: %d layers, hidden=%d, heads=%d" % (12, HIDDEN, HEADS), flush=True)
|
| 239 |
+
print("Deep: %d layers, hidden=%d, heads=%d" % (24, HIDDEN_DEEP, HEADS_DEEP), flush=True)
|
| 240 |
+
print("Steps: %d, Batch: %d, Seq: %d" % (N_STEPS, BATCH, SEQ_LEN), flush=True)
|
| 241 |
+
|
| 242 |
+
# Run all 3
|
| 243 |
+
results = []
|
| 244 |
+
|
| 245 |
+
# 1. Chebyshev shallow
|
| 246 |
+
model1 = ChebyshevTransformer(VOCAB, HIDDEN, HEADS, 12)
|
| 247 |
+
r1 = train_model("Chebyshev-12L", model1)
|
| 248 |
+
results.append(r1)
|
| 249 |
+
del model1
|
| 250 |
+
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
|
| 251 |
+
|
| 252 |
+
# 2. Standard shallow
|
| 253 |
+
model2 = StandardTransformer(VOCAB, HIDDEN, HEADS, 12)
|
| 254 |
+
r2 = train_model("Standard-12L", model2)
|
| 255 |
+
results.append(r2)
|
| 256 |
+
del model2
|
| 257 |
+
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
|
| 258 |
+
|
| 259 |
+
# 3. Standard deep (matched params)
|
| 260 |
+
model3 = StandardTransformer(VOCAB, HIDDEN_DEEP, HEADS_DEEP, 24)
|
| 261 |
+
r3 = train_model("Standard-24L", model3)
|
| 262 |
+
results.append(r3)
|
| 263 |
+
del model3
|
| 264 |
+
|
| 265 |
+
# === Summary ===
|
| 266 |
+
print("\n" + "=" * 60, flush=True)
|
| 267 |
+
print("RESULTS", flush=True)
|
| 268 |
+
print("=" * 60, flush=True)
|
| 269 |
+
print("%-20s %8s %6s %10s %10s" % ("Model", "Params", "Layers", "Final Val", "Time"), flush=True)
|
| 270 |
+
print("-" * 58, flush=True)
|
| 271 |
+
for r in results:
|
| 272 |
+
print("%-20s %8d %6d %10.4f %8.0fs" % (r["name"], r["params"], r["layers"], r["final_val"], r["time"]), flush=True)
|
| 273 |
+
|
| 274 |
+
# Convergence comparison: val loss at step 1000, 2500, 5000
|
| 275 |
+
print("\nConvergence:", flush=True)
|
| 276 |
+
print("%-20s %10s %10s %10s" % ("Model", "Step 1000", "Step 2500", "Step 5000"), flush=True)
|
| 277 |
+
print("-" * 52, flush=True)
|
| 278 |
+
for r in results:
|
| 279 |
+
vals = dict(r["val_losses"])
|
| 280 |
+
v1k = vals.get(1000, vals.get(750, "N/A"))
|
| 281 |
+
v25k = vals.get(2500, "N/A")
|
| 282 |
+
v5k = vals.get(5000, vals.get(4750, "N/A"))
|
| 283 |
+
print("%-20s %10s %10s %10s" % (
|
| 284 |
+
r["name"],
|
| 285 |
+
"%.4f" % v1k if isinstance(v1k, float) else v1k,
|
| 286 |
+
"%.4f" % v25k if isinstance(v25k, float) else v25k,
|
| 287 |
+
"%.4f" % v5k if isinstance(v5k, float) else v5k,
|
| 288 |
+
), flush=True)
|
| 289 |
+
|
| 290 |
+
# Save results
|
| 291 |
+
save = {r["name"]: {"val_losses": r["val_losses"], "params": r["params"],
|
| 292 |
+
"final_val": r["final_val"], "time": r["time"]} for r in results}
|
| 293 |
+
with open("/tmp/donkey_cheb_train_results.json", "w") as f:
|
| 294 |
+
json.dump(save, f, indent=2)
|
| 295 |
+
print("\nSaved to /tmp/donkey_cheb_train_results.json", flush=True)
|