SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2004.08249 · EMNLP · 2020

Understanding the Difficulty of Training Transformers

Jianfeng Gao, Jiawei Han, Weizhu Chen, Xiaodong Liu, Liyuan Liu

arXiv · PDF · Open in the Atlas

Code that ran

4 of 5 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 1 failure of our instrument; 1 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2004.08249.json · badge: /api/ran/2004.08249.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
c00k1ez/plain-transformers community
Papers with Code archive
3 ran · 1 no recorded run
LiyuanLucasLiu/Transforemr-Clinic marked official in Papers with Code
Papers with Code archive
1 ran · 0 no recorded run
FunctionStatusWhere it lives
FFN Ran
ran on a synthesized input · constructed an object; no result was computed
c00k1ez/plain-transformers/src/plain_transformers/layers/pre_ln_encoder.py
code served (permissive licence) · get_code("2378be1d254fb13c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, FFN: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)

# Construct minimal valid arguments for FFN
ARGS = {
    'd_model': 8,
    'dim_feedforward': 16,
    'dropout': 0.1,
    'activation_name': 'gelu'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type FFN — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a FFN output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
MultiHeadAttention Ran
ran on a synthesized input
c00k1ez/plain-transformers/src/plain_transformers/layers/pre_ln_encoder.py
code served (permissive licence) · get_code("d3e534b847d15575")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

INIT_ARGS = {
    'd_model': 8,
    'n_heads': 2,
    'dropout': 0.1,
    'query_input_dim': 4,
    'key_input_dim': 5,
    'value_input_dim': 6,
    'context_len': None,
}

ARGS = {
    'query': torch.randn(2, 3, 4),
    'key': torch.randn(2, 7, 5),
    'value': torch.randn(2, 7, 6),
    'attention_mask': None,
    'get_attention_scores': False,
}

if __name__ == '__main__':
    from typing import Optional, Tuple, Union
    import torch.nn.functional as F

    class MultiHeadAttention(nn.Module):

        def __init__(self, d_model: int, n_heads: int, dropout: Optional[float]=0.1, query_input_dim: Optional[int]=None, key_input_dim: Optional[int]=None, value_input_dim: Optional[int]=None, context_len: Optional[int]=None) -> None:
            super(MultiHeadAttention, self).__init__()
            assert d_model % n_heads == 0
            self.d_model = d_model
            self.n_heads = n_heads
            self.hidden_per_head = d_model // n_heads
            self.scale = self.hidden_per_head ** 0.5
            self.query_input_dim = d_model if query_input_dim is None else query_input_dim
            self.key_input_dim = d_model if key_input_dim is None else key_input_dim
            self.value_input_dim = d_model if value_input_dim is None else value_input_dim
            self.key_projection = nn.Linear(self.key_input_dim, d_model)
            self.query_projection = nn.Linear(self.query_input_dim, d_model)
            self.value_projection = nn.Linear(self.value_input_dim, d_model)
            self.dropout = nn.Dropout(dropout)
            self.attn_type = 'encoder'
            if context_len is not None:
                self.attn_type = 'decoder'
                self.register_buffer('masked_val', torch.FloatTensor([-10000.0]))
                self.register_buffer('tri_mask', torch.tril(torch.ones((context_len, context_len), dtype=torch.uint8)).view(1, 1, context_len, context_len))
            else:
                self.register_buffer('masked_val', None)
                self.register_buffer('tri_mask', None)

        def _transpose_to_heads(self, x: torch.Tensor) -> torch.Tensor:
            new_shape = x.shape[:-1] + (self.n_heads, self.hidden_per_head)
            x = x.view(*new_shape)
            return x.permute(0, 2, 1, 3)

        def _generate_decoder_self_attn_mask(self, q_seq_len: int, k_seq_len: int) -> torch.Tensor:
            if self.training:
                attn_mask = self.tri_mask[:, :, k_seq_len - q_seq_len:k_seq_len, :k_seq_len]
            else:
                attn_mask = torch.ones((1, 1, k_seq_len, k_seq_len)).type_as(self.tri_mask)
            return attn_mask

        def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor]=None, get_attention_scores: Optional[bool]=False) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
            query_proj = self.query_projection(query)
            key_proj = self.key_projection(key)
            value_proj = self.value_projection(value)
            query_proj = self._transpose_to_heads(query_proj)
            key_proj = self._transpose_to_heads(key_proj)
            value_proj = self._transpose_to_heads(value_proj)
            raw_scores = torch.matmul(query_proj, key_proj.transpose(-1, -2))
            if self.attn_type == 'decoder':
                decoder_attn_mask = self._generate_decoder_self_attn_mask(key_proj.shape[2], key_proj.shape[2])
                raw_scores = torch.where(decoder_attn_mask.bool(), raw_scores, self.masked_val.to(raw_scores.dtype))
            if attention_mask is not None:
                raw_scores = raw_scores + attention_mask
            attn_scores = F.softmax(raw_scores / self.scale, dim=-1)
            attn = torch.matmul(attn_scores, value_proj)
            attn = attn.permute(0, 2, 1, 3).contiguous()
            new_shape = attn.shape[:-2] + (self.d_model,)
            attn = attn.view(*new_shape)
            output = (attn,)
            if get_attention_scores:
                output = output + (attn_scores,)
            return output

    model = MultiHeadAttention(**INIT_ARGS)
    result = model(**ARGS)
    print("Output shape:", result[0].shape)
    print("Success!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
RAdam Ran
ran on a synthesized input · constructed an object; no result was computed
LiyuanLucasLiu/Transforemr-Clinic/radam_fairseq/radam.py
code served (permissive licence) · get_code("b8547574c067ca6c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, RAdam: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import math

torch.manual_seed(0)

# Create a simple model with parameters
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.linear1 = nn.Linear(4, 3)
        self.linear2 = nn.Linear(3, 2)
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        return x

model = SimpleModel()

# Create model parameters list
params = model.parameters()

# Set up gradients for the parameters (required for the optimizer to work)
for param in model.parameters():
    param.grad = torch.randn_like(param)

ARGS = {
    'params': params,
    'lr': 0.001,
    'betas': (0.9, 0.999),
    'eps': 1e-08,
    'weight_decay': 0,
    'amsgrad': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type RAdam — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a RAdam output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
act_to_func Ran
ran; our contract draft was wrong, not the code
c00k1ez/plain-transformers/src/plain_transformers/layers/pre_ln_encoder.py
code served (permissive licence) · get_code("fc0804364f10665a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned builtin_function_or_method. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn.functional as F

torch.manual_seed(0)

# The function act_to_func takes a single parameter: act_name (a string)
# It maps activation function names to their corresponding torch.nn.functional implementations
# The function returns a Callable (the activation function)

# Test with a valid activation name
ARGS = {
    'act_name': 'gelu'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type builtin_function_or_method — a builtin_function_or_method output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a builtin_function_or_method output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
PreLNEncoderLayer Not yet run
unverified (harvested, no recorded run)
c00k1ez/plain-transformers/src/plain_transformers/layers/pre_ln_encoder.py
code served (permissive licence) · get_code("5f94447ee64fb0d9")
How it ran

no invocation recorded.

Also present in other papers' code

Of 5 samples lifted from this paper's linked repositories, 5 carry a function identity and 0 do not. Of the 5 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 5 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Transformers have proved effective in many NLP tasks. However, their training requires non-trivial efforts regarding carefully designing cutting-edge optimizers and learning rate schedulers (e.g., conventional SGD fails to train Transformers effectively). Our objective here is to understand what complicates Transformer training from both empirical and theoretical perspectives. Our analysis reveals that unbalanced gradients are not the root cause of the instability of training. Instead, we identify an amplification effect that influences training substantially-for each layer in a multi-layer Transformer model, heavy dependency on its residual branch makes training unstable, since it amplifies small parameter perturbations (e.g., parameter updates) and results in significant disturbances in the model output. Yet we observe that a light dependency limits the model potential and leads to inferior trained models. Inspired by our analysis, we propose Admin (Adaptive model initialization) to stabilize the early stage's training and unleash its full potential in the late stage. Extensive experiments show that Admin is more stable, converges faster, and leads to better performance 1 .

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2004.08249")
get_code_for_paper("2004.08249")
have("2004.08249")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2004.08249.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2004.08249.svg)](https://syntology.ai/paper/2004.08249)

Connect an agent — have() is free.