SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2303.09266 · IJCAI · 2023

SmartBERT: A Promotion of Dynamic Early Exiting Mechanism for Accelerating BERT Inference

Siliang Tang, Yun Zhu, Jiacheng Li, Boren Hu

arXiv · PDF · Open in the Atlas

Code that ran

3 of 4 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (3 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; 0 failures of our instrument; 1 no recorded run), measured 2026-11-22; 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/2303.09266.json · badge: /api/ran/2303.09266.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
HuBoren99/SmartBert community
Papers with Code archive
3 ran · 1 no recorded run
FunctionStatusWhere it lives
Classifier Ran
ran on a synthesized input · constructed an object; no result was computed
HuBoren99/SmartBert/models/SmartBert.py
code served (permissive licence) · get_code("fed1284fadbf8d3b")
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, Classifier: 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 minimal config object that has the attributes used in Classifier
class MinimalConfig:
    def __init__(self):
        self.hidden_size = 128
        self.attention_probs_dropout_prob = 0.1

config = MinimalConfig()

# Parameters for Classifier.__init__
num_labels = 5
cur_layer = 0  # This parameter is not used in the class, but we need to provide it
cla_heads_num = 4
cla_hidden_size = 128

# Create classifier instance to understand dimensions
classifier = nn.Module()  # placeholder

# For forward pass, we need:
# - hidden: tensor of shape (batch_size, seq_length, hidden_size)
# - mask: attention mask (can be None or tensor)
# - is_contrast: boolean flag

batch_size = 2
seq_length = 3
hidden_size = config.hidden_size

# Create sample tensors
hidden = torch.randn(batch_size, seq_length, hidden_size)

# Create attention mask - should be broadcastable to attention scores
# Attention scores have shape (batch, num_heads, seq_len, seq_len)
# So mask should be compatible, typically (batch, 1, 1, seq_len) or (batch, 1, seq_len, seq_len)
mask = torch.zeros(batch_size, 1, 1, seq_length)

is_contrast = False

ARGS = {
    'config': config,
    'num_labels': num_labels,
    'cur_layer': cur_layer,
    'cla_heads_num': cla_heads_num,
    'cla_hidden_size': cla_hidden_size,
}

# Store the forward pass arguments separately for reference
FORWARD_ARGS = {
    'hidden': hidden,
    'mask': mask,
    'is_contrast': is_contrast,
}
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 Classifier — 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 Classifier 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
Gate Ran
ran on a synthesized input · constructed an object; no result was computed
HuBoren99/SmartBert/models/SmartBert.py
code served (permissive licence) · get_code("1defd31ecb5dc519")
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, Gate: 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)

class MultiheadAttention(nn.Module):

    def __init__(self, hidden_size, num_attention_heads, dropout, output_attentions=False):
        super(MultiheadAttention, self).__init__()
        if hidden_size % num_attention_heads != 0:
            raise ValueError('The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (hidden_size, num_attention_heads))
        self.output_attentions = output_attentions
        self.num_attention_heads = num_attention_heads
        self.attention_head_size = int(hidden_size / num_attention_heads)
        self.all_head_size = self.num_attention_heads * self.attention_head_size
        self.query = nn.Linear(hidden_size, self.all_head_size)
        self.key = nn.Linear(hidden_size, self.all_head_size)
        self.value = nn.Linear(hidden_size, self.all_head_size)
        self.dropout = nn.Dropout(dropout)

    def transpose_for_scores(self, x):
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None):
        mixed_query_layer = self.query(hidden_states)
        if encoder_hidden_states is not None:
            mixed_key_layer = self.key(encoder_hidden_states)
            mixed_value_layer = self.value(encoder_hidden_states)
            attention_mask = encoder_attention_mask
        else:
            mixed_key_layer = self.key(hidden_states)
            mixed_value_layer = self.value(hidden_states)
        query_layer = self.transpose_for_scores(mixed_query_layer)
        key_layer = self.transpose_for_scores(mixed_key_layer)
        value_layer = self.transpose_for_scores(mixed_value_layer)
        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        if attention_mask is not None:
            attention_scores = attention_scores + attention_mask
        attention_probs = nn.Softmax(dim=-1)(attention_scores)
        attention_probs = self.dropout(attention_probs)
        if head_mask is not None:
            attention_probs = attention_probs * head_mask
        context_layer = torch.matmul(attention_probs, value_layer)
        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(*new_context_layer_shape)
        outputs = (context_layer, attention_probs) if self.output_attentions else (context_layer,)
        return outputs

class Gate(nn.Module):

    def __init__(self, config, cla_hidden_size=128, cla_heads_num=2):
        super(Gate, self).__init__()
        self.input_size = config.hidden_size
        self.num_label = 1
        self.cla_hidden_size = cla_hidden_size
        self.cla_heads_num = cla_heads_num
        self.output_layer_0 = nn.Linear(self.input_size, self.cla_hidden_size)
        self.atten = MultiheadAttention(self.cla_hidden_size, self.cla_heads_num, config.attention_probs_dropout_prob)
        self.output_layer_1 = nn.Linear(self.cla_hidden_size, self.num_label)

    def forward(self, hidden, mask):
        hidden = torch.tanh(self.output_layer_0(hidden))
        hidden = self.atten(hidden, mask)[0]
        hidden = hidden[:, 0, :]
        logits = self.output_layer_1(hidden)
        probs = torch.sigmoid(logits)
        return probs

class ConfigStandIn:
    def __init__(self, hidden_size=4, attention_probs_dropout_prob=0.1):
        self.hidden_size = hidden_size
        self.attention_probs_dropout_prob = attention_probs_dropout_prob

config = ConfigStandIn(hidden_size=4, attention_probs_dropout_prob=0.1)

hidden = torch.randn(2, 3, 4)
mask = torch.zeros(2, 1, 1, 3)

ARGS = {
    'config': config,
    'cla_hidden_size': 128,
    'cla_heads_num': 2
}
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 Gate — 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 Gate 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 · constructed an object; no result was computed
HuBoren99/SmartBert/models/SmartBert.py
code served (permissive licence) · get_code("a55fea32788cd568")
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, MultiheadAttention: 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)

# Set up the arguments for MultiheadAttention
hidden_size = 8
num_attention_heads = 2
dropout = 0.1
output_attentions = True

# Create the model
model = nn.Module()

# Create sample inputs
batch_size = 2
seq_length = 4
hidden_states = torch.randn(batch_size, seq_length, hidden_size)

# Create attention mask (optional)
attention_mask = torch.zeros(batch_size, 1, 1, seq_length)

# Create head mask (optional)
head_mask = torch.ones(num_attention_heads)

# Create encoder hidden states (optional, for cross-attention)
encoder_hidden_states = torch.randn(batch_size, seq_length, hidden_size)

# Create encoder attention mask (optional)
encoder_attention_mask = torch.zeros(batch_size, 1, 1, seq_length)

ARGS = {
    'hidden_size': hidden_size,
    'num_attention_heads': num_attention_heads,
    'dropout': dropout,
    'output_attentions': output_attentions,
}
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 MultiheadAttention — 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 MultiheadAttention 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
SmartBert Not yet run
unverified (harvested, no recorded run)
HuBoren99/SmartBert/models/SmartBert.py
code served (permissive licence) · get_code("364b3b24f4ef4ec8")
How it ran

no invocation recorded.

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 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 4 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

Dynamic early exiting has been proven to improve the inference speed of the pre-trained language model like BERT. However, all samples must go through all consecutive layers before early exiting and more complex samples usually go through more layers, which still exists redundant computation. In this paper, we propose a novel dynamic early exiting combined with layer skipping for BERT inference named SmartBERT, which adds a skipping gate and an exiting operator into each layer of BERT. SmartBERT can adaptively skip some layers and adaptively choose whether to exit. Besides, we propose cross-layer contrastive learning and combine it into our training phases to boost the intermediate layers and classifiers which would be beneficial for early exiting. To keep the consistent usage of skipping gates between training and inference phases, we propose a hard weight mechanism during training phase. We conduct experiments on eight classification datasets of the GLUE benchmark. Experimental results show that SmartBERT achieves 2-3× computation reduction with minimal accuracy drops compared with BERT and our method outperforms previous methods in both efficiency and accuracy. Moreover, in some complex datasets like RTE and WNLI, we prove that the early exiting based on entropy hardly works, and the skipping mechanism is essential for reducing computation. Our codes are available at: https://github.com/HuBoren99/SmartBert.

For agents

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

get_harvested_code_for_paper("2303.09266")
get_code_for_paper("2303.09266")
have("2303.09266")

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

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

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

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

Connect an agent — have() is free.