paper_id
string | url
string | title
string | authors
string | published
string | abstract
string | introduction
string | background
string | related work
string | literature review
string | problem statement
string | research questions
string | objectives
string | hypothesis
string | theoretical framework
string | methodology
string | methods
string | experimental setup
string | data collection
string | data analysis
string | results
string | findings
string | discussion
string | interpretation
string | implications
string | limitations
string | future work
string | conclusion
string | summary
string | acknowledgments
string | references
string | appendix
string | supplementary material
string | author contributions
string | funding
string | conflict of interest
string | ethical considerations
string | data availability
string | code availability
string | abbreviations
string | glossary
string | list of figures
string | list of tables
string | materials and methods
string | theoretical analysis
string | computational details
string | statistical analysis
string | model architecture
string | algorithm description
string | performance evaluation
string | ablation studies
string | case studies
string | user study
string | comparative analysis
string | system design
string | implementation details
string | experimental results
string | qualitative analysis
string | quantitative analysis
string | proof of concept
string | theoretical proofs
string | simulation results
string | real-world experiments
string |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2407.18248v1 | http://arxiv.org/pdf/2407.18248v1 | Self-Training with Direct Preference Optimization Improves Chain-of-Thought Reasoning | Tianduo Wang, Shichen Li, Wei Lu | 2024-07-25 | Abstract
Effective training of language models (LMs)
for mathematical reasoning tasks demands
high-quality supervised fine-tuning data. Be-
sides obtaining annotations from human ex-
perts, a common alternative is sampling from
larger and more powerful LMs. However,
this knowledge distillation approach can be
costly and unstable, particularly when relying
on closed-source, proprietary LMs like GPT-
4 (OpenAI, 2023), whose behaviors are often
unpredictable. In this work, we demonstrate
that the reasoning abilities of small-scale LMs
can be enhanced through self-training, a pro-
cess where models learn from their own outputs.
We also show that the conventional self-training
can be further augmented by a preference learn-
ing algorithm called Direct Preference Opti-
mization (DPO) (Rafailov et al., 2023). By
integrating DPO into self-training, we leverage
preference data to guide LMs towards more ac-
curate and diverse chain-of-thought reasoning.
We evaluate our method across various math-
ematical reasoning tasks using different base
models. Our experiments show that this ap-
proach not only improves LMs’ reasoning per-
formance but also offers a more cost-effective
and scalable solution compared to relying on
large proprietary LMs.
1 | Introduction
Making language models (LMs) perform math-
ematical reasoning is a valuable, yet challeng-
ing research objective (Hendrycks et al., 2021;
Cobbe et al., 2021). Recent efforts have focused
on enhancing large-scale LMs’ reasoning abili-
ties through various methods, including chain-of-
thought prompting (Wei et al., 2022b; Kojima et al.,
2022), continual pretraining (Azerbayev et al.,
2024), and adding external verifiersq (Li et al.,
2023b). However, the research question of how
to enhance the reasoning capabilities of smaller-
sized LMs remains relatively under-explored.
1e+18 3e+18 1e+19 3e+19 1e+20
Compute Cost (FLOPs)152025303540Accuracy (%)Flan-T5-L
(Ours)
Flan-T5-LFlan-T5-3BFlan-T5-11B
T5-LT5-3BT5-11B
T5-LT5-3BGSM8K Performance v.s. Compute cost
Codex distillation
(Fu et al., 2023)
PaLM distillation
(Magister et al., 2023)
Calcformer
(Kadl ík et al., 2023)
Figure 1: Our approach demonstrates superior perfor-
mance on the GSM8K benchmark while minimizing
the required compute cost, including both training and
inference. Compute cost calculations are based on the
methodology outlined by Yuan et al. (2023).1
Recent studies (Fu et al., 2023; Magister et al.,
2023; Li et al., 2023a) demonstrate that the rea-
soning capabilities of smaller LMs can be signif-
icantly enhanced through learning from the out-
puts of larger and more advanced LMs, such as
Codex (Chen et al., 2021), PaLM (Chowdhery
et al., 2022), and GPT-4 (OpenAI, 2023). While
this method is straightforward to implement, the
associated costs can be substantial. The computa-
tional demand, measured in floating-point opera-
tions (FLOPs), increases considerably when using
large LMs. Additionally, the reliance on propri-
etary large LMs for data annotation not only incurs
high economic costs but also raises concerns re-
garding the sustainability and scalability of such
practices. For instance, Ho et al. (2023) highlighted
that while employing large LMs as annotators can
largely enhance the performance of smaller LMs,
it introduces a clear trade-off between economic
costs and performance gains.
1All methods presented here are integrated with an external
calculator except for the Codex distillation by Fu et al. (2023).arXiv:2407.18248v1 [cs.CL] 25 Jul 2024
Another line of research focuses on explor-
ing enhancements through self-improvement meth-
ods (Zelikman et al., 2022; Gulcehre et al., 2023;
Singh et al., 2023). These methods diverge from
using outputs from larger models, instead encour-
aging LMs to learn from their own generated data.
The effectiveness of these techniques is evident,
yet their success largely depends upon the inher-
ent capabilities of the base models. For example,
Zelikman et al. (2022) initiated self-improvement
by few-shot prompting GPT-J (Wang and Ko-
matsuzaki, 2021), a relatively large LM which
has 6 billion parameters, to generate rationales –
an emergent ability typically reserved for large
models (Wei et al., 2022a). However, the ex-
tent to which small-scale LMs can gain from self-
improvement remains uncertain.
In this work, we introduce a novel enhance-
ment to the conventional self-training framework
by incorporating Direct Preference Optimization
(DPO) (Rafailov et al., 2023). This integration
specifically targets performance objectives within
chain-of-thought reasoning, with a particular focus
on mathematical reasoning. The clear-cut nature
of mathematical solutions enables straightforward
validation of a model’s outputs, facilitating the cre-
ation of a preference dataset for DPO. Our em-
pirical results indicate that this method notably en-
hances the reasoning capabilities of LMs while also
reducing computational overhead. We visualize the
relationship between the GSM8K (Cobbe et al.,
2021) performance and computational cost across
various specialized models in Figure 1. It can be
observed that our method not only achieves strong
performance, but also reduces computational de-
mands by effectively utilizing self-generated data
for learning. Overall, the main contribution of this
work can be summarized as follows:
•We propose a novel extension to the classic
self-training framework by integrating Direct
Preference Optimization, demonstrating its ef-
fectiveness across various math reasoning tasks.
•Our method significantly enhances the reason-
ing abilities of language models while requiring
minimal computational resources, optimizing
both performance and efficiency.
•We present an efficient method for integrating
LMs with external tools, which significantly
boosts downstream task performance without
notably compromising inference speed.Algorithm 1 Self-training for CoT reasoning tasks
Input: pre-trained language model fθ
Input: labeled dataset L={(xi, yi, ai)}l
i=1
Input: unlabeled dataset U={(xi, ai)}u
i=1
Output: fine-tuned model fθ′
1:Fine-tune fθonLto get fθ′
2:repeat
3: Build pseudo-labeled dataset S:
S={(xi,ˆyi,ˆai)}s
i=1
where xi∼ U andˆyi,ˆai∼fθ′(·|xi)
4: Select Sα⊂ S when ˆai=ai
5: Update L ← Sα∪ L
6: Train fθonLto get a new fθ′
7:until convergence or max iteration is reached
2 | Background
Math word problem solving The math word
problem solving task (Cobbe et al., 2021) can be
formulated as a sequence-to-sequence task where
the input xis a question asking for an unknown
value and the output yis a rationale that leads to the
answer a. Normally, the answers can be extracted
from the rationales via some rule-based methods,
such as regular expressions. A generated rationale
ˆyis regarded as correct if the extracted answer ˆa
matches the gold answer a. Formally, the labeled
dataset for a math word problem solving task with
linstances can be represented as:
L={(xi, yi, ai)}l
i=1. (1)
A common way for specializing a LM fθtowards
math reasoning with the labeled dataset Lissuper-
vised fine-tuning (SFT). It optimizes fθby mini-
mizing the negative log likelihood loss LSFT(θ):
E
(x,y)∼L−hTX
t=1logfθ(yt|x, y 1:t−1)i
, (2)
where Tis the length of the rationale yand we use
ytto represent the t-th token in y.
Self-training Self-training is one of the earliest
approaches in semi-supervised learning (Scudder,
1965; Fralick, 1967) that has risen in popularity
recently (He et al., 2020; Amini et al., 2022). This
method first regards a base model trained with a
labeled dataset Las teacher, and uses it to build
a pseudo-labeled dataset Sby annotating an unla-
beled dataset U. Then, a student model is trained
on a combination of LandSthat are expected to
outperform the teacher model. Such a framework
has been shown effective across a wide range of
natural language processing tasks, including natu-
ral language understanding (Vu et al., 2021) and
generation (He et al., 2020). A formal description
of a self-training algorithm for chain-of-thought
(CoT) reasoning tasks is provided in Algorithm 1.
Previous studies have demonstrated that the qual-
ity of the pseudo-labels largely impacts the over-
all performance of the self-training algorithm (He
et al., 2020; Amini et al., 2022). For example, Gul-
cehre et al. (2023) proposed to select high-quality
pseudo-labels with a learned reward function. Ze-
likman et al. (2022) filtered the generated ratio-
nales to include only the ones that lead to correct
answers. Although many methods are proposed
to select pseudo-labels, few works discuss how
to improve the fine-tuned model fθ′so that more
high-quality pseudo-labels can be generated. In
this paper, we present a method to enhance fθ′in
each iteration so that higher-quality pseudo-labeled
data can be generated.
Direct Preference Optimization The Rein-
forcement Learning from Human Feedback
(RLHF) methods align LMs with human prefer-
ence (Ouyang et al., 2022; Bai et al., 2022). The
standard pipeline of RLHF requires to first train a
reward model from human preference data. Then,
the reward model is used to fine-tune language
models via reinforcement learning objective, e.g.,
Proximal Policy Optimization (Schulman et al.,
2017). A recent study propose Direct Preference
Optimization (DPO) (Rafailov et al., 2023) to avoid
explicitly training a reward model so that language
models can be directly tuned with human prefer-
ence data.
The DPO pipeline can be described as follows.
First, given some prompt x, we sample several com-
pletions from the reference model πref(normally it
is the model after supervised fine-tuning):
y1, y2∼πref(· |x). (3)
Next, construct the DPO dataset Dfrom the com-
pletions based on the human preference:
D={(xi, yi
w, yi
l)}N
i=1, (4)
where yi
wandyi
lrepresent the winning and los-
ing completions respectively. Then, we optimize
the language model πθto minimize LDPO(πθ;πref)Algorithm 2 DPO-augmented self-training
Input: pre-trained language model fθ
Input: labeled dataset L={(xi, yi, ai)}l
i=1
Input: unlabeled dataset U={(xi, ai)}u
i=1
Output: fine-tuned model fθ′
# Warm-up stage
1:Fine-tune fθonLto get fθ′
2:repeat
# DPO step
3: Generate DPO dataset D:
D={(xi, yi
w, yi
l)}N
i=1
where xi∼ U andyi
w, yi
l∼fθ′(·|xi)
4: Tune fθ′withLDPOonDto get fθd
# SFT step
5: Build pseudo-labeled dataset S:
S={(xi,ˆyi,ˆai)}s
i=1
where xi∼ U andˆyi,ˆai∼fθd(·|xi)
6: Select Sα⊂ S when ˆai=ai
7: Update L ← Sα∪ L
8: Train fθonLto get a new fθ′
9:until convergence or max iteration is reached
which can be defined as follows:
E
(x,yw,yl)∼D
−logσ
r(yw|x)−r(yl|x)
, (5)
where r(·|x) =βlogπθ(·|x)
πref(·|x)andβis a coefficient
that controls πθ’s deviation from πref.
3 Method
In this section, we first describe the proposed ap-
proach. Then, we demonstrate how we integrate
an external calculator into the model’s decoding
process which significantly improves LMs’ perfor-
mance on the downstream tasks.
3.1 DPO-augmented Self-Training
Our approach starts with a warm-up stage , and
then followed by an iterative process, where each
iteration is composed of two sub-steps: DPO step
andSFT step . The iterative process ends when
the model performance converges or reaches the
maximum iteration. A formal description of the
proposed method is illustrated in Algorithm 2. An
illustration of our method is presented in Figure 2.
Warm-up stage Like classic self-training, we
start by fine-tuning the base model fθto optimize
LSFT(θ)on the labeled data L, resulting in an up-
dated model fθ′. After this stage, we assume that
Pre-trained model
SFT model
DPO modelSupervised fine-tuningDPO trainingSampling&filteringPseudo-labeled dataSFT dataDeduplication
SamplingPreference data
Human-labeled SFT data
Iteration nFigure 2: An illustration of the DPO-augmented Self-Training framework. Traditional self-training method uses
the SFT model to generate the pseudo-labels for subsequent iterations. In contrast, our method enhances the SFT
model with Direct Preference Optimization (DPO), using the optimized DPO model to produce the pseudo-labels.
fθ′is capable of solving certain math problems.
Specifically, given a math question x,fθ′will gen-
erate a rationale ˆywith answer ˆa.
Iterative step 1: DPO step In this step, we first
sample rationales ˆyfrom the fine-tuned model fθ′
given some questions xfromU. For each ques-
tionx, we generate multiple rationales to build the
DPO training dataset D. As mentioned, for math
problem solving tasks, it is easy to know whether a
generated rationale ˆycan be considered as correct.
We label rationales with correct answers as win-
ning completions, while consider rationales with
incorrect answers as losing completions. Then, we
trainfθ′onDto optimize the objective function
LDPOand get a DPO model fθdin the end.
Iterative step 2: SFT step After obtaining fθd,
we use it to generate a new pseudo-labeled dataset
Sfor the next-round supervised fine-tuning:
S={(x,ˆy)|x∼ U,ˆy∼fθd(·|x)} (6)
After generation, we clean Sby eliminating ra-
tionales with incorrect answers and removing du-
plicates. Therefore, the pseudo-labeled dataset we
obtained in the end is a subset of the original one,
i.e.,Sα⊂ S. The final training dataset is the com-
bination of the original labeled dataset Land the
newly-generated pseudo-labeled dataset Sα. No-
tice that during this process, once we collect a new
dataset, we train from the original base model fθ
instead of continually fine-tuning fθ′to avoid over-
fitting, following previous practice (Zelikman et al.,
2022; Singh et al., 2023).Q: James writes a 3-page letter to 2
different friends twice a week. How many
pages does he write a year?
A: He writes each friend
3*2=<<3*2=6>>6 pages a week.
So he writes
6*2=<<6*2=12>>12 pages every week.
That means he writes
12*52=<<12*52=624>>624 pages a year.
#### 624
Figure 3: An example from the GSM8K dataset. The
calculation annotations are highlighted in blue. All
calculation steps are wrapped within special tokens
<<...>> . During decoding, the calculator will be trig-
gered when such patterns exist and the model’s output
tokens will be overridden by the calculator results. Fol-
lowing Cobbe et al. (2021), the calculation is performed
with the in-built python function eval() .
3.2 Batch Decoding with Calculator
Empirical observations indicate that while large
LMs, such as those described in Brown et al.
(2020), demonstrate superior proficiency in basic
arithmetic calculations, smaller LMs like Flan-T5-
Large tend to struggle with similar arithmetic tasks.
This limitation significantly affects their perfor-
mance in math reasoning tasks. To address this,
various studies (Parisi et al., 2022; Schick et al.,
2023; Kadl ˇcík et al., 2023) have explored augment-
ing small-scale models with an external calculator
to boost their arithmetic capabilities. However,
many of these existing methods are limited to a
batch size of one during decoding. This constraint
substantially reduces the inference speed and limits
their practical application.
1 8 16 32
Batch Size05101520Speedup
1.0x5.8x9.5x13.9x
6.9x12.3x19.9xCalcformer
Ours w/ calculator
Ours w/o calculatorFigure 4: Inference speed comparison between
our methods (w/ and w/o calculator) and Cal-
cformer (Kadl ˇcík et al., 2023) with varying batch sizes.
The results are measured on a single NVIDIA A40 GPU.
To address this challenge, we propose a sim-
ple yet efficient method that allows for using
larger batch sizes during inference with an external
calculator. Our approach leverages the calcula-
tor annotations provided in the original GSM8K
dataset (Cobbe et al., 2021). Figure 3 demonstrates
an example of this annotation and describes how
such annotations can be used during decoding. For
optimal utilization of these annotations, we build
our models with the Transformers library (Wolf
et al., 2020). During inference, we employ a
customized LogitsProcessor2–available in the
Transformers documentation– to adjust the model’s
generation process. This LogitsProcessor acts as
an interface, allowing modifications to the outputs
of the model during generation and thereby en-
abling efficient management of larger batch sizes.
To demonstrate the efficiency of the proposed
solution, we compare the inference speed of our
methods (w/ and w/o calculator) based on Flan-T5-
Large against an open-source tool-using method,
Calcformer (Kadl ˇcík et al., 2023) based on T5-
Large, in Figure 4. We find that when the batch size
equals 1, all three methods have a similar inference
speed of around 40 tokens per second. However, as
the inference batch size increases, the speedup of
our methods increases significantly.
4 Experiments
In this section, we first outline our experiment setup
and implementation details, then present our mod-
els’ performance on various math reasoning tasks
against competitive baselines. Finally, we analyze
the effectiveness of our method empirically.
2https://huggingface.co/docs/transformers/
internal/generation_utils#logitsprocessorDataset Split # Data
GSM8K (Cobbe et al., 2021) Train 6,705
Validation 0,768
Test 1,319
MultiArith (Roy and Roth, 2015) Test 0,600
ASDiv (Miao et al., 2020) Test 2,096
SV AMP (Patel et al., 2021) Test 1,000
Table 1: Statistics of the datasets used in our experi-
ments. The original GSM8K dataset only contains train
and test split. We randomly select 768 training examples
to construct the validation dataset in our experiments.
4.1 Setup
Base models We employ Flan-T5 models (Chung
et al., 2024) as our primary base models. Specifi-
cally, we consider two variants from the Flan-T5
family: Flan-T5-Base and Flan-T5-Large. We se-
lect Flan-T5 over the original T5 models (Raffel
et al., 2019) as our backbone models based on
the evidence from previous research (Chung et al.,
2024; Fu et al., 2023), which demonstrates that
instruction-tuned models like Flan-T5 outperform
their pre-trained counterparts in mathematical rea-
soning tasks. To broaden our analysis, we also in-
clude Llama models (Touvron et al., 2023a,b; Meta,
2024) as additional base models for comparison.
Datasets The labeled dataset Lused in our exper-
iments comes from the training split of the GSM8K
dataset. Our unlabeled dataset Uis also built upon
GSM8K’s training data by removing its annotated
rationales. For evaluation, we consider three ad-
ditional commonly used math reasoning tasks be-
sides GSM8K: MultiArith, ASDiv, and SV AMP.
Table 1 provides the statistics information of each
dataset. Following previous practice (Fu et al.,
2023), we fine-tune our base models exclusively
on the GSM8K training data while utilizing the
rest three datasets to evaluate our models’ out-of-
domain performance as they do not have an official
in-domain training split.
4.2 Implementation Details
In the warm-up stage, we fine-tune the base models
on the training set of GSM8K (Cobbe et al., 2021)
with the original human-labeled annotations and
obtain the initial SFT model. For subsequent DPO
steps, we first sample rationales from SFT mod-
els to build the preference dataset. We sample 5
rationales per question with a temperature of 0.7.
Generated rationales ˆycontaining the correct an-
Method Base Model GSM8K MultiArith ASDiv SVAMP
Supervised Fine-Tuning Flan-T5-Base 18.1 54.2 26.2 19.5
Self-Training Flan-T5-Base 25.9 73.8 28.2 24.2
DPO-aug Self-Training ( Ours ) Flan-T5-Base 27.2 74.3 29.2 22.6
Supervised Fine-Tuning Flan-T5-Large 30.8 77.2 38.1 33.6
Self-Training Flan-T5-Large 35.6 86.2 42.5 34.8
DPO-aug Self-Training ( Ours ) Flan-T5-Large 37.4 89.0 42.8 36.8
Table 2: Overall accuracies (%) over four math word problem solving tasks. Inspired by the previous practice (Fu
et al., 2023), all the models in this table are only trained with the GSM8K training set (Cobbe et al., 2021). Hence,
we report the in-distribution performance for GSM8K, while reporting the out-of-distribution performance for the
other three datasets, i.e., MultiArith, ASDiv, and SV AMP.
swer are classified as winning ones yw, while the
rest are considered losing ones yl. We set β= 0.1
in the DPO learning objective LDPO. For the sub-
sequent SFT steps, we generate 3 rationales per
question from the DPO-tuned model fθd, also with
a temperature of 0.7. Only the correct generated
rationales ˆywill be selected to build the pseudo-
labeled dataset. For both DPO and SFT steps, we
perform simple deduplication based on the Jaccard
similarity scores with a threshold of 0.7. Addi-
tional implementation details can be found in Ap-
pendix A.
Baselines We mainly consider two baseline meth-
ods to compare with our method: Supervised Fine-
Tuning (SFT) and Self-Training (ST). The SFT
baseline corresponds to the model after the warm-
up stage. The Self-Training baseline adheres to the
procedure outlined in Algorithm 1. To ensure a fair
comparison between our proposed method and the
ST baseline, we use the same set of hyperparame-
ters for both methods at each iteration.
4.3 Main Results
Comparison with baselines Table 2 shows the
performance of our method compared with the
baselines using two base models, Flan-T5-Base
and Flan-T5-Large, across four datasets. The re-
sults clearly show that both the ST baseline and our
proposed DPO-augmented Self-Training method
outperform the SFT baseline by a large margin, in-
dicating the effectiveness of the self-training frame-
work in general. Although the ST baselines make
significant improvements over the SFT baselines,
our DPO-augmented Self-Training models demon-
strate enhanced performance on both in-domain
(GSM8K) and out-of-domain (MultiArith, ASDiv,
and SV AMP) tasks.
iter 0 iter 1 iter 2 iter 315.017.520.022.525.027.530.0Accuracy (%)18.124.226.0 25.9
18.124.626.627.2Flan-T5-Base
ST
Ours
iter 0 iter 1 iter 2 iter 33032343638Accuracy (%)
30.832.935.135.6
30.834.135.637.4Flan-T5-Large
ST
OursFigure 5: The performance of the proposed method on
GSM8K over three iterations. For “iter 0”, we report the
performance of the SFT baselines, which are obtained
after the warm-up stage.
Effect of iterative training Figure 5 demon-
strates the impact of iterative training on Flan-T5-
Base and Flan-T5-Large models, comparing our
method to the ST baseline. Initially, both meth-
ods start with a warm-up stage and have similar
accuracies at iteration 0. As training progresses,
our method consistently outperforms ST across it-
erations for both models. For Flan-T5-Base, the
accuracy improvement plateaus by iteration 3, sug-
gesting convergence. In contrast, Flan-T5-Large
shows a clear and steady improvement, with our
method achieving significantly higher accuracy by
iteration 3. This underscores the effectiveness of
our iterative training process, particularly in en-
hancing performance of larger models.
Method Base Model # Annotations Annotator Tools Acc.
Supervised fine-tuning
CoT (Shridhar et al., 2023) GPT-2-Large 007K Human % 14.1
Self-consistency (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 33.3
GRACE (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 36.3
Calcformer (Kadl ˇcík et al., 2023) T5-Large 030K Human ! 34.2
Knowledge Distillation
Socratic CoT (Shridhar et al., 2023) GPT-2-Large 007K GPT-3 175B % 21.1
CoT from CodeX (Fu et al., 2023) Flan-T5-Large 100K CodeX % 20.2
CoT from PaLM (Magister et al., 2023) T5-Large 006K PaLM 540B ! 22.2
Ours
DPO-aug Self-Training ( K=3) Flan-T5-Large 007K Human ! 37.4
DPO-aug Self-Training ( K=5) Flan-T5-Large 007K Human ! 39.1
DPO-aug Self-Training ( K=10) Flan-T5-Large 007K Human ! 40.0
Table 3: Detailed comparison among existing methods with comparable model sizes on the GSM8K test set. The
“Annotator” column indicates how the rationales of the training data are generated. In this column, “Human” refers
to the labels from the original GSM8K dataset (Cobbe et al., 2021) that are written by human annotators. The
“Tools” column indicates whether external calculators are applied during inference.
4.4 Comparison with Existing Methods
In this section, we compare our methods with ex-
isting approaches. To enhance our method, we
increase the number of sampled pseudo-labels per
question to build a more diverse and robust pseudo-
label dataset. We denote this hyperparameter as K
following Yuan et al. (2023).
Table 3 presents a detailed comparison be-
tween our method and exisiting methods using
a simialr base model size. The base models we
considered include GPT-2-Large (Radford et al.,
2019), T5-Large (Raffel et al., 2019), and Flan-
T5-Large (Chung et al., 2024), each with approx-
imately 770 million parameters. As shown in Ta-
ble 3, our approach not only outperforms other
methods on the GSM8K benchmark, but also
demonstrates remarkable label efficiency by ex-
clusively using the annotations from the original
GSM8K dataset.
In Table 4, we further evaluate the effectiveness
of the proposed method with the Llama model fam-
ily (Touvron et al., 2023a,b; Meta, 2024), compar-
ing it with several state-of-the-art closed-source
models as well as similarly sized open-source mod-
els. We observe a substantial performance gap be-
tween proprietary and open-source models. Among
the open-source models, those utilizing knowledge
distillation generally outperform their counterparts
without such enhancement. Notably, our models
using Llama-1-7b and Llama-2-7b base models
surpass other open-source alternatives that do not
employ knowledge distillation, achieving accura-cies of 44.7% and 54.7% respectively. Furthermore,
our model employing the latest Llama-3-8b (Meta,
2024) matches or exceeds the performance of ear-
lier models with knowledge distillation, demon-
strating a significant accuracy of 68.8%.
Method Base Model Acc.
Closed-source models
Claude-3-Opus (Anthropic, 2024) - 95.0
Claude-2 (Anthropic, 2023) - 88.0
GPT-4 (OpenAI, 2023) - 92.0
Flan-PaLM-2 (Anil et al., 2023) - 84.7
Open-source models w/ knowledge distillation
MAmooTH (Yue et al., 2023)♡Llama-2-7b 53.6
LEMA (An et al., 2023) Llama-2-7b 54.1
WizardMath (Luo et al., 2023) Llama-2-7b 54.9
MetaMath (Yu et al., 2024) Llama-2-7b 66.5
MuggleMath (Li et al., 2023a) Llama-2-7b 68.4
ToRA (Gou et al., 2024)♡Llama-2-7b 68.8
Open-source models w/o knowledge distillation
SFT (Yuan et al., 2023) Llama-1-7b 35.9
SFT w/ Calculator♡Llama-1-7b 40.0
RFT ( K=100) (Yuan et al., 2023) Llama-1-7b 41.7
SFT (Yuan et al., 2023) Llama-2-7b 41.6
SFT w/ Calculator♡Llama-2-7b 45.1
RFT ( K=100) (Yuan et al., 2023) Llama-2-7b 47.5
SFT w/ Calculator♡Llama-3-8b 61.0
Ours
DPO-ST ( K=10)♡Llama-1-7b 44.7
DPO-ST ( K=10)♡Llama-2-7b 54.7
DPO-ST ( K=10)♡Llama-3-8b 68.8
Table 4: Comparison with the state-of-the-art pro-
prietary models and Llama-based open-source mod-
els (Touvron et al., 2023a,b; Meta, 2024).♡: models
augmented with external tools.
30333639Dev accuracy (%)36.136.5Pass@1
60626466Dev accuracy (%)62.964.8Pass@10
240027003000
24952940# generated
CoT pseudo-labels
Before DPO step After DPO stepFigure 6: Effects of the DPO step. Left: we report
the greedy decoding results for Pass@1. Middle: For
Pass@10, the solutions are sampled with temperature
0.7.Right: We count the number of generated pseudo-
labels after deduplication.
4.5 Effects of the DPO Step
As mentioned earlier, the main difference between
the proposed method and the classic self-training
is the DPO step in every iterative process. We now
analyze how the DPO steps improve self-training.
Figure 6 compares the performance of models be-
fore and after the DPO step in the first iteration on
the Pass@K metrics. Pass@K measures the proba-
bility that at least one of the Kgenerated solutions
for a problem is correct, which serves as a gauge
for both the quality and the variety of the model-
generated solutions. The models we investigate
here are fine-tuned from the Flan-T5-Large.
As shown in Figure 6, the DPO step yields only
marginal improvements over the SFT model in the
Pass@1 performance on the development set. How-
ever, the performance significantly improves when
multiple rationales, i.e., 10 solutions per question,
are sampled with temperature 0.7 (measured with
the Pass@10 metric). This indicates that the DPO
training objective makes language models inclined
to generate rationales of both high quality and di-
versity. We also compare the number of generated
rationales on the training set Lfor models with
and without the DPO step. Figure 6 (right) clearly
shows that the model after the DPO step can pro-
duce more SFT data for the next iteration.
4.6 Effects of External Calculator
Driven by the observation that small-scale LMs
frequently make basic calculation errors, we de-
velop a simple yet efficient method that integrates
an external calculator into the models’ decoding
process. To evaluate the impact of this integration,
iter 0 iter 1 iter 2 iter 31020304050Dev accuracy (%)36.740.543.944.8
16.317.117.8 18.0w/ calculator
w/o calculatorFigure 7: GSM8K development set accuracy of Flan-
T5-Large with and without the use of an external calcu-
lator during inference.
we conduct an ablation study by omitting the cal-
culator and present the findings in Figure 7. Our
results indicate that decoding without the calcula-
tor markedly reduces accuracy across all iterations.
We believe that this is because models will generate
large amount of false positive pseudo-labels with-
out calculator, that is, the generated pseudo-labels
may have correct final answers but make errors in
the intermediate reasoning steps.
5 | Related Work
Learning from pseudo-labels Supervised fine-
tuning (SFT) is prevalent technique employed to
enhance the performance of pre-trained language
models on specific downstream tasks (Ouyang
et al., 2022; Chung et al., 2024). However, this
method heavily depends on the availability of high-
quality labeled data, which can be both expensive
and labor-intensive to procure (Brown et al., 2020).
To address this limitation, various strategies have
been developed to generate high-quality pseudo-
labels using either unlabeled or synthetic data for
a wide range of applications, including text clas-
sification (Xie et al., 2020), sentence representa-
tion learning (Wang and Lu, 2022), instruction
tuning (Honovich et al., 2022), and math reason-
ing (Wang and Lu, 2023). Recent advancements
in this area primarily focus on two directions: self-
training and knowledge distillation. The key dif-
ference between these | Section not found | Section not found | Section not found | objectives within
chain-of-thought reasoning, with a particular focus
on mathematical reasoning. The clear-cut nature
of mathematical solutions enables straightforward
validation of a model’s outputs, facilitating the cre-
ation of a preference dataset for DPO. Our em-
pirical results indicate that this method notably en-
hances the reasoning capabilities of LMs while also
reducing computational overhead. We visualize the
relationship between the GSM8K (Cobbe et al.,
2021) performance and computational cost across
various specialized models in Figure 1. It can be
observed that our method not only achieves strong
performance, but also reduces computational de-
mands by effectively utilizing self-generated data
for learning. Overall, the main contribution of this
work can be summarized as follows:
•We propose a novel extension to the classic
self-training framework by integrating Direct
Preference Optimization, demonstrating its ef-
fectiveness across various math reasoning tasks.
•Our method significantly enhances the reason-
ing abilities of language models while requiring
minimal computational resources, optimizing
both performance and efficiency.
•We present an efficient method for integrating
LMs with external tools, which significantly
boosts downstream task performance without
notably compromising inference speed.Algorithm 1 Self-training for CoT reasoning tasks
Input: pre-trained language model fθ
Input: labeled dataset L={(xi, yi, ai)}l
i=1
Input: unlabeled dataset U={(xi, ai)}u
i=1
Output: fine-tuned model fθ′
1:Fine-tune fθonLto get fθ′
2:repeat
3: Build pseudo-labeled dataset S:
S={(xi,ˆyi,ˆai)}s
i=1
where xi∼ U andˆyi,ˆai∼fθ′(·|xi)
4: Select Sα⊂ S when ˆai=ai
5: Update L ← Sα∪ L
6: Train fθonLto get a new fθ′
7:until convergence or max iteration is reached
2 Background
Math word problem solving The math word
problem solving task (Cobbe et al., 2021) can be
formulated as a sequence-to-sequence task where
the input xis a question asking for an unknown
value and the output yis a rationale that leads to the
answer a. Normally, the answers can be extracted
from the rationales via some rule-based | Section not found | Section not found | methodology outlined by Yuan et al. (2023).1
Recent studies (Fu et al., 2023; Magister et al.,
2023; Li et al., 2023a) demonstrate that the rea-
soning capabilities of smaller LMs can be signif-
icantly enhanced through learning from the out-
puts of larger and more advanced LMs, such as
Codex (Chen et al., 2021), PaLM (Chowdhery
et al., 2022), and GPT-4 (OpenAI, 2023). While
this method is straightforward to implement, the
associated costs can be substantial. The computa-
tional demand, measured in floating-point opera-
tions (FLOPs), increases considerably when using
large LMs. Additionally, the reliance on propri-
etary large LMs for data annotation not only incurs
high economic costs but also raises concerns re-
garding the sustainability and scalability of such
practices. For instance, Ho et al. (2023) highlighted
that while employing large LMs as annotators can
largely enhance the performance of smaller LMs,
it introduces a clear trade-off between economic
costs and performance gains.
1All | methods, including chain-of-
thought prompting (Wei et al., 2022b; Kojima et al.,
2022), continual pretraining (Azerbayev et al.,
2024), and adding external verifiersq (Li et al.,
2023b). However, the research question of how
to enhance the reasoning capabilities of smaller-
sized LMs remains relatively under-explored.
1e+18 3e+18 1e+19 3e+19 1e+20
Compute Cost (FLOPs)152025303540Accuracy (%)Flan-T5-L
(Ours)
Flan-T5-LFlan-T5-3BFlan-T5-11B
T5-LT5-3BT5-11B
T5-LT5-3BGSM8K Performance v.s. Compute cost
Codex distillation
(Fu et al., 2023)
PaLM distillation
(Magister et al., 2023)
Calcformer
(Kadl ík et al., 2023)
Figure 1: Our approach demonstrates superior perfor-
mance on the GSM8K benchmark while minimizing
the required compute cost, including both training and
inference. Compute cost calculations are based on the
methodology outlined by Yuan et al. (2023).1
Recent studies (Fu et al., 2023; Magister et al.,
2023; Li et al., 2023a) demonstrate that the rea-
soning capabilities of smaller LMs can be signif-
icantly enhanced through learning from the out-
puts of larger and more advanced LMs, such as
Codex (Chen et al., 2021), PaLM (Chowdhery
et al., 2022), and GPT-4 (OpenAI, 2023). While
this method is straightforward to implement, the
associated costs can be substantial. The computa-
tional demand, measured in floating-point opera-
tions (FLOPs), increases considerably when using
large LMs. Additionally, the reliance on propri-
etary large LMs for data annotation not only incurs
high economic costs but also raises concerns re-
garding the sustainability and scalability of such
practices. For instance, Ho et al. (2023) highlighted
that while employing large LMs as annotators can
largely enhance the performance of smaller LMs,
it introduces a clear trade-off between economic
costs and performance gains.
1All methods presented here are integrated with an external
calculator except for the Codex distillation by Fu et al. (2023).arXiv:2407.18248v1 [cs.CL] 25 Jul 2024
Another line of research focuses on explor-
ing enhancements through self-improvement meth-
ods (Zelikman et al., 2022; Gulcehre et al., 2023;
Singh et al., 2023). These methods diverge from
using outputs from larger models, instead encour-
aging LMs to learn from their own generated data.
The effectiveness of these techniques is evident,
yet their success largely depends upon the inher-
ent capabilities of the base models. For example,
Zelikman et al. (2022) initiated self-improvement
by few-shot prompting GPT-J (Wang and Ko-
matsuzaki, 2021), a relatively large LM which
has 6 billion parameters, to generate rationales –
an emergent ability typically reserved for large
models (Wei et al., 2022a). However, the ex-
tent to which small-scale LMs can gain from self-
improvement remains uncertain.
In this work, we introduce a novel enhance-
ment to the conventional self-training framework
by incorporating Direct Preference Optimization
(DPO) (Rafailov et al., 2023). This integration
specifically targets performance objectives within
chain-of-thought reasoning, with a particular focus
on mathematical reasoning. The clear-cut nature
of mathematical solutions enables straightforward
validation of a model’s outputs, facilitating the cre-
ation of a preference dataset for DPO. Our em-
pirical | Section not found | Section not found | Section not found | results indicate that this method notably en-
hances the reasoning capabilities of LMs while also
reducing computational overhead. We visualize the
relationship between the GSM8K (Cobbe et al.,
2021) performance and computational cost across
various specialized models in Figure 1. It can be
observed that our method not only achieves strong
performance, but also reduces computational de-
mands by effectively utilizing self-generated data
for learning. Overall, the main contribution of this
work can be summarized as follows:
•We propose a novel extension to the classic
self-training framework by integrating Direct
Preference Optimization, demonstrating its ef-
fectiveness across various math reasoning tasks.
•Our method significantly enhances the reason-
ing abilities of language models while requiring
minimal computational resources, optimizing
both performance and efficiency.
•We present an efficient method for integrating
LMs with external tools, which significantly
boosts downstream task performance without
notably compromising inference speed.Algorithm 1 Self-training for CoT reasoning tasks
Input: pre-trained language model fθ
Input: labeled dataset L={(xi, yi, ai)}l
i=1
Input: unlabeled dataset U={(xi, ai)}u
i=1
Output: fine-tuned model fθ′
1:Fine-tune fθonLto get fθ′
2:repeat
3: Build pseudo-labeled dataset S:
S={(xi,ˆyi,ˆai)}s
i=1
where xi∼ U andˆyi,ˆai∼fθ′(·|xi)
4: Select Sα⊂ S when ˆai=ai
5: Update L ← Sα∪ L
6: Train fθonLto get a new fθ′
7:until convergence or max iteration is reached
2 Background
Math word problem solving The math word
problem solving task (Cobbe et al., 2021) can be
formulated as a sequence-to-sequence task where
the input xis a question asking for an unknown
value and the output yis a rationale that leads to the
answer a. Normally, the answers can be extracted
from the rationales via some rule-based methods,
such as regular expressions. A generated rationale
ˆyis regarded as correct if the extracted answer ˆa
matches the gold answer a. Formally, the labeled
dataset for a math word problem solving task with
linstances can be represented as:
L={(xi, yi, ai)}l
i=1. (1)
A common way for specializing a LM fθtowards
math reasoning with the labeled dataset Lissuper-
vised fine-tuning (SFT). It optimizes fθby mini-
mizing the negative log likelihood loss LSFT(θ):
E
(x,y)∼L−hTX
t=1logfθ(yt|x, y 1:t−1)i
, (2)
where Tis the length of the rationale yand we use
ytto represent the t-th token in y.
Self-training Self-training is one of the earliest
approaches in semi-supervised learning (Scudder,
1965; Fralick, 1967) that has risen in popularity
recently (He et al., 2020; Amini et al., 2022). This
method first regards a base model trained with a
labeled dataset Las teacher, and uses it to build
a pseudo-labeled dataset Sby annotating an unla-
beled dataset U. Then, a student model is trained
on a combination of LandSthat are expected to
outperform the teacher model. Such a framework
has been shown effective across a wide range of
natural language processing tasks, including natu-
ral language understanding (Vu et al., 2021) and
generation (He et al., 2020). A formal description
of a self-training algorithm for chain-of-thought
(CoT) reasoning tasks is provided in Algorithm 1.
Previous studies have demonstrated that the qual-
ity of the pseudo-labels largely impacts the over-
all performance of the self-training algorithm (He
et al., 2020; Amini et al., 2022). For example, Gul-
cehre et al. (2023) proposed to select high-quality
pseudo-labels with a learned reward function. Ze-
likman et al. (2022) filtered the generated ratio-
nales to include only the ones that lead to correct
answers. Although many methods are proposed
to select pseudo-labels, few works discuss how
to improve the fine-tuned model fθ′so that more
high-quality pseudo-labels can be generated. In
this paper, we present a method to enhance fθ′in
each iteration so that higher-quality pseudo-labeled
data can be generated.
Direct Preference Optimization The Rein-
forcement Learning from Human Feedback
(RLHF) methods align LMs with human prefer-
ence (Ouyang et al., 2022; Bai et al., 2022). The
standard pipeline of RLHF requires to first train a
reward model from human preference data. Then,
the reward model is used to fine-tune language
models via reinforcement learning objective, e.g.,
Proximal Policy Optimization (Schulman et al.,
2017). A recent study propose Direct Preference
Optimization (DPO) (Rafailov et al., 2023) to avoid
explicitly training a reward model so that language
models can be directly tuned with human prefer-
ence data.
The DPO pipeline can be described as follows.
First, given some prompt x, we sample several com-
pletions from the reference model πref(normally it
is the model after supervised fine-tuning):
y1, y2∼πref(· |x). (3)
Next, construct the DPO dataset Dfrom the com-
pletions based on the human preference:
D={(xi, yi
w, yi
l)}N
i=1, (4)
where yi
wandyi
lrepresent the winning and los-
ing completions respectively. Then, we optimize
the language model πθto minimize LDPO(πθ;πref)Algorithm 2 DPO-augmented self-training
Input: pre-trained language model fθ
Input: labeled dataset L={(xi, yi, ai)}l
i=1
Input: unlabeled dataset U={(xi, ai)}u
i=1
Output: fine-tuned model fθ′
# Warm-up stage
1:Fine-tune fθonLto get fθ′
2:repeat
# DPO step
3: Generate DPO dataset D:
D={(xi, yi
w, yi
l)}N
i=1
where xi∼ U andyi
w, yi
l∼fθ′(·|xi)
4: Tune fθ′withLDPOonDto get fθd
# SFT step
5: Build pseudo-labeled dataset S:
S={(xi,ˆyi,ˆai)}s
i=1
where xi∼ U andˆyi,ˆai∼fθd(·|xi)
6: Select Sα⊂ S when ˆai=ai
7: Update L ← Sα∪ L
8: Train fθonLto get a new fθ′
9:until convergence or max iteration is reached
which can be defined as follows:
E
(x,yw,yl)∼D
−logσ
r(yw|x)−r(yl|x)
, (5)
where r(·|x) =βlogπθ(·|x)
πref(·|x)andβis a coefficient
that controls πθ’s deviation from πref.
3 Method
In this section, we first describe the proposed ap-
proach. Then, we demonstrate how we integrate
an external calculator into the model’s decoding
process which significantly improves LMs’ perfor-
mance on the downstream tasks.
3.1 DPO-augmented Self-Training
Our approach starts with a warm-up stage , and
then followed by an iterative process, where each
iteration is composed of two sub-steps: DPO step
andSFT step . The iterative process ends when
the model performance converges or reaches the
maximum iteration. A formal description of the
proposed method is illustrated in Algorithm 2. An
illustration of our method is presented in Figure 2.
Warm-up stage Like classic self-training, we
start by fine-tuning the base model fθto optimize
LSFT(θ)on the labeled data L, resulting in an up-
dated model fθ′. After this stage, we assume that
Pre-trained model
SFT model
DPO modelSupervised fine-tuningDPO trainingSampling&filteringPseudo-labeled dataSFT dataDeduplication
SamplingPreference data
Human-labeled SFT data
Iteration nFigure 2: An illustration of the DPO-augmented Self-Training framework. Traditional self-training method uses
the SFT model to generate the pseudo-labels for subsequent iterations. In contrast, our method enhances the SFT
model with Direct Preference Optimization (DPO), using the optimized DPO model to produce the pseudo-labels.
fθ′is capable of solving certain math problems.
Specifically, given a math question x,fθ′will gen-
erate a rationale ˆywith answer ˆa.
Iterative step 1: DPO step In this step, we first
sample rationales ˆyfrom the fine-tuned model fθ′
given some questions xfromU. For each ques-
tionx, we generate multiple rationales to build the
DPO training dataset D. As mentioned, for math
problem solving tasks, it is easy to know whether a
generated rationale ˆycan be considered as correct.
We label rationales with correct answers as win-
ning completions, while consider rationales with
incorrect answers as losing completions. Then, we
trainfθ′onDto optimize the objective function
LDPOand get a DPO model fθdin the end.
Iterative step 2: SFT step After obtaining fθd,
we use it to generate a new pseudo-labeled dataset
Sfor the next-round supervised fine-tuning:
S={(x,ˆy)|x∼ U,ˆy∼fθd(·|x)} (6)
After generation, we clean Sby eliminating ra-
tionales with incorrect answers and removing du-
plicates. Therefore, the pseudo-labeled dataset we
obtained in the end is a subset of the original one,
i.e.,Sα⊂ S. The final training dataset is the com-
bination of the original labeled dataset Land the
newly-generated pseudo-labeled dataset Sα. No-
tice that during this process, once we collect a new
dataset, we train from the original base model fθ
instead of continually fine-tuning fθ′to avoid over-
fitting, following previous practice (Zelikman et al.,
2022; Singh et al., 2023).Q: James writes a 3-page letter to 2
different friends twice a week. How many
pages does he write a year?
A: He writes each friend
3*2=<<3*2=6>>6 pages a week.
So he writes
6*2=<<6*2=12>>12 pages every week.
That means he writes
12*52=<<12*52=624>>624 pages a year.
#### 624
Figure 3: An example from the GSM8K dataset. The
calculation annotations are highlighted in blue. All
calculation steps are wrapped within special tokens
<<...>> . During decoding, the calculator will be trig-
gered when such patterns exist and the model’s output
tokens will be overridden by the calculator results. Fol-
lowing Cobbe et al. (2021), the calculation is performed
with the in-built python function eval() .
3.2 Batch Decoding with Calculator
Empirical observations indicate that while large
LMs, such as those described in Brown et al.
(2020), demonstrate superior proficiency in basic
arithmetic calculations, smaller LMs like Flan-T5-
Large tend to struggle with similar arithmetic tasks.
This limitation significantly affects their perfor-
mance in math reasoning tasks. To address this,
various studies (Parisi et al., 2022; Schick et al.,
2023; Kadl ˇcík et al., 2023) have explored augment-
ing small-scale models with an external calculator
to boost their arithmetic capabilities. However,
many of these existing methods are limited to a
batch size of one during decoding. This constraint
substantially reduces the inference speed and limits
their practical application.
1 8 16 32
Batch Size05101520Speedup
1.0x5.8x9.5x13.9x
6.9x12.3x19.9xCalcformer
Ours w/ calculator
Ours w/o calculatorFigure 4: Inference speed comparison between
our methods (w/ and w/o calculator) and Cal-
cformer (Kadl ˇcík et al., 2023) with varying batch sizes.
The results are measured on a single NVIDIA A40 GPU.
To address this challenge, we propose a sim-
ple yet efficient method that allows for using
larger batch sizes during inference with an external
calculator. Our approach leverages the calcula-
tor annotations provided in the original GSM8K
dataset (Cobbe et al., 2021). Figure 3 demonstrates
an example of this annotation and describes how
such annotations can be used during decoding. For
optimal utilization of these annotations, we build
our models with the Transformers library (Wolf
et al., 2020). During inference, we employ a
customized LogitsProcessor2–available in the
Transformers documentation– to adjust the model’s
generation process. This LogitsProcessor acts as
an interface, allowing modifications to the outputs
of the model during generation and thereby en-
abling efficient management of larger batch sizes.
To demonstrate the efficiency of the proposed
solution, we compare the inference speed of our
methods (w/ and w/o calculator) based on Flan-T5-
Large against an open-source tool-using method,
Calcformer (Kadl ˇcík et al., 2023) based on T5-
Large, in Figure 4. We find that when the batch size
equals 1, all three methods have a similar inference
speed of around 40 tokens per second. However, as
the inference batch size increases, the speedup of
our methods increases significantly.
4 Experiments
In this section, we first outline our experiment setup
and implementation details, then present our mod-
els’ performance on various math reasoning tasks
against competitive baselines. Finally, we analyze
the effectiveness of our method empirically.
2https://huggingface.co/docs/transformers/
internal/generation_utils#logitsprocessorDataset Split # Data
GSM8K (Cobbe et al., 2021) Train 6,705
Validation 0,768
Test 1,319
MultiArith (Roy and Roth, 2015) Test 0,600
ASDiv (Miao et al., 2020) Test 2,096
SV AMP (Patel et al., 2021) Test 1,000
Table 1: Statistics of the datasets used in our experi-
ments. The original GSM8K dataset only contains train
and test split. We randomly select 768 training examples
to construct the validation dataset in our experiments.
4.1 Setup
Base models We employ Flan-T5 models (Chung
et al., 2024) as our primary base models. Specifi-
cally, we consider two variants from the Flan-T5
family: Flan-T5-Base and Flan-T5-Large. We se-
lect Flan-T5 over the original T5 models (Raffel
et al., 2019) as our backbone models based on
the evidence from previous research (Chung et al.,
2024; Fu et al., 2023), which demonstrates that
instruction-tuned models like Flan-T5 outperform
their pre-trained counterparts in mathematical rea-
soning tasks. To broaden our analysis, we also in-
clude Llama models (Touvron et al., 2023a,b; Meta,
2024) as additional base models for comparison.
Datasets The labeled dataset Lused in our exper-
iments comes from the training split of the GSM8K
dataset. Our unlabeled dataset Uis also built upon
GSM8K’s training data by removing its annotated
rationales. For evaluation, we consider three ad-
ditional commonly used math reasoning tasks be-
sides GSM8K: MultiArith, ASDiv, and SV AMP.
Table 1 provides the statistics information of each
dataset. Following previous practice (Fu et al.,
2023), we fine-tune our base models exclusively
on the GSM8K training data while utilizing the
rest three datasets to evaluate our models’ out-of-
domain performance as they do not have an official
in-domain training split.
4.2 Implementation Details
In the warm-up stage, we fine-tune the base models
on the training set of GSM8K (Cobbe et al., 2021)
with the original human-labeled annotations and
obtain the initial SFT model. For subsequent DPO
steps, we first sample rationales from SFT mod-
els to build the preference dataset. We sample 5
rationales per question with a temperature of 0.7.
Generated rationales ˆycontaining the correct an-
Method Base Model GSM8K MultiArith ASDiv SVAMP
Supervised Fine-Tuning Flan-T5-Base 18.1 54.2 26.2 19.5
Self-Training Flan-T5-Base 25.9 73.8 28.2 24.2
DPO-aug Self-Training ( Ours ) Flan-T5-Base 27.2 74.3 29.2 22.6
Supervised Fine-Tuning Flan-T5-Large 30.8 77.2 38.1 33.6
Self-Training Flan-T5-Large 35.6 86.2 42.5 34.8
DPO-aug Self-Training ( Ours ) Flan-T5-Large 37.4 89.0 42.8 36.8
Table 2: Overall accuracies (%) over four math word problem solving tasks. Inspired by the previous practice (Fu
et al., 2023), all the models in this table are only trained with the GSM8K training set (Cobbe et al., 2021). Hence,
we report the in-distribution performance for GSM8K, while reporting the out-of-distribution performance for the
other three datasets, i.e., MultiArith, ASDiv, and SV AMP.
swer are classified as winning ones yw, while the
rest are considered losing ones yl. We set β= 0.1
in the DPO learning objective LDPO. For the sub-
sequent SFT steps, we generate 3 rationales per
question from the DPO-tuned model fθd, also with
a temperature of 0.7. Only the correct generated
rationales ˆywill be selected to build the pseudo-
labeled dataset. For both DPO and SFT steps, we
perform simple deduplication based on the Jaccard
similarity scores with a threshold of 0.7. Addi-
tional implementation details can be found in Ap-
pendix A.
Baselines We mainly consider two baseline meth-
ods to compare with our method: Supervised Fine-
Tuning (SFT) and Self-Training (ST). The SFT
baseline corresponds to the model after the warm-
up stage. The Self-Training baseline adheres to the
procedure outlined in Algorithm 1. To ensure a fair
comparison between our proposed method and the
ST baseline, we use the same set of hyperparame-
ters for both methods at each iteration.
4.3 Main Results
Comparison with baselines Table 2 shows the
performance of our method compared with the
baselines using two base models, Flan-T5-Base
and Flan-T5-Large, across four datasets. The re-
sults clearly show that both the ST baseline and our
proposed DPO-augmented Self-Training method
outperform the SFT baseline by a large margin, in-
dicating the effectiveness of the self-training frame-
work in general. Although the ST baselines make
significant improvements over the SFT baselines,
our DPO-augmented Self-Training models demon-
strate enhanced performance on both in-domain
(GSM8K) and out-of-domain (MultiArith, ASDiv,
and SV AMP) tasks.
iter 0 iter 1 iter 2 iter 315.017.520.022.525.027.530.0Accuracy (%)18.124.226.0 25.9
18.124.626.627.2Flan-T5-Base
ST
Ours
iter 0 iter 1 iter 2 iter 33032343638Accuracy (%)
30.832.935.135.6
30.834.135.637.4Flan-T5-Large
ST
OursFigure 5: The performance of the proposed method on
GSM8K over three iterations. For “iter 0”, we report the
performance of the SFT baselines, which are obtained
after the warm-up stage.
Effect of iterative training Figure 5 demon-
strates the impact of iterative training on Flan-T5-
Base and Flan-T5-Large models, comparing our
method to the ST baseline. Initially, both meth-
ods start with a warm-up stage and have similar
accuracies at iteration 0. As training progresses,
our method consistently outperforms ST across it-
erations for both models. For Flan-T5-Base, the
accuracy improvement plateaus by iteration 3, sug-
gesting convergence. In contrast, Flan-T5-Large
shows a clear and steady improvement, with our
method achieving significantly higher accuracy by
iteration 3. This underscores the effectiveness of
our iterative training process, particularly in en-
hancing performance of larger models.
Method Base Model # Annotations Annotator Tools Acc.
Supervised fine-tuning
CoT (Shridhar et al., 2023) GPT-2-Large 007K Human % 14.1
Self-consistency (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 33.3
GRACE (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 36.3
Calcformer (Kadl ˇcík et al., 2023) T5-Large 030K Human ! 34.2
Knowledge Distillation
Socratic CoT (Shridhar et al., 2023) GPT-2-Large 007K GPT-3 175B % 21.1
CoT from CodeX (Fu et al., 2023) Flan-T5-Large 100K CodeX % 20.2
CoT from PaLM (Magister et al., 2023) T5-Large 006K PaLM 540B ! 22.2
Ours
DPO-aug Self-Training ( K=3) Flan-T5-Large 007K Human ! 37.4
DPO-aug Self-Training ( K=5) Flan-T5-Large 007K Human ! 39.1
DPO-aug Self-Training ( K=10) Flan-T5-Large 007K Human ! 40.0
Table 3: Detailed comparison among existing methods with comparable model sizes on the GSM8K test set. The
“Annotator” column indicates how the rationales of the training data are generated. In this column, “Human” refers
to the labels from the original GSM8K dataset (Cobbe et al., 2021) that are written by human annotators. The
“Tools” column indicates whether external calculators are applied during inference.
4.4 Comparison with Existing Methods
In this section, we compare our methods with ex-
isting approaches. To enhance our method, we
increase the number of sampled pseudo-labels per
question to build a more diverse and robust pseudo-
label dataset. We denote this hyperparameter as K
following Yuan et al. (2023).
Table 3 presents a detailed comparison be-
tween our method and exisiting methods using
a simialr base model size. The base models we
considered include GPT-2-Large (Radford et al.,
2019), T5-Large (Raffel et al., 2019), and Flan-
T5-Large (Chung et al., 2024), each with approx-
imately 770 million parameters. As shown in Ta-
ble 3, our approach not only outperforms other
methods on the GSM8K benchmark, but also
demonstrates remarkable label efficiency by ex-
clusively using the annotations from the original
GSM8K dataset.
In Table 4, we further evaluate the effectiveness
of the proposed method with the Llama model fam-
ily (Touvron et al., 2023a,b; Meta, 2024), compar-
ing it with several state-of-the-art closed-source
models as well as similarly sized open-source mod-
els. We observe a substantial performance gap be-
tween proprietary and open-source models. Among
the open-source models, those utilizing knowledge
distillation generally outperform their counterparts
without such enhancement. Notably, our models
using Llama-1-7b and Llama-2-7b base models
surpass other open-source alternatives that do not
employ knowledge distillation, achieving accura-cies of 44.7% and 54.7% respectively. Furthermore,
our model employing the latest Llama-3-8b (Meta,
2024) matches or exceeds the performance of ear-
lier models with knowledge distillation, demon-
strating a significant accuracy of 68.8%.
Method Base Model Acc.
Closed-source models
Claude-3-Opus (Anthropic, 2024) - 95.0
Claude-2 (Anthropic, 2023) - 88.0
GPT-4 (OpenAI, 2023) - 92.0
Flan-PaLM-2 (Anil et al., 2023) - 84.7
Open-source models w/ knowledge distillation
MAmooTH (Yue et al., 2023)♡Llama-2-7b 53.6
LEMA (An et al., 2023) Llama-2-7b 54.1
WizardMath (Luo et al., 2023) Llama-2-7b 54.9
MetaMath (Yu et al., 2024) Llama-2-7b 66.5
MuggleMath (Li et al., 2023a) Llama-2-7b 68.4
ToRA (Gou et al., 2024)♡Llama-2-7b 68.8
Open-source models w/o knowledge distillation
SFT (Yuan et al., 2023) Llama-1-7b 35.9
SFT w/ Calculator♡Llama-1-7b 40.0
RFT ( K=100) (Yuan et al., 2023) Llama-1-7b 41.7
SFT (Yuan et al., 2023) Llama-2-7b 41.6
SFT w/ Calculator♡Llama-2-7b 45.1
RFT ( K=100) (Yuan et al., 2023) Llama-2-7b 47.5
SFT w/ Calculator♡Llama-3-8b 61.0
Ours
DPO-ST ( K=10)♡Llama-1-7b 44.7
DPO-ST ( K=10)♡Llama-2-7b 54.7
DPO-ST ( K=10)♡Llama-3-8b 68.8
Table 4: Comparison with the state-of-the-art pro-
prietary models and Llama-based open-source mod-
els (Touvron et al., 2023a,b; Meta, 2024).♡: models
augmented with external tools.
30333639Dev accuracy (%)36.136.5Pass@1
60626466Dev accuracy (%)62.964.8Pass@10
240027003000
24952940# generated
CoT pseudo-labels
Before DPO step After DPO stepFigure 6: Effects of the DPO step. Left: we report
the greedy decoding results for Pass@1. Middle: For
Pass@10, the solutions are sampled with temperature
0.7.Right: We count the number of generated pseudo-
labels after deduplication.
4.5 Effects of the DPO Step
As mentioned earlier, the main difference between
the proposed method and the classic self-training
is the DPO step in every iterative process. We now
analyze how the DPO steps improve self-training.
Figure 6 compares the performance of models be-
fore and after the DPO step in the first iteration on
the Pass@K metrics. Pass@K measures the proba-
bility that at least one of the Kgenerated solutions
for a problem is correct, which serves as a gauge
for both the quality and the variety of the model-
generated solutions. The models we investigate
here are fine-tuned from the Flan-T5-Large.
As shown in Figure 6, the DPO step yields only
marginal improvements over the SFT model in the
Pass@1 performance on the development set. How-
ever, the performance significantly improves when
multiple rationales, i.e., 10 solutions per question,
are sampled with temperature 0.7 (measured with
the Pass@10 metric). This indicates that the DPO
training objective makes language models inclined
to generate rationales of both high quality and di-
versity. We also compare the number of generated
rationales on the training set Lfor models with
and without the DPO step. Figure 6 (right) clearly
shows that the model after the DPO step can pro-
duce more SFT data for the next iteration.
4.6 Effects of External Calculator
Driven by the observation that small-scale LMs
frequently make basic calculation errors, we de-
velop a simple yet efficient method that integrates
an external calculator into the models’ decoding
process. To evaluate the impact of this integration,
iter 0 iter 1 iter 2 iter 31020304050Dev accuracy (%)36.740.543.944.8
16.317.117.8 18.0w/ calculator
w/o calculatorFigure 7: GSM8K development set accuracy of Flan-
T5-Large with and without the use of an external calcu-
lator during inference.
we conduct an ablation study by omitting the cal-
culator and present the | findings in Figure 7. Our
results indicate that decoding without the calcula-
tor markedly reduces accuracy across all iterations.
We believe that this is because models will generate
large amount of false positive pseudo-labels with-
out calculator, that is, the generated pseudo-labels
may have correct final answers but make errors in
the intermediate reasoning steps.
5 Related Work
Learning from pseudo-labels Supervised fine-
tuning (SFT) is prevalent technique employed to
enhance the performance of pre-trained language
models on specific downstream tasks (Ouyang
et al., 2022; Chung et al., 2024). However, this
method heavily depends on the availability of high-
quality labeled data, which can be both expensive
and labor-intensive to procure (Brown et al., 2020).
To address this limitation, various strategies have
been developed to generate high-quality pseudo-
labels using either unlabeled or synthetic data for
a wide range of applications, including text clas-
sification (Xie et al., 2020), sentence representa-
tion learning (Wang and Lu, 2022), instruction
tuning (Honovich et al., 2022), and math reason-
ing (Wang and Lu, 2023). Recent advancements
in this area primarily focus on two directions: self-
training and knowledge distillation. The key dif-
ference between these methods lies in the source
of the pseudo-labels: self-training uses the model’s
own predictions on unlabeled data, while knowl-
edge distillation utilizes the insights from larger,
more powerful models.
Self-training in language model Recently, we
have witnessed a large number of works focus-
ing on self-training algorithms for language mod-
els (He et al., 2020; Zelikman et al., 2022; Yuan
et al., 2023). Most of such methods are built
upon the classic self-training framework (Scud-
der, 1965). He et al. (2020) empirically studied
the effectiveness of self-training in natural lan-
guage generation tasks, e.g., summarization and
translation. Zelikman et al. (2022) proposed self-
taught reasoner (STaR), which demonstrated that
language models can be iteratively improved from
its own generation, even there are no gold ratio-
nales provided. Yuan et al. (2023) proposed re-
jection sampling fine-tuning to improve language
models’ math reasoning abilities. This method can
be interpreted as only executing one iteration of
the self-training algorithm. Singh et al. (2023) pro-
posed ReSTEM, a self-improving algorithm based
on expectation-maximization framework. This
method demonstrates significant improvements in
problem-solving tasks, e.g., math reasoning and
code generation.
Knowledge distillation from LLMs Many of
the recent research efforts demonstrated large lan-
guage models (LLMs) are capable of performing
math reasoning (Wei et al., 2022b; Gao et al., 2022;
OpenAI, 2023; Anil et al., 2023). As a result, there
is growing interest in enhancing the reasoning abil-
ities of smaller language models by distilling chain-
of-thought pseudo-labels from LLMs. (Ho et al.,
2023; Magister et al., 2023; Fu et al., 2023). For
example, Luo et al. (2023) proposed Reinforce-
ment Learning from Evol-Instruct Feedback built
upon the Evol-Instruct framework (Xu et al., 2023),
which requires ChatGPT to provide the training sig-
nals. An et al. (2023) demonstrated that language
models can effectively learn from the mistakes that
can be corrected by LLMs during supervised fine-
tuning. Although these methods are shown to have
promising experimental results, they are costly to
implement as large models cost more FLOPs dur-
ing inference. Our work demonstrates that small-
scale language models can effectively learn from
their own generations, offering a more resource-
efficient alternative to knowledge distillation. Since
our method is conceptually orthogonal to knowl-
edge distillation techniques, an interesting avenue
for future research would be to explore integrating
knowledge distillation into our iterative training
process to further enhance model performance.6 Conclusion
We present an effective and resource-efficient
method called DPO-augmented Self-Training
(DPO-ST), which augments the original Self-
Training algorithm with Direct Preference Opti-
mization (Rafailov et al., 2023). Unlike previous
studies that improve small-scale language models’
reasoning abilities by distilling a larger and more
powerful model, we argue that small models that
are trained merely on the limited human-labeled
data can improve themselves significantly. We also
empirically find that models trained with DPO loss
can generate pseudo-labeled data with higher qual-
ity and diversity. Our experiments demonstrate that
the proposed method not only outperforms exist-
ing methods with comparable model sizes on the
GSM8K benchmark, but also achieves remarkable
resource efficiency in terms of both computational
cost and the requirements of human-labeled data. | Section not found | Section not found | Section not found | Limitations
Use of unlabeled data Our method is built upon
the classic self-training algorithm, which provides
an effective semi-supervised learning framework
capable of utilizing unlabeled data efficiently. How-
ever, this work doesn’t explore the use of unla-
beled data explicitly. Future research efforts can be
made to explore how to collect high-quality unla-
beled data for math word problem solving. In other
words, we need to find an efficient method for col-
lecting unlabeled data U={(xi, ai)}u
i=1that for
each math question xi, there is a corresponding
ground-truth answer ai, ensuring the data’s rele-
vance and utility for enhancing model training.
Generalization to other tasks One of the lim-
itations of this work is the narrow scope of our
experiments, which were exclusively conducted on
math reasoning tasks. The primary reason for this
limitation is the lack of appropriate training data
for other reasoning tasks. As our method requires
a set of training data with chain-of-thought labels,
many existing reasoning tasks lack such annota-
tions, making it challenging to extend our experi-
ments beyond the current scope. Future research
may focus on identifying and developing suitable
datasets for a wider range of reasoning tasks to
fully evaluate the applicability and effectiveness of
our method across different reasoning tasks.
Acknowledgements
This work was done when Shichen Li was a vis-
iting student at the StatNLP Research Group of
SUTD. We would like to thank the anonymous re-
viewers, our meta-reviewer, and senior area chairs
for their constructive comments and support on
this work. This research/project is supported by
Ministry of Education, Singapore, under its Aca-
demic Research Fund (AcRF) Tier 2 Programme
(MOE AcRF Tier 2 Award No: MOET2EP20122-
0011), the National Research Foundation Singa-
pore and DSO National Laboratories under the
AI Singapore Program (AISG Award No: AISG2-
RP-2020-016), and Ministry of Education, Singa-
pore, under its Tier 3 Programme (The Award No.:
MOET320200004). Any opinions, findings and | Section not found | Conclusion
We present an effective and resource-efficient
method called DPO-augmented Self-Training
(DPO-ST), which augments the original Self-
Training algorithm with Direct Preference Opti-
mization (Rafailov et al., 2023). Unlike previous
studies that improve small-scale language models’
reasoning abilities by distilling a larger and more
powerful model, we argue that small models that
are trained merely on the limited human-labeled
data can improve themselves significantly. We also
empirically find that models trained with DPO loss
can generate pseudo-labeled data with higher qual-
ity and diversity. Our experiments demonstrate that
the proposed method not only outperforms exist-
ing methods with comparable model sizes on the
GSM8K benchmark, but also achieves remarkable
resource efficiency in terms of both computational
cost and the requirements of human-labeled data.
Limitations
Use of unlabeled data Our method is built upon
the classic self-training algorithm, which provides
an effective semi-supervised learning framework
capable of utilizing unlabeled data efficiently. How-
ever, this work doesn’t explore the use of unla-
beled data explicitly. Future research efforts can be
made to explore how to collect high-quality unla-
beled data for math word problem solving. In other
words, we need to find an efficient method for col-
lecting unlabeled data U={(xi, ai)}u
i=1that for
each math question xi, there is a corresponding
ground-truth answer ai, ensuring the data’s rele-
vance and utility for enhancing model training.
Generalization to other tasks One of the lim-
itations of this work is the narrow scope of our
experiments, which were exclusively conducted on
math reasoning tasks. The primary reason for this
limitation is the lack of appropriate training data
for other reasoning tasks. As our method requires
a set of training data with chain-of-thought labels,
many existing reasoning tasks lack such annota-
tions, making it challenging to extend our experi-
ments beyond the current scope. Future research
may focus on identifying and developing suitable
datasets for a wider range of reasoning tasks to
fully evaluate the applicability and effectiveness of
our method across different reasoning tasks.
Acknowledgements
This work was done when Shichen Li was a vis-
iting student at the StatNLP Research Group of
SUTD. We would like to thank the anonymous re-
viewers, our meta-reviewer, and senior area chairs
for their constructive comments and support on
this work. This research/project is supported by
Ministry of Education, Singapore, under its Aca-
demic Research Fund (AcRF) Tier 2 Programme
(MOE AcRF Tier 2 Award No: MOET2EP20122-
0011), the National Research Foundation Singa-
pore and DSO National Laboratories under the
AI Singapore Program (AISG Award No: AISG2-
RP-2020-016), and Ministry of Education, Singa-
pore, under its Tier 3 Programme (The Award No.:
MOET320200004). Any opinions, findings and
conclusions or recommendations expressed in this
material are those of the authors and do not reflect
the views of the funding agencies. | Section not found | Section not found | References
Massih-Reza Amini, Vasilii Feofanov, Loïc
Pauletto, Emilie Devijver, and Yury Maximov.
2022. Self-training: A survey. arXiv preprint
arXiv:2202.12040 .
Shengnan An, Zexiong Ma, Zeqi Lin, Nanning Zheng,
Jian-Guang Lou, and Weizhu Chen. 2023. Learn-
ing from mistakes makes llm better reasoner. arXiv
preprint arXiv:2310.20689 .
Rohan Anil, Andrew M Dai, Orhan Firat, Melvin John-
son, Dmitry Lepikhin, Alexandre Passos, Siamak
Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng
Chen, et al. 2023. Palm 2 technical report. arXiv
preprint arXiv:2305.10403 .
Anthropic. 2023. Claude 2. https://www.anthropic.
com/news/claude-2 . Accessed: 2024-05-06.
Anthropic. 2024. The claude 3 model family: Opus,
sonnet, haiku. Accessed: 2024-05-06.
Zhangir Azerbayev, Hailey Schoelkopf, Keiran Paster,
Marco Dos Santos, Stephen McAleer, Albert Q Jiang,
Jia Deng, Stella Biderman, and Sean Welleck. 2024.
Llemma: An open language model for mathematics.
InProceedings of ICLR .
Yuntao Bai, Andy Jones, Kamal Ndousse, Amanda
Askell, Anna Chen, Nova DasSarma, Dawn Drain,
Stanislav Fort, Deep Ganguli, Tom Henighan, et al.
2022. Training a helpful and harmless assistant with
reinforcement learning from human feedback. arXiv
preprint arXiv:2204.05862 .
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, ArvindNeelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, Sandhini Agarwal, Ariel Herbert-V oss,
Gretchen Krueger, et al. 2020. Language models
are few-shot learners. In Proceedings of NeurIPS .
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, et al. 2021. Evaluating large
language models trained on code. arXiv preprint
arXiv:2107.03374 .
Aakanksha Chowdhery, Sharan Narang, Jacob Devlin,
Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul
Barham, Hyung Won Chung, Charles Sutton, Sebas-
tian Gehrmann, et al. 2022. Palm: Scaling language
modeling with pathways. Journal of Machine Learn-
ing Research .
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Yunxuan Li, Xuezhi
Wang, Mostafa Dehghani, Siddhartha Brahma, et al.
2024. Scaling instruction-finetuned language models.
Journal of Machine Learning Research , 25(70):1–53.
Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian,
Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro
Nakano, et al. 2021. Training verifiers to solve math
word problems. arXiv preprint arXiv:2110.14168 .
Stanley C. Fralick. 1967. Learning to recognize patterns
without a teacher. IEEE Trans. Inf. Theory .
Yao Fu, Hao Peng, Litu Ou, Ashish Sabharwal, and
Tushar Khot. 2023. Specializing smaller language
models towards multi-step reasoning. In Proceedings
of ICML .
Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon,
Pengfei Liu, Yiming Yang, Jamie Callan, and Gra-
ham Neubig. 2022. Pal: Program-aided language
models. arXiv preprint arXiv:2211.10435 .
Zhibin Gou, Zhihong Shao, Yeyun Gong, Yujiu Yang,
Minlie Huang, Nan Duan, Weizhu Chen, et al. 2024.
Tora: A tool-integrated reasoning agent for mathe-
matical problem solving. In Proceedings of ACL .
Caglar Gulcehre, Tom Le Paine, Srivatsan Srini-
vasan, Ksenia Konyushkova, Lotte Weerts, Abhishek
Sharma, Aditya Siddhant, Alex Ahern, Miaosen
Wang, Chenjie Gu, et al. 2023. Reinforced self-
training (rest) for language modeling. arXiv preprint
arXiv:2308.08998 .
Junxian He, Jiatao Gu, Jiajun Shen, and Marc’Aurelio
Ranzato. 2020. Revisiting self-training for neural
sequence generation. In Proceedings of ICLR .
Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul
Arora, Steven Basart, Eric Tang, Dawn Song, and
Jacob Steinhardt. 2021. Measuring mathematical
problem solving with the math dataset. In Proceed-
ings of NeurIPS .
Namgyu Ho, Laura Schmid, and Se-Young Yun. 2023.
Large language models are reasoning teachers. In
Proceedings of ACL .
Or Honovich, Thomas Scialom, Omer Levy, and Timo
Schick. 2022. Unnatural instructions: Tuning lan-
guage models with (almost) no human labor. arXiv
preprint arXiv:2212.09689 .
Marek Kadl ˇcík, Michal Štefánik, Ond ˇrej Sotolá ˇr, and
Vlastimil Martinek. 2023. Calc-x and calcformers:
Empowering arithmetical chain-of-thought through
interaction with symbolic systems. In Proceedings
of EMNLP .
Muhammad Khalifa, Lajanugen Logeswaran, Moon-
tae Lee, Honglak Lee, and Lu Wang. 2023. Grace:
Discriminator-guided chain-of-thought reasoning. In
Findings of EMNLP .
Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yu-
taka Matsuo, and Yusuke Iwasawa. 2022. Large lan-
guage models are zero-shot reasoners. In Proceed-
ings of NeurIPS .
Chengpeng Li, Zheng Yuan, Guanting Dong, Keming
Lu, Jiancan Wu, Chuanqi Tan, Xiang Wang, and
Chang Zhou. 2023a. Query and response augmenta-
tion cannot help out-of-domain math reasoning gen-
eralization. arXiv preprint arXiv:2310.05506 .
Yifei Li, Zeqi Lin, Shizhuo Zhang, Qiang Fu, Bei Chen,
Jian-Guang Lou, and Weizhu Chen. 2023b. Making
language models better reasoners with step-aware
verifier. In Proceedings of ACL .
Ilya Loshchilov and Frank Hutter. 2019. Decoupled
weight decay regularization. In Proceedings of ICLR .
Haipeng Luo, Qingfeng Sun, Can Xu, Pu Zhao, Jian-
guang Lou, Chongyang Tao, Xiubo Geng, Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. 2023. Wiz-
ardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct.
arXiv preprint arXiv:2308.09583 .
Lucie Charlotte Magister, Jonathan Mallinson, Jakub
Adamek, Eric Malmi, and Aliaksei Severyn. 2023.
Teaching small language models to reason. In Pro-
ceedings of ACL .
Meta. 2024. Llama 3. https://llama.meta.com/
llama3/ . Accessed: 2024-06-01.
Shen-yun Miao, Chao-Chun Liang, and Keh-Yih Su.
2020. A diverse corpus for evaluating and developing
english math word problem solvers. In Proceedings
of ACL .
OpenAI. 2023. Gpt-4 technical report. arXiv preprint
arXiv:2303.08774 .
Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Car-
roll L. Wainwright, Pamela Mishkin, Chong Zhang,
Sandhini Agarwal, Katarina Slama, Alex Ray, John
Schulman, Jacob Hilton, Fraser Kelton, Luke E.Miller, Maddie Simens, Amanda Askell, Peter Welin-
der, Paul Francis Christiano, Jan Leike, and Ryan J.
Lowe. 2022. Training language models to follow
instructions with human feedback. In Proceedings of
NeurIPS .
Aaron Parisi, Yao Zhao, and Noah Fiedel. 2022. Talm:
Tool augmented language models. arXiv preprint
arXiv:2205.12255 .
Arkil Patel, Satwik Bhattamishra, and Navin Goyal.
2021. Are NLP models really able to solve simple
math word problems? In Proceedings of NAACL .
Alec Radford, Jeff Wu, Rewon Child, David Luan,
Dario Amodei, and Ilya Sutskever. 2019. Language
models are unsupervised multitask learners. OpenAI
blog.
Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano
Ermon, Christopher D Manning, and Chelsea Finn.
2023. Direct preference optimization: Your language
model is secretly a reward model. In Proceedings of
NeurIPS .
Colin Raffel, Noam M. Shazeer, Adam Roberts, Kather-
ine Lee, Sharan Narang, Michael Matena, Yanqi
Zhou, Wei Li, and Peter J. Liu. 2019. Exploring the
limits of transfer learning with a unified text-to-text
transformer. Journal of Machine Learning Research .
Subhro Roy and Dan Roth. 2015. Solving general arith-
metic word problems. In Proceedings of EMNLP .
Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta
Raileanu, Maria Lomeli, Luke Zettlemoyer, Nicola
Cancedda, and Thomas Scialom. 2023. Toolformer:
Language models can teach themselves to use tools.
InProceedings of NeurIPS .
John Schulman, Filip Wolski, Prafulla Dhariwal,
Alec Radford, and Oleg Klimov. 2017. Proxi-
mal policy optimization algorithms. arXiv preprint
arXiv:1707.06347 .
H. J. Scudder. 1965. Probability of error of some adap-
tive pattern-recognition machines. IEEE Trans. Inf.
Theory .
Kumar Shridhar, Alessandro Stolfo, and Mrinmaya
Sachan. 2023. Distilling reasoning capabilities into
smaller language models. In Findings of ACL .
Avi Singh, John D Co-Reyes, Rishabh Agarwal, Ankesh
Anand, Piyush Patil, Peter J Liu, James Harri-
son, Jaehoon Lee, Kelvin Xu, Aaron Parisi, et al.
2023. Beyond human data: Scaling self-training
for problem-solving with language models. arXiv
preprint arXiv:2312.06585 .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timothée Lacroix,
Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Tu Vu, Minh-Thang Luong, Quoc Le, Grady Simon,
and Mohit Iyyer. 2021. STraTA: Self-training with
task augmentation for better few-shot learning. In
Proceedings of EMNLP .
Ben Wang and Aran Komatsuzaki. 2021. GPT-J-
6B: A 6 Billion Parameter Autoregressive Lan-
guage Model. https://github.com/kingoflolz/
mesh-transformer-jax .
Tianduo Wang and Wei Lu. 2022. Differentiable data
augmentation for contrastive sentence representation
learning. In Proceedings of EMNLP .
Tianduo Wang and Wei Lu. 2023. Learning multi-step
reasoning by solving arithmetic tasks. In Proceed-
ings of ACL .
Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel,
Barret Zoph, Sebastian Borgeaud, Dani Yogatama,
Maarten Bosma, Denny Zhou, Donald Metzler, et al.
2022a. Emergent abilities of large language models.
Transactions on Machine Learning Research .
Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten
Bosma, Ed Chi, Quoc Le, and Denny Zhou. 2022b.
Chain of thought prompting elicits reasoning in large
language models. In Proceedings of NeurIPS .
Thomas Wolf, Lysandre Debut, Victor Sanh, Julien
Chaumond, Clement Delangue, Anthony Moi, Pier-
ric Cistac, Tim Rault, et al. 2020. Transformers:
State-of-the-art natural language processing. In Pro-
ceedings of EMNLP .
Qizhe Xie, Zihang Dai, Eduard Hovy, Thang Luong, and
Quoc Le. 2020. Unsupervised data augmentation for
consistency training. In Proceedings of NeurIPS .
Can Xu, Qingfeng Sun, Kai Zheng, Xiubo Geng,
Pu Zhao, Jiazhan Feng, Chongyang Tao, and Daxin
Jiang. 2023. Wizardlm: Empowering large lan-
guage models to follow complex instructions. arXiv
preprint arXiv:2304.12244 .
Longhui Yu, Weisen Jiang, Han Shi, Jincheng Yu,
Zhengying Liu, Yu Zhang, James T Kwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. 2024. Meta-
math: Bootstrap your own mathematical questions
for large language models. In Proceedings of ICLR .
Zheng Yuan, Hongyi Yuan, Chengpeng Li, Guanting
Dong, Chuanqi Tan, and Chang Zhou. 2023. Scal-
ing relationship on learning mathematical reason-
ing with large language models. arXiv preprint
arXiv:2308.01825 .Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wen-
hao Huang, Huan Sun, Yu Su, and Wenhu Chen.
2023. Mammoth: Building math generalist models
through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 .
Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Good-
man. 2022. Star: Bootstrapping reasoning with rea-
soning. In Proceedings of NeurIPS .
A Additional | Section not found | Section not found | Section not found | funding agencies.
References
Massih-Reza Amini, Vasilii Feofanov, Loïc
Pauletto, Emilie Devijver, and Yury Maximov.
2022. Self-training: A survey. arXiv preprint
arXiv:2202.12040 .
Shengnan An, Zexiong Ma, Zeqi Lin, Nanning Zheng,
Jian-Guang Lou, and Weizhu Chen. 2023. Learn-
ing from mistakes makes llm better reasoner. arXiv
preprint arXiv:2310.20689 .
Rohan Anil, Andrew M Dai, Orhan Firat, Melvin John-
son, Dmitry Lepikhin, Alexandre Passos, Siamak
Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng
Chen, et al. 2023. Palm 2 technical report. arXiv
preprint arXiv:2305.10403 .
Anthropic. 2023. Claude 2. https://www.anthropic.
com/news/claude-2 . Accessed: 2024-05-06.
Anthropic. 2024. The claude 3 model family: Opus,
sonnet, haiku. Accessed: 2024-05-06.
Zhangir Azerbayev, Hailey Schoelkopf, Keiran Paster,
Marco Dos Santos, Stephen McAleer, Albert Q Jiang,
Jia Deng, Stella Biderman, and Sean Welleck. 2024.
Llemma: An open language model for mathematics.
InProceedings of ICLR .
Yuntao Bai, Andy Jones, Kamal Ndousse, Amanda
Askell, Anna Chen, Nova DasSarma, Dawn Drain,
Stanislav Fort, Deep Ganguli, Tom Henighan, et al.
2022. Training a helpful and harmless assistant with
reinforcement learning from human feedback. arXiv
preprint arXiv:2204.05862 .
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, ArvindNeelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, Sandhini Agarwal, Ariel Herbert-V oss,
Gretchen Krueger, et al. 2020. Language models
are few-shot learners. In Proceedings of NeurIPS .
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, et al. 2021. Evaluating large
language models trained on code. arXiv preprint
arXiv:2107.03374 .
Aakanksha Chowdhery, Sharan Narang, Jacob Devlin,
Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul
Barham, Hyung Won Chung, Charles Sutton, Sebas-
tian Gehrmann, et al. 2022. Palm: Scaling language
modeling with pathways. Journal of Machine Learn-
ing Research .
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Yunxuan Li, Xuezhi
Wang, Mostafa Dehghani, Siddhartha Brahma, et al.
2024. Scaling instruction-finetuned language models.
Journal of Machine Learning Research , 25(70):1–53.
Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian,
Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro
Nakano, et al. 2021. Training verifiers to solve math
word problems. arXiv preprint arXiv:2110.14168 .
Stanley C. Fralick. 1967. Learning to recognize patterns
without a teacher. IEEE Trans. Inf. Theory .
Yao Fu, Hao Peng, Litu Ou, Ashish Sabharwal, and
Tushar Khot. 2023. Specializing smaller language
models towards multi-step reasoning. In Proceedings
of ICML .
Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon,
Pengfei Liu, Yiming Yang, Jamie Callan, and Gra-
ham Neubig. 2022. Pal: Program-aided language
models. arXiv preprint arXiv:2211.10435 .
Zhibin Gou, Zhihong Shao, Yeyun Gong, Yujiu Yang,
Minlie Huang, Nan Duan, Weizhu Chen, et al. 2024.
Tora: A tool-integrated reasoning agent for mathe-
matical problem solving. In Proceedings of ACL .
Caglar Gulcehre, Tom Le Paine, Srivatsan Srini-
vasan, Ksenia Konyushkova, Lotte Weerts, Abhishek
Sharma, Aditya Siddhant, Alex Ahern, Miaosen
Wang, Chenjie Gu, et al. 2023. Reinforced self-
training (rest) for language modeling. arXiv preprint
arXiv:2308.08998 .
Junxian He, Jiatao Gu, Jiajun Shen, and Marc’Aurelio
Ranzato. 2020. Revisiting self-training for neural
sequence generation. In Proceedings of ICLR .
Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul
Arora, Steven Basart, Eric Tang, Dawn Song, and
Jacob Steinhardt. 2021. Measuring mathematical
problem solving with the math dataset. In Proceed-
ings of NeurIPS .
Namgyu Ho, Laura Schmid, and Se-Young Yun. 2023.
Large language models are reasoning teachers. In
Proceedings of ACL .
Or Honovich, Thomas Scialom, Omer Levy, and Timo
Schick. 2022. Unnatural instructions: Tuning lan-
guage models with (almost) no human labor. arXiv
preprint arXiv:2212.09689 .
Marek Kadl ˇcík, Michal Štefánik, Ond ˇrej Sotolá ˇr, and
Vlastimil Martinek. 2023. Calc-x and calcformers:
Empowering arithmetical chain-of-thought through
interaction with symbolic systems. In Proceedings
of EMNLP .
Muhammad Khalifa, Lajanugen Logeswaran, Moon-
tae Lee, Honglak Lee, and Lu Wang. 2023. Grace:
Discriminator-guided chain-of-thought reasoning. In
Findings of EMNLP .
Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yu-
taka Matsuo, and Yusuke Iwasawa. 2022. Large lan-
guage models are zero-shot reasoners. In Proceed-
ings of NeurIPS .
Chengpeng Li, Zheng Yuan, Guanting Dong, Keming
Lu, Jiancan Wu, Chuanqi Tan, Xiang Wang, and
Chang Zhou. 2023a. Query and response augmenta-
tion cannot help out-of-domain math reasoning gen-
eralization. arXiv preprint arXiv:2310.05506 .
Yifei Li, Zeqi Lin, Shizhuo Zhang, Qiang Fu, Bei Chen,
Jian-Guang Lou, and Weizhu Chen. 2023b. Making
language models better reasoners with step-aware
verifier. In Proceedings of ACL .
Ilya Loshchilov and Frank Hutter. 2019. Decoupled
weight decay regularization. In Proceedings of ICLR .
Haipeng Luo, Qingfeng Sun, Can Xu, Pu Zhao, Jian-
guang Lou, Chongyang Tao, Xiubo Geng, Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. 2023. Wiz-
ardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct.
arXiv preprint arXiv:2308.09583 .
Lucie Charlotte Magister, Jonathan Mallinson, Jakub
Adamek, Eric Malmi, and Aliaksei Severyn. 2023.
Teaching small language models to reason. In Pro-
ceedings of ACL .
Meta. 2024. Llama 3. https://llama.meta.com/
llama3/ . Accessed: 2024-06-01.
Shen-yun Miao, Chao-Chun Liang, and Keh-Yih Su.
2020. A diverse corpus for evaluating and developing
english math word problem solvers. In Proceedings
of ACL .
OpenAI. 2023. Gpt-4 technical report. arXiv preprint
arXiv:2303.08774 .
Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Car-
roll L. Wainwright, Pamela Mishkin, Chong Zhang,
Sandhini Agarwal, Katarina Slama, Alex Ray, John
Schulman, Jacob Hilton, Fraser Kelton, Luke E.Miller, Maddie Simens, Amanda Askell, Peter Welin-
der, Paul Francis Christiano, Jan Leike, and Ryan J.
Lowe. 2022. Training language models to follow
instructions with human feedback. In Proceedings of
NeurIPS .
Aaron Parisi, Yao Zhao, and Noah Fiedel. 2022. Talm:
Tool augmented language models. arXiv preprint
arXiv:2205.12255 .
Arkil Patel, Satwik Bhattamishra, and Navin Goyal.
2021. Are NLP models really able to solve simple
math word problems? In Proceedings of NAACL .
Alec Radford, Jeff Wu, Rewon Child, David Luan,
Dario Amodei, and Ilya Sutskever. 2019. Language
models are unsupervised multitask learners. OpenAI
blog.
Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano
Ermon, Christopher D Manning, and Chelsea Finn.
2023. Direct preference optimization: Your language
model is secretly a reward model. In Proceedings of
NeurIPS .
Colin Raffel, Noam M. Shazeer, Adam Roberts, Kather-
ine Lee, Sharan Narang, Michael Matena, Yanqi
Zhou, Wei Li, and Peter J. Liu. 2019. Exploring the
limits of transfer learning with a unified text-to-text
transformer. Journal of Machine Learning Research .
Subhro Roy and Dan Roth. 2015. Solving general arith-
metic word problems. In Proceedings of EMNLP .
Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta
Raileanu, Maria Lomeli, Luke Zettlemoyer, Nicola
Cancedda, and Thomas Scialom. 2023. Toolformer:
Language models can teach themselves to use tools.
InProceedings of NeurIPS .
John Schulman, Filip Wolski, Prafulla Dhariwal,
Alec Radford, and Oleg Klimov. 2017. Proxi-
mal policy optimization algorithms. arXiv preprint
arXiv:1707.06347 .
H. J. Scudder. 1965. Probability of error of some adap-
tive pattern-recognition machines. IEEE Trans. Inf.
Theory .
Kumar Shridhar, Alessandro Stolfo, and Mrinmaya
Sachan. 2023. Distilling reasoning capabilities into
smaller language models. In Findings of ACL .
Avi Singh, John D Co-Reyes, Rishabh Agarwal, Ankesh
Anand, Piyush Patil, Peter J Liu, James Harri-
son, Jaehoon Lee, Kelvin Xu, Aaron Parisi, et al.
2023. Beyond human data: Scaling self-training
for problem-solving with language models. arXiv
preprint arXiv:2312.06585 .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timothée Lacroix,
Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Tu Vu, Minh-Thang Luong, Quoc Le, Grady Simon,
and Mohit Iyyer. 2021. STraTA: Self-training with
task augmentation for better few-shot learning. In
Proceedings of EMNLP .
Ben Wang and Aran Komatsuzaki. 2021. GPT-J-
6B: A 6 Billion Parameter Autoregressive Lan-
guage Model. https://github.com/kingoflolz/
mesh-transformer-jax .
Tianduo Wang and Wei Lu. 2022. Differentiable data
augmentation for contrastive sentence representation
learning. In Proceedings of EMNLP .
Tianduo Wang and Wei Lu. 2023. Learning multi-step
reasoning by solving arithmetic tasks. In Proceed-
ings of ACL .
Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel,
Barret Zoph, Sebastian Borgeaud, Dani Yogatama,
Maarten Bosma, Denny Zhou, Donald Metzler, et al.
2022a. Emergent abilities of large language models.
Transactions on Machine Learning Research .
Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten
Bosma, Ed Chi, Quoc Le, and Denny Zhou. 2022b.
Chain of thought prompting elicits reasoning in large
language models. In Proceedings of NeurIPS .
Thomas Wolf, Lysandre Debut, Victor Sanh, Julien
Chaumond, Clement Delangue, Anthony Moi, Pier-
ric Cistac, Tim Rault, et al. 2020. Transformers:
State-of-the-art natural language processing. In Pro-
ceedings of EMNLP .
Qizhe Xie, Zihang Dai, Eduard Hovy, Thang Luong, and
Quoc Le. 2020. Unsupervised data augmentation for
consistency training. In Proceedings of NeurIPS .
Can Xu, Qingfeng Sun, Kai Zheng, Xiubo Geng,
Pu Zhao, Jiazhan Feng, Chongyang Tao, and Daxin
Jiang. 2023. Wizardlm: Empowering large lan-
guage models to follow complex instructions. arXiv
preprint arXiv:2304.12244 .
Longhui Yu, Weisen Jiang, Han Shi, Jincheng Yu,
Zhengying Liu, Yu Zhang, James T Kwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. 2024. Meta-
math: Bootstrap your own mathematical questions
for large language models. In Proceedings of ICLR .
Zheng Yuan, Hongyi Yuan, Chengpeng Li, Guanting
Dong, Chuanqi Tan, and Chang Zhou. 2023. Scal-
ing relationship on learning mathematical reason-
ing with large language models. arXiv preprint
arXiv:2308.01825 .Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wen-
hao Huang, Huan Sun, Yu Su, and Wenhu Chen.
2023. Mammoth: Building math generalist models
through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 .
Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Good-
man. 2022. Star: Bootstrapping reasoning with rea-
soning. In Proceedings of NeurIPS .
A Additional | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | implementation details, then present our mod-
els’ performance on various math reasoning tasks
against competitive baselines. Finally, we analyze
the effectiveness of our method empirically.
2https://huggingface.co/docs/transformers/
internal/generation_utils#logitsprocessorDataset Split # Data
GSM8K (Cobbe et al., 2021) Train 6,705
Validation 0,768
Test 1,319
MultiArith (Roy and Roth, 2015) Test 0,600
ASDiv (Miao et al., 2020) Test 2,096
SV AMP (Patel et al., 2021) Test 1,000
Table 1: Statistics of the datasets used in our experi-
ments. The original GSM8K dataset only contains train
and test split. We randomly select 768 training examples
to construct the validation dataset in our experiments.
4.1 Setup
Base models We employ Flan-T5 models (Chung
et al., 2024) as our primary base models. Specifi-
cally, we consider two variants from the Flan-T5
family: Flan-T5-Base and Flan-T5-Large. We se-
lect Flan-T5 over the original T5 models (Raffel
et al., 2019) as our backbone models based on
the evidence from previous research (Chung et al.,
2024; Fu et al., 2023), which demonstrates that
instruction-tuned models like Flan-T5 outperform
their pre-trained counterparts in mathematical rea-
soning tasks. To broaden our analysis, we also in-
clude Llama models (Touvron et al., 2023a,b; Meta,
2024) as additional base models for comparison.
Datasets The labeled dataset Lused in our exper-
iments comes from the training split of the GSM8K
dataset. Our unlabeled dataset Uis also built upon
GSM8K’s training data by removing its annotated
rationales. For evaluation, we consider three ad-
ditional commonly used math reasoning tasks be-
sides GSM8K: MultiArith, ASDiv, and SV AMP.
Table 1 provides the statistics information of each
dataset. Following previous practice (Fu et al.,
2023), we fine-tune our base models exclusively
on the GSM8K training data while utilizing the
rest three datasets to evaluate our models’ out-of-
domain performance as they do not have an official
in-domain training split.
4.2 Implementation Details
In the warm-up stage, we fine-tune the base models
on the training set of GSM8K (Cobbe et al., 2021)
with the original human-labeled annotations and
obtain the initial SFT model. For subsequent DPO
steps, we first sample rationales from SFT mod-
els to build the preference dataset. We sample 5
rationales per question with a temperature of 0.7.
Generated rationales ˆycontaining the correct an-
Method Base Model GSM8K MultiArith ASDiv SVAMP
Supervised Fine-Tuning Flan-T5-Base 18.1 54.2 26.2 19.5
Self-Training Flan-T5-Base 25.9 73.8 28.2 24.2
DPO-aug Self-Training ( Ours ) Flan-T5-Base 27.2 74.3 29.2 22.6
Supervised Fine-Tuning Flan-T5-Large 30.8 77.2 38.1 33.6
Self-Training Flan-T5-Large 35.6 86.2 42.5 34.8
DPO-aug Self-Training ( Ours ) Flan-T5-Large 37.4 89.0 42.8 36.8
Table 2: Overall accuracies (%) over four math word problem solving tasks. Inspired by the previous practice (Fu
et al., 2023), all the models in this table are only trained with the GSM8K training set (Cobbe et al., 2021). Hence,
we report the in-distribution performance for GSM8K, while reporting the out-of-distribution performance for the
other three datasets, i.e., MultiArith, ASDiv, and SV AMP.
swer are classified as winning ones yw, while the
rest are considered losing ones yl. We set β= 0.1
in the DPO learning objective LDPO. For the sub-
sequent SFT steps, we generate 3 rationales per
question from the DPO-tuned model fθd, also with
a temperature of 0.7. Only the correct generated
rationales ˆywill be selected to build the pseudo-
labeled dataset. For both DPO and SFT steps, we
perform simple deduplication based on the Jaccard
similarity scores with a threshold of 0.7. Addi-
tional implementation details can be found in Ap-
pendix A.
Baselines We mainly consider two baseline meth-
ods to compare with our method: Supervised Fine-
Tuning (SFT) and Self-Training (ST). The SFT
baseline corresponds to the model after the warm-
up stage. The Self-Training baseline adheres to the
procedure outlined in Algorithm 1. To ensure a fair
comparison between our proposed method and the
ST baseline, we use the same set of hyperparame-
ters for both methods at each iteration.
4.3 Main Results
Comparison with baselines Table 2 shows the
performance of our method compared with the
baselines using two base models, Flan-T5-Base
and Flan-T5-Large, across four datasets. The re-
sults clearly show that both the ST baseline and our
proposed DPO-augmented Self-Training method
outperform the SFT baseline by a large margin, in-
dicating the effectiveness of the self-training frame-
work in general. Although the ST baselines make
significant improvements over the SFT baselines,
our DPO-augmented Self-Training models demon-
strate enhanced performance on both in-domain
(GSM8K) and out-of-domain (MultiArith, ASDiv,
and SV AMP) tasks.
iter 0 iter 1 iter 2 iter 315.017.520.022.525.027.530.0Accuracy (%)18.124.226.0 25.9
18.124.626.627.2Flan-T5-Base
ST
Ours
iter 0 iter 1 iter 2 iter 33032343638Accuracy (%)
30.832.935.135.6
30.834.135.637.4Flan-T5-Large
ST
OursFigure 5: The performance of the proposed method on
GSM8K over three iterations. For “iter 0”, we report the
performance of the SFT baselines, which are obtained
after the warm-up stage.
Effect of iterative training Figure 5 demon-
strates the impact of iterative training on Flan-T5-
Base and Flan-T5-Large models, comparing our
method to the ST baseline. Initially, both meth-
ods start with a warm-up stage and have similar
accuracies at iteration 0. As training progresses,
our method consistently outperforms ST across it-
erations for both models. For Flan-T5-Base, the
accuracy improvement plateaus by iteration 3, sug-
gesting convergence. In contrast, Flan-T5-Large
shows a clear and steady improvement, with our
method achieving significantly higher accuracy by
iteration 3. This underscores the effectiveness of
our iterative training process, particularly in en-
hancing performance of larger models.
Method Base Model # Annotations Annotator Tools Acc.
Supervised fine-tuning
CoT (Shridhar et al., 2023) GPT-2-Large 007K Human % 14.1
Self-consistency (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 33.3
GRACE (Khalifa et al., 2023) Flan-T5-Large 007K Human ! 36.3
Calcformer (Kadl ˇcík et al., 2023) T5-Large 030K Human ! 34.2
Knowledge Distillation
Socratic CoT (Shridhar et al., 2023) GPT-2-Large 007K GPT-3 175B % 21.1
CoT from CodeX (Fu et al., 2023) Flan-T5-Large 100K CodeX % 20.2
CoT from PaLM (Magister et al., 2023) T5-Large 006K PaLM 540B ! 22.2
Ours
DPO-aug Self-Training ( K=3) Flan-T5-Large 007K Human ! 37.4
DPO-aug Self-Training ( K=5) Flan-T5-Large 007K Human ! 39.1
DPO-aug Self-Training ( K=10) Flan-T5-Large 007K Human ! 40.0
Table 3: Detailed comparison among existing methods with comparable model sizes on the GSM8K test set. The
“Annotator” column indicates how the rationales of the training data are generated. In this column, “Human” refers
to the labels from the original GSM8K dataset (Cobbe et al., 2021) that are written by human annotators. The
“Tools” column indicates whether external calculators are applied during inference.
4.4 Comparison with Existing Methods
In this section, we compare our methods with ex-
isting approaches. To enhance our method, we
increase the number of sampled pseudo-labels per
question to build a more diverse and robust pseudo-
label dataset. We denote this hyperparameter as K
following Yuan et al. (2023).
Table 3 presents a detailed comparison be-
tween our method and exisiting methods using
a simialr base model size. The base models we
considered include GPT-2-Large (Radford et al.,
2019), T5-Large (Raffel et al., 2019), and Flan-
T5-Large (Chung et al., 2024), each with approx-
imately 770 million parameters. As shown in Ta-
ble 3, our approach not only outperforms other
methods on the GSM8K benchmark, but also
demonstrates remarkable label efficiency by ex-
clusively using the annotations from the original
GSM8K dataset.
In Table 4, we further evaluate the effectiveness
of the proposed method with the Llama model fam-
ily (Touvron et al., 2023a,b; Meta, 2024), compar-
ing it with several state-of-the-art closed-source
models as well as similarly sized open-source mod-
els. We observe a substantial performance gap be-
tween proprietary and open-source models. Among
the open-source models, those utilizing knowledge
distillation generally outperform their counterparts
without such enhancement. Notably, our models
using Llama-1-7b and Llama-2-7b base models
surpass other open-source alternatives that do not
employ knowledge distillation, achieving accura-cies of 44.7% and 54.7% respectively. Furthermore,
our model employing the latest Llama-3-8b (Meta,
2024) matches or exceeds the performance of ear-
lier models with knowledge distillation, demon-
strating a significant accuracy of 68.8%.
Method Base Model Acc.
Closed-source models
Claude-3-Opus (Anthropic, 2024) - 95.0
Claude-2 (Anthropic, 2023) - 88.0
GPT-4 (OpenAI, 2023) - 92.0
Flan-PaLM-2 (Anil et al., 2023) - 84.7
Open-source models w/ knowledge distillation
MAmooTH (Yue et al., 2023)♡Llama-2-7b 53.6
LEMA (An et al., 2023) Llama-2-7b 54.1
WizardMath (Luo et al., 2023) Llama-2-7b 54.9
MetaMath (Yu et al., 2024) Llama-2-7b 66.5
MuggleMath (Li et al., 2023a) Llama-2-7b 68.4
ToRA (Gou et al., 2024)♡Llama-2-7b 68.8
Open-source models w/o knowledge distillation
SFT (Yuan et al., 2023) Llama-1-7b 35.9
SFT w/ Calculator♡Llama-1-7b 40.0
RFT ( K=100) (Yuan et al., 2023) Llama-1-7b 41.7
SFT (Yuan et al., 2023) Llama-2-7b 41.6
SFT w/ Calculator♡Llama-2-7b 45.1
RFT ( K=100) (Yuan et al., 2023) Llama-2-7b 47.5
SFT w/ Calculator♡Llama-3-8b 61.0
Ours
DPO-ST ( K=10)♡Llama-1-7b 44.7
DPO-ST ( K=10)♡Llama-2-7b 54.7
DPO-ST ( K=10)♡Llama-3-8b 68.8
Table 4: Comparison with the state-of-the-art pro-
prietary models and Llama-based open-source mod-
els (Touvron et al., 2023a,b; Meta, 2024).♡: models
augmented with external tools.
30333639Dev accuracy (%)36.136.5Pass@1
60626466Dev accuracy (%)62.964.8Pass@10
240027003000
24952940# generated
CoT pseudo-labels
Before DPO step After DPO stepFigure 6: Effects of the DPO step. Left: we report
the greedy decoding results for Pass@1. Middle: For
Pass@10, the solutions are sampled with temperature
0.7.Right: We count the number of generated pseudo-
labels after deduplication.
4.5 Effects of the DPO Step
As mentioned earlier, the main difference between
the proposed method and the classic self-training
is the DPO step in every iterative process. We now
analyze how the DPO steps improve self-training.
Figure 6 compares the performance of models be-
fore and after the DPO step in the first iteration on
the Pass@K metrics. Pass@K measures the proba-
bility that at least one of the Kgenerated solutions
for a problem is correct, which serves as a gauge
for both the quality and the variety of the model-
generated solutions. The models we investigate
here are fine-tuned from the Flan-T5-Large.
As shown in Figure 6, the DPO step yields only
marginal improvements over the SFT model in the
Pass@1 performance on the development set. How-
ever, the performance significantly improves when
multiple rationales, i.e., 10 solutions per question,
are sampled with temperature 0.7 (measured with
the Pass@10 metric). This indicates that the DPO
training objective makes language models inclined
to generate rationales of both high quality and di-
versity. We also compare the number of generated
rationales on the training set Lfor models with
and without the DPO step. Figure 6 (right) clearly
shows that the model after the DPO step can pro-
duce more SFT data for the next iteration.
4.6 Effects of External Calculator
Driven by the observation that small-scale LMs
frequently make basic calculation errors, we de-
velop a simple yet efficient method that integrates
an external calculator into the models’ decoding
process. To evaluate the impact of this integration,
iter 0 iter 1 iter 2 iter 31020304050Dev accuracy (%)36.740.543.944.8
16.317.117.8 18.0w/ calculator
w/o calculatorFigure 7: GSM8K development set accuracy of Flan-
T5-Large with and without the use of an external calcu-
lator during inference.
we conduct an ablation study by omitting the cal-
culator and present the findings in Figure 7. Our
results indicate that decoding without the calcula-
tor markedly reduces accuracy across all iterations.
We believe that this is because models will generate
large amount of false positive pseudo-labels with-
out calculator, that is, the generated pseudo-labels
may have correct final answers but make errors in
the intermediate reasoning steps.
5 Related Work
Learning from pseudo-labels Supervised fine-
tuning (SFT) is prevalent technique employed to
enhance the performance of pre-trained language
models on specific downstream tasks (Ouyang
et al., 2022; Chung et al., 2024). However, this
method heavily depends on the availability of high-
quality labeled data, which can be both expensive
and labor-intensive to procure (Brown et al., 2020).
To address this limitation, various strategies have
been developed to generate high-quality pseudo-
labels using either unlabeled or synthetic data for
a wide range of applications, including text clas-
sification (Xie et al., 2020), sentence representa-
tion learning (Wang and Lu, 2022), instruction
tuning (Honovich et al., 2022), and math reason-
ing (Wang and Lu, 2023). Recent advancements
in this area primarily focus on two directions: self-
training and knowledge distillation. The key dif-
ference between these methods lies in the source
of the pseudo-labels: self-training uses the model’s
own predictions on unlabeled data, while knowl-
edge distillation utilizes the insights from larger,
more powerful models.
Self-training in language model Recently, we
have witnessed a large number of works focus-
ing on self-training algorithms for language mod-
els (He et al., 2020; Zelikman et al., 2022; Yuan
et al., 2023). Most of such methods are built
upon the classic self-training framework (Scud-
der, 1965). He et al. (2020) empirically studied
the effectiveness of self-training in natural lan-
guage generation tasks, e.g., summarization and
translation. Zelikman et al. (2022) proposed self-
taught reasoner (STaR), which demonstrated that
language models can be iteratively improved from
its own generation, even there are no gold ratio-
nales provided. Yuan et al. (2023) proposed re-
jection sampling fine-tuning to improve language
models’ math reasoning abilities. This method can
be interpreted as only executing one iteration of
the self-training algorithm. Singh et al. (2023) pro-
posed ReSTEM, a self-improving algorithm based
on expectation-maximization framework. This
method demonstrates significant improvements in
problem-solving tasks, e.g., math reasoning and
code generation.
Knowledge distillation from LLMs Many of
the recent research efforts demonstrated large lan-
guage models (LLMs) are capable of performing
math reasoning (Wei et al., 2022b; Gao et al., 2022;
OpenAI, 2023; Anil et al., 2023). As a result, there
is growing interest in enhancing the reasoning abil-
ities of smaller language models by distilling chain-
of-thought pseudo-labels from LLMs. (Ho et al.,
2023; Magister et al., 2023; Fu et al., 2023). For
example, Luo et al. (2023) proposed Reinforce-
ment Learning from Evol-Instruct Feedback built
upon the Evol-Instruct framework (Xu et al., 2023),
which requires ChatGPT to provide the training sig-
nals. An et al. (2023) demonstrated that language
models can effectively learn from the mistakes that
can be corrected by LLMs during supervised fine-
tuning. Although these methods are shown to have
promising | experimental results, they are costly to
implement as large models cost more FLOPs dur-
ing inference. Our work demonstrates that small-
scale language models can effectively learn from
their own generations, offering a more resource-
efficient alternative to knowledge distillation. Since
our method is conceptually orthogonal to knowl-
edge distillation techniques, an interesting avenue
for future research would be to explore integrating
knowledge distillation into our iterative training
process to further enhance model performance.6 Conclusion
We present an effective and resource-efficient
method called DPO-augmented Self-Training
(DPO-ST), which augments the original Self-
Training algorithm with Direct Preference Opti-
mization (Rafailov et al., 2023). Unlike previous
studies that improve small-scale language models’
reasoning abilities by distilling a larger and more
powerful model, we argue that small models that
are trained merely on the limited human-labeled
data can improve themselves significantly. We also
empirically find that models trained with DPO loss
can generate pseudo-labeled data with higher qual-
ity and diversity. Our experiments demonstrate that
the proposed method not only outperforms exist-
ing methods with comparable model sizes on the
GSM8K benchmark, but also achieves remarkable
resource efficiency in terms of both computational
cost and the requirements of human-labeled data.
Limitations
Use of unlabeled data Our method is built upon
the classic self-training algorithm, which provides
an effective semi-supervised learning framework
capable of utilizing unlabeled data efficiently. How-
ever, this work doesn’t explore the use of unla-
beled data explicitly. Future research efforts can be
made to explore how to collect high-quality unla-
beled data for math word problem solving. In other
words, we need to find an efficient method for col-
lecting unlabeled data U={(xi, ai)}u
i=1that for
each math question xi, there is a corresponding
ground-truth answer ai, ensuring the data’s rele-
vance and utility for enhancing model training.
Generalization to other tasks One of the lim-
itations of this work is the narrow scope of our
experiments, which were exclusively conducted on
math reasoning tasks. The primary reason for this
limitation is the lack of appropriate training data
for other reasoning tasks. As our method requires
a set of training data with chain-of-thought labels,
many existing reasoning tasks lack such annota-
tions, making it challenging to extend our experi-
ments beyond the current scope. Future research
may focus on identifying and developing suitable
datasets for a wider range of reasoning tasks to
fully evaluate the applicability and effectiveness of
our method across different reasoning tasks.
Acknowledgements
This work was done when Shichen Li was a vis-
iting student at the StatNLP Research Group of
SUTD. We would like to thank the anonymous re-
viewers, our meta-reviewer, and senior area chairs
for their constructive comments and support on
this work. This research/project is supported by
Ministry of Education, Singapore, under its Aca-
demic Research Fund (AcRF) Tier 2 Programme
(MOE AcRF Tier 2 Award No: MOET2EP20122-
0011), the National Research Foundation Singa-
pore and DSO National Laboratories under the
AI Singapore Program (AISG Award No: AISG2-
RP-2020-016), and Ministry of Education, Singa-
pore, under its Tier 3 Programme (The Award No.:
MOET320200004). Any opinions, findings and
conclusions or recommendations expressed in this
material are those of the authors and do not reflect
the views of the funding agencies.
References
Massih-Reza Amini, Vasilii Feofanov, Loïc
Pauletto, Emilie Devijver, and Yury Maximov.
2022. Self-training: A survey. arXiv preprint
arXiv:2202.12040 .
Shengnan An, Zexiong Ma, Zeqi Lin, Nanning Zheng,
Jian-Guang Lou, and Weizhu Chen. 2023. Learn-
ing from mistakes makes llm better reasoner. arXiv
preprint arXiv:2310.20689 .
Rohan Anil, Andrew M Dai, Orhan Firat, Melvin John-
son, Dmitry Lepikhin, Alexandre Passos, Siamak
Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng
Chen, et al. 2023. Palm 2 technical report. arXiv
preprint arXiv:2305.10403 .
Anthropic. 2023. Claude 2. https://www.anthropic.
com/news/claude-2 . Accessed: 2024-05-06.
Anthropic. 2024. The claude 3 model family: Opus,
sonnet, haiku. Accessed: 2024-05-06.
Zhangir Azerbayev, Hailey Schoelkopf, Keiran Paster,
Marco Dos Santos, Stephen McAleer, Albert Q Jiang,
Jia Deng, Stella Biderman, and Sean Welleck. 2024.
Llemma: An open language model for mathematics.
InProceedings of ICLR .
Yuntao Bai, Andy Jones, Kamal Ndousse, Amanda
Askell, Anna Chen, Nova DasSarma, Dawn Drain,
Stanislav Fort, Deep Ganguli, Tom Henighan, et al.
2022. Training a helpful and harmless assistant with
reinforcement learning from human feedback. arXiv
preprint arXiv:2204.05862 .
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, ArvindNeelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, Sandhini Agarwal, Ariel Herbert-V oss,
Gretchen Krueger, et al. 2020. Language models
are few-shot learners. In Proceedings of NeurIPS .
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, et al. 2021. Evaluating large
language models trained on code. arXiv preprint
arXiv:2107.03374 .
Aakanksha Chowdhery, Sharan Narang, Jacob Devlin,
Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul
Barham, Hyung Won Chung, Charles Sutton, Sebas-
tian Gehrmann, et al. 2022. Palm: Scaling language
modeling with pathways. Journal of Machine Learn-
ing Research .
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Yunxuan Li, Xuezhi
Wang, Mostafa Dehghani, Siddhartha Brahma, et al.
2024. Scaling instruction-finetuned language models.
Journal of Machine Learning Research , 25(70):1–53.
Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian,
Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro
Nakano, et al. 2021. Training verifiers to solve math
word problems. arXiv preprint arXiv:2110.14168 .
Stanley C. Fralick. 1967. Learning to recognize patterns
without a teacher. IEEE Trans. Inf. Theory .
Yao Fu, Hao Peng, Litu Ou, Ashish Sabharwal, and
Tushar Khot. 2023. Specializing smaller language
models towards multi-step reasoning. In Proceedings
of ICML .
Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon,
Pengfei Liu, Yiming Yang, Jamie Callan, and Gra-
ham Neubig. 2022. Pal: Program-aided language
models. arXiv preprint arXiv:2211.10435 .
Zhibin Gou, Zhihong Shao, Yeyun Gong, Yujiu Yang,
Minlie Huang, Nan Duan, Weizhu Chen, et al. 2024.
Tora: A tool-integrated reasoning agent for mathe-
matical problem solving. In Proceedings of ACL .
Caglar Gulcehre, Tom Le Paine, Srivatsan Srini-
vasan, Ksenia Konyushkova, Lotte Weerts, Abhishek
Sharma, Aditya Siddhant, Alex Ahern, Miaosen
Wang, Chenjie Gu, et al. 2023. Reinforced self-
training (rest) for language modeling. arXiv preprint
arXiv:2308.08998 .
Junxian He, Jiatao Gu, Jiajun Shen, and Marc’Aurelio
Ranzato. 2020. Revisiting self-training for neural
sequence generation. In Proceedings of ICLR .
Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul
Arora, Steven Basart, Eric Tang, Dawn Song, and
Jacob Steinhardt. 2021. Measuring mathematical
problem solving with the math dataset. In Proceed-
ings of NeurIPS .
Namgyu Ho, Laura Schmid, and Se-Young Yun. 2023.
Large language models are reasoning teachers. In
Proceedings of ACL .
Or Honovich, Thomas Scialom, Omer Levy, and Timo
Schick. 2022. Unnatural instructions: Tuning lan-
guage models with (almost) no human labor. arXiv
preprint arXiv:2212.09689 .
Marek Kadl ˇcík, Michal Štefánik, Ond ˇrej Sotolá ˇr, and
Vlastimil Martinek. 2023. Calc-x and calcformers:
Empowering arithmetical chain-of-thought through
interaction with symbolic systems. In Proceedings
of EMNLP .
Muhammad Khalifa, Lajanugen Logeswaran, Moon-
tae Lee, Honglak Lee, and Lu Wang. 2023. Grace:
Discriminator-guided chain-of-thought reasoning. In
Findings of EMNLP .
Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yu-
taka Matsuo, and Yusuke Iwasawa. 2022. Large lan-
guage models are zero-shot reasoners. In Proceed-
ings of NeurIPS .
Chengpeng Li, Zheng Yuan, Guanting Dong, Keming
Lu, Jiancan Wu, Chuanqi Tan, Xiang Wang, and
Chang Zhou. 2023a. Query and response augmenta-
tion cannot help out-of-domain math reasoning gen-
eralization. arXiv preprint arXiv:2310.05506 .
Yifei Li, Zeqi Lin, Shizhuo Zhang, Qiang Fu, Bei Chen,
Jian-Guang Lou, and Weizhu Chen. 2023b. Making
language models better reasoners with step-aware
verifier. In Proceedings of ACL .
Ilya Loshchilov and Frank Hutter. 2019. Decoupled
weight decay regularization. In Proceedings of ICLR .
Haipeng Luo, Qingfeng Sun, Can Xu, Pu Zhao, Jian-
guang Lou, Chongyang Tao, Xiubo Geng, Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. 2023. Wiz-
ardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct.
arXiv preprint arXiv:2308.09583 .
Lucie Charlotte Magister, Jonathan Mallinson, Jakub
Adamek, Eric Malmi, and Aliaksei Severyn. 2023.
Teaching small language models to reason. In Pro-
ceedings of ACL .
Meta. 2024. Llama 3. https://llama.meta.com/
llama3/ . Accessed: 2024-06-01.
Shen-yun Miao, Chao-Chun Liang, and Keh-Yih Su.
2020. A diverse corpus for evaluating and developing
english math word problem solvers. In Proceedings
of ACL .
OpenAI. 2023. Gpt-4 technical report. arXiv preprint
arXiv:2303.08774 .
Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Car-
roll L. Wainwright, Pamela Mishkin, Chong Zhang,
Sandhini Agarwal, Katarina Slama, Alex Ray, John
Schulman, Jacob Hilton, Fraser Kelton, Luke E.Miller, Maddie Simens, Amanda Askell, Peter Welin-
der, Paul Francis Christiano, Jan Leike, and Ryan J.
Lowe. 2022. Training language models to follow
instructions with human feedback. In Proceedings of
NeurIPS .
Aaron Parisi, Yao Zhao, and Noah Fiedel. 2022. Talm:
Tool augmented language models. arXiv preprint
arXiv:2205.12255 .
Arkil Patel, Satwik Bhattamishra, and Navin Goyal.
2021. Are NLP models really able to solve simple
math word problems? In Proceedings of NAACL .
Alec Radford, Jeff Wu, Rewon Child, David Luan,
Dario Amodei, and Ilya Sutskever. 2019. Language
models are unsupervised multitask learners. OpenAI
blog.
Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano
Ermon, Christopher D Manning, and Chelsea Finn.
2023. Direct preference optimization: Your language
model is secretly a reward model. In Proceedings of
NeurIPS .
Colin Raffel, Noam M. Shazeer, Adam Roberts, Kather-
ine Lee, Sharan Narang, Michael Matena, Yanqi
Zhou, Wei Li, and Peter J. Liu. 2019. Exploring the
limits of transfer learning with a unified text-to-text
transformer. Journal of Machine Learning Research .
Subhro Roy and Dan Roth. 2015. Solving general arith-
metic word problems. In Proceedings of EMNLP .
Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta
Raileanu, Maria Lomeli, Luke Zettlemoyer, Nicola
Cancedda, and Thomas Scialom. 2023. Toolformer:
Language models can teach themselves to use tools.
InProceedings of NeurIPS .
John Schulman, Filip Wolski, Prafulla Dhariwal,
Alec Radford, and Oleg Klimov. 2017. Proxi-
mal policy optimization algorithms. arXiv preprint
arXiv:1707.06347 .
H. J. Scudder. 1965. Probability of error of some adap-
tive pattern-recognition machines. IEEE Trans. Inf.
Theory .
Kumar Shridhar, Alessandro Stolfo, and Mrinmaya
Sachan. 2023. Distilling reasoning capabilities into
smaller language models. In Findings of ACL .
Avi Singh, John D Co-Reyes, Rishabh Agarwal, Ankesh
Anand, Piyush Patil, Peter J Liu, James Harri-
son, Jaehoon Lee, Kelvin Xu, Aaron Parisi, et al.
2023. Beyond human data: Scaling self-training
for problem-solving with language models. arXiv
preprint arXiv:2312.06585 .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timothée Lacroix,
Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Tu Vu, Minh-Thang Luong, Quoc Le, Grady Simon,
and Mohit Iyyer. 2021. STraTA: Self-training with
task augmentation for better few-shot learning. In
Proceedings of EMNLP .
Ben Wang and Aran Komatsuzaki. 2021. GPT-J-
6B: A 6 Billion Parameter Autoregressive Lan-
guage Model. https://github.com/kingoflolz/
mesh-transformer-jax .
Tianduo Wang and Wei Lu. 2022. Differentiable data
augmentation for contrastive sentence representation
learning. In Proceedings of EMNLP .
Tianduo Wang and Wei Lu. 2023. Learning multi-step
reasoning by solving arithmetic tasks. In Proceed-
ings of ACL .
Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel,
Barret Zoph, Sebastian Borgeaud, Dani Yogatama,
Maarten Bosma, Denny Zhou, Donald Metzler, et al.
2022a. Emergent abilities of large language models.
Transactions on Machine Learning Research .
Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten
Bosma, Ed Chi, Quoc Le, and Denny Zhou. 2022b.
Chain of thought prompting elicits reasoning in large
language models. In Proceedings of NeurIPS .
Thomas Wolf, Lysandre Debut, Victor Sanh, Julien
Chaumond, Clement Delangue, Anthony Moi, Pier-
ric Cistac, Tim Rault, et al. 2020. Transformers:
State-of-the-art natural language processing. In Pro-
ceedings of EMNLP .
Qizhe Xie, Zihang Dai, Eduard Hovy, Thang Luong, and
Quoc Le. 2020. Unsupervised data augmentation for
consistency training. In Proceedings of NeurIPS .
Can Xu, Qingfeng Sun, Kai Zheng, Xiubo Geng,
Pu Zhao, Jiazhan Feng, Chongyang Tao, and Daxin
Jiang. 2023. Wizardlm: Empowering large lan-
guage models to follow complex instructions. arXiv
preprint arXiv:2304.12244 .
Longhui Yu, Weisen Jiang, Han Shi, Jincheng Yu,
Zhengying Liu, Yu Zhang, James T Kwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. 2024. Meta-
math: Bootstrap your own mathematical questions
for large language models. In Proceedings of ICLR .
Zheng Yuan, Hongyi Yuan, Chengpeng Li, Guanting
Dong, Chuanqi Tan, and Chang Zhou. 2023. Scal-
ing relationship on learning mathematical reason-
ing with large language models. arXiv preprint
arXiv:2308.01825 .Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wen-
hao Huang, Huan Sun, Yu Su, and Wenhu Chen.
2023. Mammoth: Building math generalist models
through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 .
Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Good-
man. 2022. Star: Bootstrapping reasoning with rea-
soning. In Proceedings of NeurIPS .
A Additional Implementation Details
Our models are trained using the AdamW opti-
mizer (Loshchilov and Hutter, 2019) with a weight
decay of 0.01 and gradient clipping of 1.0. We em-
ploy a cosine learning rate schedule with warm-up.
During training, the maximum sequence lengths
are set to 500 for T5 models and 640 for Llama
models. Both T5 and Llama models undergo DPO-
ST for three iterations, using the same set of hyper-
parameters for each iteration as detailed in Table 5.
For each DPO step, we sample 5 pseudo-labels per
question from the SFT model to build the DPO
training data, and set β= 0.1during DPO training.
In SFT steps, the number of model-generated so-
lutions per question can be varied and controlled
by the hyperparameter K. When sampling pseudo-
labels, we limit the maximum generated tokens to
300 and use a temperature of 0.7.
Flan-T5 LLaMA
Hyperparameters SFT DPO SFT DPO
Batch size 96 96 128 128
Epochs 8 - 2 -
Max steps - 150 - 100
Learning rate 3e-4 7e-7 2e-5 3e-7
Warm-up ratio 0.1 0.1 0.03 0.03
Table 5: Training details of SFT and DPO steps for
Flan-T5 and Llama models. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18227v1 | http://arxiv.org/pdf/2407.18227v1 | Automated Ensemble Multimodal Machine Learning for Healthcare | Fergus Imrie, Stefan Denner, Lucas S. Brunschwig, Klaus Maier-Hein, Mihaela van der Schaar | 2024-07-25 | Abstract
The application of machine learning in medicine and healthcare has led
to the creation of numerous diagnostic and prognostic models. However,
despite their success, current approaches generally issue predictions using
data from a single modality. This stands in stark contrast with clini-
cian decision-making which employs diverse information from multiple
sources. While several multimodal machine learning approaches exist,
significant challenges in developing multimodal systems remain that are
hindering clinical adoption. In this paper, we introduce a multimodal
framework, AutoPrognosis-M, that enables the integration of structured
clinical (tabular) data and medical imaging using automated machine
learning. AutoPrognosis-M incorporates 17 imaging models, including
convolutional neural networks and vision transformers, and three dis-
tinct multimodal fusion strategies. In an illustrative application using
a multimodal skin lesion dataset, we highlight the importance of mul-
timodal machine learning and the power of combining multiple fusion
strategies using ensemble learning. We have open-sourced our framework
as a tool for the community and hope it will accelerate the uptake of
multimodal machine learning in healthcare and spur further innovation.
Preprint
1arXiv:2407.18227v1 [cs.LG] 25 Jul 2024
2 AutoPrognosis-Multimodal | Introduction
Medical and healthcare data is increasingly diverse in origin and nature,
encompassing patient records and imaging to genetic information and real-time
biometrics. Machine learning (ML) can learn complex relationships from data
to construct powerful predictive models. As a result, ML is increasingly being
proposed in medicine and healthcare, particularly for diagnostic and prog-
nostic modeling [1, 2]. However, such approaches typically make predictions
based on only one type of data [3] and thus cannot incorporate all available
information or consider the broader clinical context.
In contrast, clinicians make decisions based on the synthesis of informa-
tion from multiple sources, including imaging, structured clinical or laboratory
data, and clinical notes [4]. This can be critical for accurate diagnoses and prog-
noses, and the absence of such information has been shown to result in lower
performance and decreased clinical utility in numerous studies [5, 6]. While
true across healthcare, this is perhaps particularly the case in medical imag-
ing. For example, almost 90% of radiologists reported that additional clinical
information was important and could change diagnoses compared to using the
imaging alone [7]. Numerous other examples of the importance of clinical con-
text for medical image analysis exist across specialties such as ophthalmology
[8], pathology [9], and dermatology [10].
Multimodal machine learning integrates multiple types and sources of data,
offering a more holistic approach to model development that mirrors clinical
decision-making processes. As a result, while multimodal ML remains in its
infancy, models that incorporate multiple data modalities have been developed
for several medical domains including cardiology [11], dermatology [12], oncol-
ogy [13, 14], and radiology [15]. However, technical challenges in developing,
understanding, and deploying multimodal ML systems are currently prevent-
ing broad adoption in medicine beyond bespoke individual examples. Thus,
techniques that reduce these obstacles could have substantial benefits across
numerous applications and clinical use cases.
In this paper, we propose a general-purpose approach that addresses these
challenges using automated machine learning (AutoML) and ensemble learn-
ing. AutoML can help design powerful ML pipelines by determining the most
appropriate modeling and hyperparameter choices, while requiring minimal
technical expertise from the user. To bridge the gap between clinicians and
cutting-edge ML, we previously proposed an AutoML approach, AutoProgno-
sis [16], for constructing ensemble ML-based diagnostic and prognostic models
using structured data. AutoPrognosis has been used to develop clinical mod-
els for a number of outcomes, including cardiovascular disease [17, 18], cystic
fibrosis [19], breast cancer [20], and lung cancer [21]. While AutoPrognosis has
been shown to yield promising results across a range of medical areas, it is
constrained to only handling tabular features. Several other frameworks for
automated pipeline optimization, such as Auto-sklearn [22], Auto-Weka [23],
and TPOT [24], suffer from the same limitation.
AutoPrognosis-Multimodal 3
Explanations
Modality 1Modality n
…Unimodal ModelUnimodal Model(a) How predictive is each modality? PredictionsPredictionsModality 1
Modality n…Multimodal Model(b) What is the value of a new modality?PredictionsPredictionsModality n-1Modality 1…Modality n-1+Multimodal Model(c) When is additional information required?Modality 1…Multimodal ModelPredictionsModality nUncertainty+(d) How do modalities interact?Modality 1…Multimodal ModelModality n
PredictionsModality 1…Multimodal Approach 1Modality n(e) What is the most predictive multimodal model?Multimodal Approach n…
Fig. 1 :Overview of the types of questions that can be asked with
multimodal machine learning. In addition to developing powerful mul-
timodal models (e), multimodal ML can help understand the value of each
modality (a), the impact of adding a new modality (b), when an additional
modality is required (c), and how the information in different modalities inter-
acts (d).
Consequently, in this work, we developed AutoPrognosis-Multimodal
(AutoPrognosis-M), an AutoML framework that incorporates data from multi-
ple modalities, namely imaging and tabular data. Additionally, AutoPrognosis-
M enables such models to be interrogated with explainable AI and provides
uncertainty estimates using conformal prediction, aiding understanding and
helping build model trust [25].
We applied our approach in an illustrative clinical scenario: skin lesion diag-
nosis using both images and clinical features. Our experiments demonstrate
the benefit of incorporating information from multiple modalities and high-
light the impact of the multimodal learning strategy on model performance.
We show different strategies can be effectively combined to form ensemble
models that substantially outperform any individual approach. Additionally,
we quantify the value of information from each modality and show how our
framework can be used to determine whether additional data is necessary on
an individual patient basis.
While our experiments focus on skin lesion diagnosis, we emphasize that
AutoPrognosis-M is a general-purpose approach that can be used to train mul-
timodal diagnostic and prognostic models for any disease or clinical outcome,
without requiring substantial ML expertise, and can help answer a range of
clinical questions (Fig. 1). We have open-sourced AutoPrognosis-M as a tool
for the community to aid the clinical adoption of multimodal ML models.
4 AutoPrognosis-Multimodal
AutoPrognosis-Multimodal
Joint FusionLate FusionFusion StrategiesEarly FusionExplanations
71%
Medical ImagesTabular DataTabular ModelsPreprocessingImputation
Tabular Pipelines
Image ModelingMultimodal EnsemblePredictionsUncertaintyVision TransformersConvolutional Neural Nets
Transformer1234Projection
Fig. 2 :Overview of AutoPrognosis-M. AutoPrognosis-M leverages auto-
mated machine learning to produce multimodal ensembles by optimizing
state-of-the-art image and tabular modeling approaches across three fusion
strategies. AutoPrognosis-M also enables such models to be interrogated with
explainable AI and provides uncertainty estimates using conformal prediction. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Methods: AutoPrognosis-M
AutoPrognosis-M enables clinicians and other users to develop diagnostic and
prognostic models for a diverse range of applications using state-of-the-art
multimodal ML (Fig. 2). Perhaps the most significant challenge is the complex
design space of model architectures and associated hyperparameters, which
must be set appropriately for the specific task and data being considered. Fail-
ure to do so can significantly degrade performance; however, this often requires
significant ML knowledge and expertise to do so effectively. This challenge is
further compounded in the multimodal setting by the different possible ways
of integrating data from multiple sources.
To address this, our framework employs AutoML [23] to efficiently and
effectively search the model and hyperparameter space. AutoPrognosis-M con-
structs powerful ensemble multimodal ML models designed for the specific
problem and data under consideration. While incorporating multiple modal-
ities can improve predictive power, this may not always be the case or a
modality might be particularly expensive to acquire. Thus, it is important to
understand the importance of each modality individually, and the added value
of including an additional modality (Fig. 1a-b). AutoPrognosis-M can opti-
mize both unimodal models and multimodal models, allowing the value of each
modality to be assessed, both separately and in combination with other sources
of information, as well as enabling models to be debugged and understood
using techniques from explainable AI (Fig. 2).
AutoPrognosis-Multimodal 5
By automating the optimization of ML pipelines across multiple modalities
and determining the most suitable way of combining the information from dis-
tinct sources, we reduce the barrier for non-ML experts, such as clinicians and
healthcare professionals, to build powerful multimodal ML models for problems
in the healthcare and medicine domains. We believe that AutoPrognosis-M
significantly simplifies the process of training and validating multimodal ML
models without compromising on the expressiveness or quality of the ML
models considered.
Automated Machine Learning
AutoML aims to simplify and automate the process of designing and train-
ing ML models, thereby reducing the technical capabilities required to develop
effective models. Human practitioners have biases about what model architec-
tures or hyperparameters will provide the best | Section not found | Section not found | Section not found | results across a range of medical areas, it is
constrained to only handling tabular features. Several other frameworks for
automated pipeline optimization, such as Auto-sklearn [22], Auto-Weka [23],
and TPOT [24], suffer from the same limitation.
AutoPrognosis-Multimodal 3
Explanations
Modality 1Modality n
…Unimodal ModelUnimodal Model(a) How predictive is each modality? PredictionsPredictionsModality 1
Modality n…Multimodal Model(b) What is the value of a new modality?PredictionsPredictionsModality n-1Modality 1…Modality n-1+Multimodal Model(c) When is additional information required?Modality 1…Multimodal ModelPredictionsModality nUncertainty+(d) How do modalities interact?Modality 1…Multimodal ModelModality n
PredictionsModality 1…Multimodal Approach 1Modality n(e) What is the most predictive multimodal model?Multimodal Approach n…
Fig. 1 :Overview of the types of questions that can be asked with
multimodal machine learning. In addition to developing powerful mul-
timodal models (e), multimodal ML can help understand the value of each
modality (a), the impact of adding a new modality (b), when an additional
modality is required (c), and how the information in different modalities inter-
acts (d).
Consequently, in this work, we developed AutoPrognosis-Multimodal
(AutoPrognosis-M), an AutoML framework that incorporates data from multi-
ple modalities, namely imaging and tabular data. Additionally, AutoPrognosis-
M enables such models to be interrogated with explainable AI and provides
uncertainty estimates using conformal prediction, aiding understanding and
helping build model trust [25].
We applied our approach in an illustrative clinical scenario: skin lesion diag-
nosis using both images and clinical features. Our experiments demonstrate
the benefit of incorporating information from multiple modalities and high-
light the impact of the multimodal learning strategy on model performance.
We show different strategies can be effectively combined to form ensemble
models that substantially outperform any individual approach. Additionally,
we quantify the value of information from each modality and show how our
framework can be used to determine whether additional data is necessary on
an individual patient basis.
While our experiments focus on skin lesion diagnosis, we emphasize that
AutoPrognosis-M is a general-purpose approach that can be used to train mul-
timodal diagnostic and prognostic models for any disease or clinical outcome,
without requiring substantial ML expertise, and can help answer a range of
clinical questions (Fig. 1). We have open-sourced AutoPrognosis-M as a tool
for the community to aid the clinical adoption of multimodal ML models.
4 AutoPrognosis-Multimodal
AutoPrognosis-Multimodal
Joint FusionLate FusionFusion StrategiesEarly FusionExplanations
71%
Medical ImagesTabular DataTabular ModelsPreprocessingImputation
Tabular Pipelines
Image ModelingMultimodal EnsemblePredictionsUncertaintyVision TransformersConvolutional Neural Nets
Transformer1234Projection
Fig. 2 :Overview of AutoPrognosis-M. AutoPrognosis-M leverages auto-
mated machine learning to produce multimodal ensembles by optimizing
state-of-the-art image and tabular modeling approaches across three fusion
strategies. AutoPrognosis-M also enables such models to be interrogated with
explainable AI and provides uncertainty estimates using conformal prediction.
Methods: AutoPrognosis-M
AutoPrognosis-M enables clinicians and other users to develop diagnostic and
prognostic models for a diverse range of applications using state-of-the-art
multimodal ML (Fig. 2). Perhaps the most significant challenge is the complex
design space of model architectures and associated hyperparameters, which
must be set appropriately for the specific task and data being considered. Fail-
ure to do so can significantly degrade performance; however, this often requires
significant ML knowledge and expertise to do so effectively. This challenge is
further compounded in the multimodal setting by the different possible ways
of integrating data from multiple sources.
To address this, our framework employs AutoML [23] to efficiently and
effectively search the model and hyperparameter space. AutoPrognosis-M con-
structs powerful ensemble multimodal ML models designed for the specific
problem and data under consideration. While incorporating multiple modal-
ities can improve predictive power, this may not always be the case or a
modality might be particularly expensive to acquire. Thus, it is important to
understand the importance of each modality individually, and the added value
of including an additional modality (Fig. 1a-b). AutoPrognosis-M can opti-
mize both unimodal models and multimodal models, allowing the value of each
modality to be assessed, both separately and in combination with other sources
of information, as well as enabling models to be debugged and understood
using techniques from explainable AI (Fig. 2).
AutoPrognosis-Multimodal 5
By automating the optimization of ML pipelines across multiple modalities
and determining the most suitable way of combining the information from dis-
tinct sources, we reduce the barrier for non-ML experts, such as clinicians and
healthcare professionals, to build powerful multimodal ML models for problems
in the healthcare and medicine domains. We believe that AutoPrognosis-M
significantly simplifies the process of training and validating multimodal ML
models without compromising on the expressiveness or quality of the ML
models considered.
Automated Machine Learning
AutoML aims to simplify and automate the process of designing and train-
ing ML models, thereby reducing the technical capabilities required to develop
effective models. Human practitioners have biases about what model architec-
tures or hyperparameters will provide the best results for a specific task. While
this might be helpful in some cases, often it will not and can cause inconsistency
in the quality of the final predictive system [26]. AutoML helps minimize these
biases by automatically searching over a more general set of models, hyper-
parameters, and other design choices to optimize a given objective function,
returning the best configurations found. Beyond simply minimizing human
biases, AutoML reduces the demand for human experts and has been shown
to typically match or exceed the skilled human performance [27].
Unimodal approaches
Tabular
We implement the tabular component of our multimodal framework using
AutoPrognosis 2.0 [16]. In contrast to many other approaches for learning from
tabular data, we consider full ML pipelines , rather than just predictive models,
consisting of missing data imputation, feature processing, model selection, and
hyperparameter optimization. AutoPrognosis includes implementations for 22
classification algorithms, nine imputation algorithms, including mean imputa-
tion, MICE [28], and MissForest [29], five dimensionality reduction, such as
PCA, and six feature scaling algorithms. The best-performing pipelines are
then combined into an ensemble via either a learned weighting or stacking,
where a meta-model is trained on the output of the underlying pipelines. For
further detail, we refer the reader to Imrie et al. [16]
Imaging
For imaging tasks, we employ a several distinct model architectures to cater to
a wide range of diagnostic and prognostic applications. Specifically, we utilized
Convolutional Neural Networks (CNNs), including ResNet [30], EfficientNet
[31], and MobileNetV2 [32], as well as Vision Transformers (ViTs) [33]. Each
model architecture is available in several sizes to be able to handle different
6 AutoPrognosis-Multimodal
-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Unimodal
ModelUnimodal
Model
Prediction Prediction
Combine
Final
Prediction
(a) Late Fusion-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Feature
ExtractorFeature
Extractor
Predictor
Final
Prediction
(b) Early FusionExtracted Features Extracted Features
Combine-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Feature
ExtractorFeature
Extractor
Predictor
Final
Prediction
(c) Joint FusionExtracted Features Extracted Features
Combine
LossLoss Loss
Loss LossLoss Loss
Fig. 3 :Illustration of the three types of multimodal fusion. (a) Late
fusion combines the predictions of separate unimodal models. (b) Early fusion
trains a predictive model on the combination of fixed extracted features. (c)
Joint fusion flexibly integrates multiple modalities, learning to extract repre-
sentations and make predictions simultaneously in an end-to-end manner.
task complexities. A full list of the 17 imaging models provided, together with
additional details, can be found in Table S.1.
While general-purpose models for tabular data do not exist, the transfer-
ability of imaging models has been shown in a diverse range of disciplines
[34, 35], and can be particularly effective when there is limited available data
for a particular problem. Pretrained models are especially useful when the
available data for a specific task is scarce or when computational resources are
limited. They allow one to leverage learned features and patterns from vast
datasets, potentially improving performance on related tasks.
While most models are pretrained in a supervised manner, self-supervised
pretraining has been shown to improve performance on many classification
tasks. Thus, in addition to supervised ViT [33], we also consider DINOv2 [36].
One approach to using pretrained models for new prediction tasks is to extract
a fixed representation and train a new classification head on the available task-
specific data. However, often these representations are not well adapted for
the specific data under consideration, especially when transferring from the
natural image to the medical image domain. In this case, we can train these
models further by fine-tuning the entire model on the available data. Fine-
tuning is most important when the target task or domain is related but not
identical to the one on which the model was originally trained by adapting
the generalized capabilities of the pretrained model to specific needs without
the necessity of training a model from scratch. The optimal training strategy
depends on the specific task, availability of data, and computational resources.
AutoPrognosis-M can be used to train vision models from scratch, use their
existing representations, or finetune on the available data.
AutoPrognosis-Multimodal 7
Multimodal data integration
Multimodal ML seeks to train a model that effectively integrates multiple
types of data to enable more accurate predictions than can be obtained using
any single modality. Modalities can exhibit different relationships, including
redundancy, depending on the interactions between the information contained
in each source [37], which can additionally vary in complexity. Thus a key
challenge is discerning the relation between modalities and learning how to
integrate modalities most effectively.
We can typically decompose multimodal architectures into two compo-
nents: modality-specific representations and a joint prediction [37]. Multimodal
learning strategies differ primarily in the nature of these components and
whether they are jointly or separately learned. Three main multimodal strate-
gies exist and are incorporated in AutoPrognosis-M: Late Fusion, Early Fusion,
and Joint Fusion (Fig. 3).
Late Fusion
Late fusion is an ensemble-based approach that combines predictions from
multiple unimodal models, and thus is sometimes referred to as decision-
level fusion [38] (Fig. 3a). Each modality is processed independently using a
modality-specific model before the predictions are combined. This allows the
user to find the best classifier for each modality independently and evaluate
whether each modality has predictive power for the original task. However, this
has the drawback of not permitting interactions between modalities before the
final output, which could result in suboptimal performance when the relation-
ship between modalities is crucial for making accurate predictions or decisions.
One benefit of late fusion is the ability to incorporate new modalities by adding
an additional unimodal model and retraining only the ensembling step. We
implement late fusion using a weighted combination of unimodal tabular and
imaging models.
Early fusion
Early fusion necessitates the translation of each modality into a representation
that can be combined using a fusion module, such as concatenation, into a
single, unified representation (Fig. 3b). The combined representation is then
used as input to train a separate predictive model.
Compared to late fusion, early fusion allows interactions between different
modalities to be captured by the predictive model. However, the represen-
tations are fixed and translating different data types into effective (latent)
representations to form a unified representation can be challenging, especially
when dealing with heterogeneous data sources with differing scales, dimensions,
or types of information.
For image data, a common strategy is to use an intermediate (or the last)
layer of a vision model that was either trained to solve the relevant prediction
task or a general-purpose imaging model. For tabular data, especially if the
8 AutoPrognosis-Multimodal
number of features is relatively modest, the representation step can be skipped
and the original features are directly combined with the latent representations
extracted from the other modalities. We used concatenation to combine the
imaging and tabular features and trained a fully connected neural network on
this representation.
Joint Fusion
The fixed, independent representations used in early fusion may not capture
relevant factors for the joint prediction task. Joint fusion [4] (or intermediate
fusion [39]) aims to improve these representations using joint optimization
to enable both cross-modal relationships and modality-specific features to be
learned using end-to-end training (Fig. 3c). The added flexibility of joint fusion
can come at the cost of potentially overfitting, especially in the limited data
setting.
The most popular approaches for joint fusion use differentiable unimodal
models to produce latent representations that are combined via concatenation
and passed to a prediction head. The system is then trained in an end-to-
end manner, either from scratch or using pre-trained unimodal models. We
implement joint fusion similarly to early fusion, except we train end-to-end.
Fusion Ensembles
One major challenge is determining which fusion approach is best. Further, no
individual fusion approach may be universally best for all patients. Ensembling
has repeatedly been shown to lead to improved model performance, even when
multiple copies of the same model are trained, but can be particularly bene-
ficial when different approaches are combined due to the increased diversity
of predictions [40]. The three fusion approaches learn to combine the informa-
tion from multiple modalities in distinct ways. Thus combining the strengths
of these different strategies via an ensembling approach could improve both
the absolute performance and the robustness of the final model. We combine
the best-performing unimodal and multimodal fusion approaches in a weighted
ensemble. All ensembles were determined using Bayesian optimization [41]. We
refer to this ensemble as AutoPrognosis-M in our experiments.
Explainability
Models must be thoroughly understood and debugged to validate the under-
lying logic of the model, engender model trust from both clinical users and
patients [25], and satisfy regulatory requirements prior to clinical use [42]. This
is particularly true in the multimodal setting, where we wish to understand
what information is being used from each modality and for which patients each
modality is contributing to the model output. Consequently, AutoPrognosis-M
contains multiple classes of explainability techniques to enable ML mod-
els to be better understood. We have included feature-based interpretability
methods, such as SHAP [43] and Integrated Gradients [44], that allow us to
AutoPrognosis-Multimodal 9
understand the importance of individual features, as well as an example-based
interpretability method, SimplEx [45], that explains the model output for a
particular sample with examples of similar instances, similar to case-based
reasoning.
Uncertainty estimation
Quantifying the uncertainty of predictions is another critical component
in engendering model trust with both clinicians and patients, and can be
used both to protect against likely inaccurate predictions and inform clinical
decision-making [46, 47]. We adopted the conformal prediction framework for
uncertainty quantification. Conformal prediction produces statistically valid
prediction intervals or sets for any underlying predictor while making mini-
mal assumptions [48]. We used inductive conformal prediction [49], which uses
a calibration set to determine the width of prediction intervals or the neces-
sary size of the prediction sets, with local adaptivity to adjust the interval or
set to the specific example [50–52]. For our experiments, we used regularized
adaptive prediction sets [53].
Experiments
We demonstrate the application of AutoPrognosis-M to multimodal healthcare
data with the example of skin lesion diagnosis. This task is inherently a mul-
timodal process: primary care physicians, dermatologists, or other clinicians
use multiple factors to determine a diagnosis. Visual inspection has formed a
crucial element in lesion diagnosis, for example the “ABCD” rule or the ELM
7-point checklist [54]. These approaches have been refined to include other
characteristics beyond the appearance of the lesion at a single point in time,
such as evolution [55]. Beyond visual examination, clinicians also consider
medical history and other factors, such as itching and bleeding [10].
Data
Experiments were conducted using PAD-UFES-20 [56]. The dataset contains
2,298 skin lesion images from 1,373 patients in Brazil. Images of lesions were
captured from smartphones and each image is associated with 21 tabular fea-
tures, including the patient’s age, the anatomical region where the lesion is
located, demographic information, and other characteristics of the legion, such
as whether it itched, bled, or had grown. An overview of the clinical features
can be found in Table S.2. Further details can be found in the publication
describing the dataset [56].
Skin lesions are classified as one of six different diagnoses, three of which are
cancerous (Basal Cell Carcinoma, Squamous Cell Carcinoma, and Melanoma)
and three are non-cancerous (Actinic Keratosis, Melanocytic Nevus, and Seb-
orrheic Keratosis). As is common in studies of skin lesions, there are substantial
10 AutoPrognosis-Multimodal
Table 1 :Unimodal skin legion classification performance. The best
result for each modality is in bold. The best non-ensemble approach for each
modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
Tabular
Log. Reg. 63.6% 63.3% 0.890 0.559 83.0% 0.904 0.814 0.657
Random Forest 65.2% 54.0% 0.865 0.535 83.0% 0.903 0.810 0.662
XGBoost 66.5% 54.4% 0.875 0.545 81.3% 0.885 0.797 0.623
CatBoost 64.3% 57.2% 0.877 0.545 83.4% 0.902 0.822 0.667
MLP 69.7% 52.8% 0.878 0.526 83.1% 0.902 0.819 0.663
AutoPrognosis 69.4% 61.9% 0.891 0.580 83.9% 0.909 0.825 0.676
Imaging
ResNet18 59.8% 57.8% 0.885 0.547 81.9% 0.897 0.808 0.637
ResNet34 57.4% 54.5% 0.873 0.517 80.3% 0.881 0.790 0.603
ResNet50 60.7% 60.0% 0.888 0.562 82.0% 0.888 0.811 0.637
ResNet101 60.3% 56.6% 0.886 0.543 81.6% 0.883 0.802 0.628
ResNet152 63.6% 59.6% 0.895 0.578 82.1% 0.892 0.810 0.640
EfficientNetB0 64.3% 60.8% 0.899 0.577 82.4% 0.900 0.807 0.645
EfficientNetB1 65.5% 63.7% 0.901 0.602 82.6% 0.899 0.811 0.648
EfficientNetB2 65.1% 59.7% 0.899 0.578 81.5% 0.888 0.801 0.628
EfficientNetB3 64.2% 62.6% 0.902 0.598 81.9% 0.898 0.805 0.635
EfficientNetB4 66.7% 62.1% 0.899 0.602 81.9% 0.897 0.807 0.635
EfficientNetB5 66.7% 62.8% 0.904 0.609 82.6% 0.903 0.810 0.649
MobileNetV2 58.4% 54.5% 0.868 0.512 79.6% 0.877 0.779 0.590
ViTBase 67.1% 65.0% 0.917 0.618 82.9% 0.913 0.816 0.657
ViTLarge 68.1% 65.2% 0.916 0.631 84.1% 0.916 0.831 0.682
DinoV2Small 68.1% 65.0% 0.913 0.630 84.2% 0.912 0.834 0.683
DinoV2Base 68.5% 65.9% 0.914 0.639 84.0% 0.913 0.833 0.679
DinoV2Large 69.0% 65.8% 0.916 0.640 84.4% 0.913 0.834 0.686
Imaging ensemble 71.6% 69.4% 0.927 0.672 85.3% 0.927 0.845 0.706
differences in the number of lesions with each diagnosis, resulting in class imbal-
ance (Table S.2). Aggregating the diagnoses into cancerous and non-cancerous
almost eliminates this imbalance (47% cancerous, 53% non-cancerous). To
demonstrate the suitability of our framework for balanced and imbalanced
classification scenarios, we explore both the task of predicting the specific diag-
noses and the binary determination of whether a given lesion is cancerous. We
assessed lesion categorization usin accuracy, balanced accuracy, area under the
receiver operating curve (AUROC), and macro F1 score, and assessed can-
cer diagnosis using accuracy, AUROC, F1 score and Matthew’s correlation
coefficient (MCC).
To account for the presence of multiple images for some patients and
the imbalance in incidence of different diagnoses, we conducted 5-fold cross-
validation with stratified sampling, ensuring all images from the same patient
were contained in the same fold. Additionally, we used 20% of the training
set of each fold to optimize hyperparameters and ensemble weights. 13 clinical
variables had substantial levels of missingness (c. 35%) and this missingness
was often strongly associated with diagnosis. Consequently, we retained only
features without this missingness. Some other features had entries recorded
AutoPrognosis-Multimodal 11
as “unknown,” corresponding to the patient being asked the question but not
knowing the answer. This was the case for six features, with an occurrence
between 0.1% and 17%. This resulted in eight tabular variables being retained.
Categorical variables were one-hot encoded, yielding 27 clinical features and
one image for each sample.
How predictive is each modality in isolation?
Collecting additional information is never without expense. This can be finan-
cial, time, or even adverse effects of collecting the information. Thus it is
critical to understand whether a modality is necessary and brings additional
predictive power. Therefore, we first used AutoPrognosis-M to optimize ML
pipelines for each modality separately to quantify the value of imaging and clin-
ical features individually. Both the clinical variables and lesion images exhibit
some predictive power for lesion categorization and cancer diagnosis (Table
1), with the individual imaging models outperforming the tabular models for
lesion categorization while achieving similar results for cancer diagnosis.
Tabular. We tested several classification models in isolation, as well as
the performance of AutoPrognosis-M on just the tabular modality, which is
equivalent to AutoPrognosis [16]. Overall, AutoPrognosis outperformed any
individual tabular model, in particular for cancer diagnosis, demonstrating
the importance of AutoML and ensembling (Table 1). However, the relative
outperformance over logistic regression for lesion categorization and CatBoost
for cancer diagnosis was relatively minor, perhaps reflecting the nature of the
structured information available.
Imaging. The different imaging architectures displayed significant vari-
ability in performance across the lesion categorization and cancer diagnosis
prediction tasks, however several trends could be observed. The vision trans-
former architectures (ViT and DINOv2) outperformed the CNN-based models
(ResNet, EfficientNet, MobileNet) almost universally across both tasks. One
explanation beyond the model architecture could be the pre-training set, which
differed between the transformer and CNN models (see Table S.1). Increas-
ing the size of models typically led to improvements in performance for the
transformer models, although the largest models did not necessarily improve
performance (e.g. DINOv2Large vs. DINOv2Base), while the trend was less
clear for the CNN-based models. All model architectures consistently under-
performed when trained from initialization, thus all results shown are from
fine-tuning pre-trained models.
Ensembling the best-performing image models resulted in a substantial
increase in performance across all metrics for both prediction tasks. While
the transformers outperformed the CNNs individually, many of the ensembles
contained CNN-based approaches, demonstrating the importance of diversity
in ensemble learning.
12 AutoPrognosis-Multimodal
Table 2 :Skin legion classification performance. All multimodal
approaches outperform the unimodal baselines. AutoPrognosis-M achieves the
best results.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
Tabular ensemble 69.4% 61.9% 0.891 0.580 83.9% 0.909 0.825 0.676
Best image model 68.5% 65.9% 0.914 0.639 84.4% 0.913 0.834 0.686
Imaging ensemble 71.6% 69.4% 0.927 0.672 85.3% 0.927 0.845 0.706
Best late fusion 77.0% 72.8% 0.935 0.706 89.2% 0.950 0.883 0.782
Late fusion ensemble 79.0% 74.7% 0.939 0.730 89.1% 0.954 0.882 0.781
Best early fusion 70.9% 68.1% 0.918 0.657 85.7% 0.922 0.847 0.713
Early fusion ensemble 74.7% 70.2% 0.930 0.701 86.7% 0.936 0.856 0.731
Best joint fusion 73.8% 71.4% 0.930 0.698 87.5% 0.940 0.866 0.748
Joint fusion ensemble 75.6% 71.9% 0.937 0.716 88.8% 0.951 0.880 0.775
AutoPrognosis-M 80.6% 75.8% 0.945 0.758 89.8% 0.956 0.889 0.794
What benefit does multimodal ML provide?
Now that we have shown that each modality has a potential predictive capa-
bility for skin lesion diagnoses, we sought to quantify what, if any, benefit
incorporating both modalities when issuing predictions provides. To do this,
we assessed each of the multimodal strategies included in AutoPrognosis-M.
All three fusion approaches demonstrate significant improvements over the
unimodal classifiers, demonstrating the importance of integrating data from
multiple sources. In Table 2, we report the best single model for each fusion
strategy, together with the impact of ensembling the best-performing models as
measured on the held-out portion of the training set. The impact of combining
the modalities varied across the various model architectures, with the results
also differing for each of the fusion strategies, late (Table S.3), early (Table
S.4), and joint (Table S.5).
Perhaps surprisingly, late fusion outperformed both early and joint fusion,
with early fusion the worst-performing fusion approach. This is likely a conse-
quence of the relatively strong predictive power of the tabular features and the
number of samples available, but could also reveal the nature of the relationship
between the two modalities. Again, ensembling the best-performing models for
each fusion strategy provides a relatively small but consistent improvement,
except for the cancer diagnosis task for late fusion, where the best individual
model performed similarly to the ensemble.
AutoPrognosis-M leverages the power of each fusion strategy and the uni-
modal models by combining them in an ensemble. This approach performed
best across both tasks as measured by any metric, improving the performance
over any one fusion approach alone. Despite late fusion outperforming the other
multimodal and unimodal approaches, it was not always selected as the most
important component in the ensemble and the largest weight assigned to any
of the five strategies (two unimodal, three fusion) was 39%, further reinforcing
the importance of diversity.
AutoPrognosis-Multimodal 13
0% 20% 40% 60% 80% 100%
Proportion Selected0%2%4%6%8%10%12%14%16%Absolute % gain in Bal. Acc.
T abular onlyMultimodalSelective Acquisition
(a) Lesion categorization
0% 20% 40% 60% 80% 100%
Proportion Selected0%1%2%3%4%5%6%7%Absolute % gain in Accuracy
T abular onlyMultimodalSelective Acquisition (b) Cancer diagnosis
Fig. 4 : Selective acquisition of images based on conformal prediction. By
acquiring images for around 20% of samples with the highest predicted uncer-
tainty based on the tabular features, we capture c. 55% and 65% of the
improvement of the multimodal classifier for (a) lesion categorization and (b)
cancer diagnosis, respectively. We approach the performance of the multimodal
classifier by acquiring images for around half of all patients.
When are additional modalities most helpful?
While we have shown multimodal systems significantly outperform unimodal
approaches for lesion categorization and cancer diagnosis, we might not require
all modalities for all patients. As mentioned previously, there might be down-
sides to collecting additional information, thus identifying when we would
benefit is both important and often a key clinical decision, since modalities are
typically acquired sequentially.
We demonstrate how AutoPrognosis-M can be used to answer this question.
We assumed access initially to the clinical features and wanted to identify for
which patients to acquire an image of the lesion. We used conformal prediction
to estimate the uncertainty of each prediction and chose to acquire images for
the patients with the highest uncertainty.
By acquiring images for around 20% of samples with the highest predicted
uncertainty based on the tabular features, we can capture around two-thirds
of the total improvement of the multimodal ensemble classifier for the cancer
diagnosis task (Fig. 4b) and over half for the lesion categorization task (Fig.
4a). Acquiring lesion images for around 50% of patients results in coming close
to matching the performance of the multimodal classifier, thereby halving the
number of images needed to be collected.
Understanding the information provided by each
modality
Understanding why predictions were issued is incredibly important across med-
ical contexts. We demonstrate how the interpretability techniques included in
14 AutoPrognosis-Multimodal
bleed_T
ruehurt_T
rueage itch_T
rueelevation_T
rueregion_NOSE changed_False grew_T
rue−0.1−0.0500.050.10.15Image Attributions - Image only Attributions - Joint fusion Tabular Attributions - Joint fusion
Label: BCC Pred: {BCC: 0.18, ACK: 0.00, NEV : 0.70,
SEK: 0.11, SCC: 0.00, MEL: 0.00}Pred: {BCC: 0.55, ACK: 0.01, NEV : 0.43,
SEK: 0.00, SCC: 0.01, MEL: 0.00}
Fig. 5 : Comparison of explanations for unimodal and multimodal models
using integrated gradients. The original image (left, img id: PAT 521984412)
together with attributions for the unimodal (center left) and joint fusion Effi-
cientNetB4 models (center right and right).
AutoPrognosis-M can be used to analyze the rationale for predictions across
multiple modalities. We used integrated gradients [44] to analyze the pre-
dictions from the image-only and joint fusion variants of EfficientNetB4. An
example is shown in Fig. 5.
The image-only model incorrectly classifies the lesion as Melanocytic Nevus
(NEV, non-cancerous), while the joint fusion model correctly identifies the
lesion as Basal Cell Carcinoma (BCC, cancerous). The image attributions (Fig.
5 center) are somewhat similar, both placing the most importance on the lesion,
although there are minor differences in several areas. Importantly, the clinical
variables allow the multimodal approach to correct the image-only prediction.
NEV is typically asymptomatic [57] and more common in younger individu-
als [58]. The patient reported the lesion had bled, hurt, and itched, which the
multimodal model correctly identified made NEV less likely and increased the
chance of BCC, offset by the relatively young age of the patient (32) which
reduced the magnitude of the BCC prediction. This example clearly demon-
strates the importance of incorporating both modalities and the understanding
that explainability methods can provide. | Section not found | Discussion
Predictive modeling has the potential to support clinical decision-making and
improve outcomes. However, incorporating multiple types of data into compu-
tational approaches is not yet widespread in medicine and healthcare. In this
paper, we demonstrated the utility of AutoPrognosis-M for developing clin-
ical models from multimodal data using AutoML. Our framework simplifies
the application of multimodal fusion strategies, automatically determining the
best strategy for the available data and clinical application.
We have shown how AutoPrognosis-M can be used to perform unimodal
analysis for tabular and imaging data, enabling clinicians to understand when
multimodal approaches will provide benefit. Beyond prediction, we used uncer-
tainty estimation to determine for which patients additional information is
necessary and explainability techniques to improve model understanding.
AutoPrognosis-Multimodal 15
The use of AutoML frameworks such as AutoPrognosis-M can aid in model
development, but does not alter the necessity to ensure models are suitably
validated to ensure they exhibit the desired characteristics, such as being accu-
rate, reliable, and fair. As with any learning algorithm, significant care must
be taken by the user to ensure appropriate study design and data curation,
without which an inaccurate or biased model could be developed which could
have adverse effects on patient health.
While there have been bespoke multimodal ML systems developed, few
general-purpose frameworks exist. HAIM [59] is an early fusion approach
using user-defined pre-trained feature-extraction models to extract represen-
tations that are concatenated and passed to an XGBoost model. Wang et
al. proposed a multimodal approach for esophageal variceal bleeding predic-
tion [60]. They first trained an imaging model and then used automated
machine learning to develop a classifier based on structured clinical data and
the output of the imaging model. Finally, AutoGluon-Multimodal [61] enables
fine-tuning of pretrained models across multiple modalities, combining their
outputs via late fusion. In contrast, AutoPrognosis-M incorporates multiple
fusion approaches, including both early and late fusion as possible strategies,
while our experiments highlight the | Section not found | Section not found | limitations of only considering a single
fusion strategy.
While in this paper, we demonstrated the application of AutoPrognosis-M
to the problem of diagnosing skin lesions using smartphone images and clinical
variables, our framework is generally applicable and can naturally be extended
to additional modalities and both new unimodal models and fusion strategies.
We believe AutoPrognosis-M represents a powerful tool for clinicians and ML
experts when working with data from multiple modalities and hope our aids
the adoption of multimodal ML methods in healthcare and medicine.
Code and data availability. AutoPrognosis-M is available at https:
//github.com/vanderschaarlab/AutoPrognosis-Multimodal. PAD-UFES-20 is
freely available at https://data.mendeley.com/datasets/zr7vgbcyr2/1 (DOI:
10.17632/zr7vgbcyr2.1) [56]. All preprocessing and the splits used for
our experiments can be found at https://github.com/vanderschaarlab/
AutoPrognosis-Multimodal. | Section not found | Section not found | Section not found | Section not found | References
[1] Abr` amoff, M. D., Lavin, P. T., Birch, M., Shah, N. & Folk, J. C. Pivotal
trial of an autonomous AI-based diagnostic system for detection of diabetic
retinopathy in primary care offices. npj Digit. Med. 1(1), 39 (2018). https:
//doi.org/10.1038/s41746-018-0040-6 .
[2] Rajpurkar, P., Chen, E., Banerjee, O. & Topol, E. J. AI in health and medicine.
Nat. Med. 28(1), 31–38 (2022). https://doi.org/10.1038/s41591-021-01614-0 .
[3] Kline, A. et al. Multimodal machine learning in precision health: A scop-
ing review. npj Digit. Med. 5(1), 171 (2022). https://doi.org/10.1038/
16 AutoPrognosis-Multimodal
s41746-022-00712-8 .
[4] Huang, S.-C., Pareek, A., Seyyedi, S., Banerjee, I. & Lungren, M. P. Fusion of
medical imaging and electronic health records using deep learning: A systematic
review and implementation guidelines. npj Digit. Med. 3(1), 136 (2020). https:
//doi.org/10.1038/s41746-020-00341-z .
[5] Leslie, A. & Jones, P. R., A. J.and Goddard. The influence of clinical informa-
tion on the reporting of CT by radiologists. Br. J. Radiol. 73(874), 1052–1055
(2000). https://doi.org/10.1259/bjr.73.874.11271897 .
[6] Castillo, C., Steffens, T., Sim, L. & Caffery, L. The effect of clinical information
on radiology reporting: A systematic review. J. Med. Radiat. Sci. 68(1), 60–74
(2021). https://doi.org/10.1002/jmrs.424 .
[7] Boonn, W. W. & Langlotz, C. P. Radiologist use of and perceived need for
patient data access. J. Digit. Imaging 22(4), 357–362 (2009). https://doi.org/
10.1007/s10278-008-9115-2 .
[8] Wang, M. Y., Asanad, S., Asanad, K., Karanjia, R. & Sadun, A. A. Value of
medical history in ophthalmology: A study of diagnostic accuracy. J. Curr.
Ophthalmol. 30(4), 359–364 (2018). https://doi.org/https://doi.org/10.1016/
j.joco.2018.09.001 .
[9] Ombrello, M. J., Sikora, K. A. & Kastner, D. L. Genetics, genomics, and their
relevance to pathology and therapy. Best Pract. Res.: Clin. Rheumatol. 28(2),
175–189 (2014). https://doi.org/https://doi.org/10.1016/j.berh.2014.05.001 .
[10] Bergenmar, M., Hansson, J. & Brandberg, Y. Detection of nodular and super-
ficial spreading melanoma with tumour thickness ≤2.0 mm - an interview
study. Eur. J. Cancer Prev. 11(1), 49–55 (2002). https://doi.org/10.1097/
00008469-200202000-00007 .
[11] Li, P., Hu, Y. & Liu, Z.-P. Prediction of cardiovascular diseases by integrating
multi-modal features with machine learning methods. Biomed. Signal Pro-
cess. Control. 66, 102474 (2021). https://doi.org/https://doi.org/10.1016/j.
bspc.2021.102474 .
[12] Liu, Y. et al. A deep learning system for differential diagnosis of skin dis-
eases. Nat. Med. 26(6), 900–908 (2020). URL https://doi.org/10.1038/
s41591-020-0842-3. https://doi.org/10.1038/s41591-020-0842-3 .
[13] Yala, A., Lehman, C., Schuster, T., Portnoi, T. & Barzilay, R. A deep learn-
ing mammography-based model for improved breast cancer risk prediction.
Radiology 292(1), 60–66 (2019). https://doi.org/10.1148/radiol.2019182716 .
[14] Kyono, T., Gilbert, F. J. & van der Schaar, M. Improving workflow efficiency
for mammography using machine learning. J. Am. Coll. Radiol. 17(1), 56–63
(2020). https://doi.org/10.1016/j.jacr.2019.05.012 .
AutoPrognosis-Multimodal 17
[15] Wu, J. et al. Radiological tumour classification across imaging modality and
histology. Nat. Mach. Intell. 3(9), 787–798 (2021). https://doi.org/10.1038/
s42256-021-00377-0 .
[16] Imrie, F., Cebere, B., McKinney, E. F. & van der Schaar, M. AutoProgno-
sis 2.0: Democratizing diagnostic and prognostic modeling in healthcare with
automated machine learning. PLOS Digit. Health 2(6), e0000276 (2023).
https://doi.org/10.1371/journal.pdig.0000276 .
[17] Alaa, A. M., Bolton, T., Di Angelantonio, E., Rudd, J. H. F. & van der Schaar,
M. Cardiovascular disease risk prediction using automated machine learning: A
prospective study of 423,604 UK Biobank participants. PLoS One 14(5), 1–17
(2019). https://doi.org/10.1371/journal.pone.0213653 .
[18] Imrie, F., Rauba, P. & van der Schaar, M. Redefining digital health interfaces
with large language models. arXiv preprint arXiv:2310.03560 (2023) .
[19] Alaa, A. M. & van der Schaar, M. Prognostication and risk factors for cystic
fibrosis via automated machine learning. Sci. Rep. 8(1), 11242 (2018). https:
//doi.org/10.1038/s41598-018-29523-2 .
[20] Alaa, A. M., Gurdasani, D., Harris, A. L., Rashbass, J. & van der Schaar,
M. Machine learning to guide the use of adjuvant therapies for breast can-
cer. Nat. Mach. Intell. 3(8), 716–726 (2021). https://doi.org/10.1038/
s42256-021-00353-8 .
[21] Callender, T. et al. Assessing eligibility for lung cancer screening using parsimo-
nious ensemble machine learning models: A development and validation study.
PLOS Med. 20(10), e1004287 (2023). https://doi.org/10.1371/journal.pmed.
1004287 .
[22] Feurer, M. et al. Efficient and robust automated machine learning. Adv. Neural
Inf. Process. Syst. 28, 2755–2763 (2015) .
[23] Thornton, C., Hutter, F., Hoos, H. H. & Leyton-Brown, K. Auto-WEKA: Com-
bined selection and hyperparameter optimization of classification algorithms.
Proceedings of the 19th ACM SIGKDD International Conference on Knowledge
Discovery and Data Mining 847–855 (2013). https://doi.org/10.1145/2487575.
2487629 .
[24] Olson, R. S. & Moore, J. H. TPOT: A tree-based pipeline optimization tool
for automating machine learning. In: International Conference on Machine
Learning - AutoML Workshop 66–74 (2016) .
[25] Imrie, F., Davis, R. & van der Schaar, M. Multiple stakeholders drive diverse
interpretability requirements for machine learning in healthcare. Nat. Mach.
Intell. 5(8), 824–829 (2023). https://doi.org/10.1038/s42256-023-00698-2 .
[26] Callender, T. & van der Schaar, M. Automated machine learning as a partner
in predictive modelling. Lancet Digit. Health 5(5), e254–e256 (2023). https:
//doi.org/10.1016/S2589-7500(23)00054-7 .
18 AutoPrognosis-Multimodal
[27] Waring, J., Lindvall, C. & Umeton, R. Automated machine learning: Review
of the state-of-the-art and opportunities for healthcare. Artif. Intell. Med. 104,
101822 (2020) .
[28] van Buuren, S. & Groothuis-Oudshoorn, K. mice: Multivariate imputation by
chained equations in R. J. Stat. Softw. 45(3), 1–67 (2011). https://doi.org/
10.18637/jss.v045.i03 .
[29] Stekhoven, D. J. & B¨ uhlmann, P. MissForest—non-parametric missing value
imputation for mixed-type data. Bioinformatics 28(1), 112–118 (2011). https:
//doi.org/10.1093/bioinformatics/btr597 .
[30] He, K., Zhang, X., Ren, S. & Sun, J. Deep residual learning for image recogni-
tion. In: Proceedings of the IEEE Conference on Computer Vision and Pattern
Recognition 770–778 (2016) .
[31] Tan, M. & Le, Q. EfficientNet: Rethinking model scaling for convolutional
neural networks. In: International Conference on Machine Learning 6105–6114
(2019) .
[32] Sandler, M., Howard, A., Zhu, M., Zhmoginov, A. & Chen, L.-C. MobileNetV2:
Inverted residuals and linear bottlenecks. In: Proceedings of the IEEE Confer-
ence on Computer Vision and Pattern Recognition 4510–4520 (2018) .
[33] Dosovitskiy, A. et al. An image is worth 16x16 words: Transformers for image
recognition at scale. In: International Conference on Learning Representations
(2021) .
[34] Weiss, K., Khoshgoftaar, T. M. & Wang, D. A survey of transfer learning. J.
Big Data 3, 1–40 (2016) .
[35] Zhuang, F. et al. A comprehensive survey on transfer learning. Proc. IEEE
109(1), 43–76 (2020) .
[36] Oquab, M. et al. DINOv2: Learning robust visual features without supervision.
Trans. Mach. Learn. Res. (2024) .
[37] Baltruˇ saitis, T., Ahuja, C. & Morency, L.-P. Multimodal machine learning: A
survey and taxonomy. IEEE Trans. Pattern Anal. Mach. Intell. 41(2), 423–443
(2019). https://doi.org/10.1109/TPAMI.2018.2798607 .
[38] Sharma, R., Pavlovic, V. I. & Huang, T. S. Toward multimodal human-
computer interface. Proc. IEEE 86(5), 853–869 (1998) .
[39] Stahlschmidt, S. R., Ulfenborg, B. & Synnergren, J. Multimodal deep learning
for biomedical data fusion: A review. Brief. Bioinform. 23(2), bbab569 (2022) .
[40] Krogh, A. & Vedelsby, J. Neural network ensembles, cross validation, and active
learning. Adv. Neural Inf. Process. Syst. 7(1994) .
AutoPrognosis-Multimodal 19
[41] Akiba, T., Sano, S., Yanase, T., Ohta, T. & Koyama, M. Optuna: A next-
generation hyperparameter optimization framework. In: Proceedings of the
25th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining 2623–2631 (2019) .
[42] Medicines & Healthcare products Regulatory Agency. Soft-
ware and ai as a medical device change programme -
roadmap (2023). URL https://www.gov.uk/government/
publications/software-and-ai-as-a-medical-device-change-programme/
software-and-ai-as-a-medical-device-change-programme-roadmap. Updated
14 June 2023 .
[43] Lundberg, S. M. & Lee, S.-I. A unified approach to interpreting model
predictions. Adv. Neural Inf. Process. Syst. 30(2017) .
[44] Sundararajan, M., Taly, A. & Yan, Q. Axiomatic attribution for deep networks.
In: International Conference on Machine Learning 3319–3328 (2017) .
[45] Crabbe, J., Qian, Z., Imrie, F. & van der Schaar, M. Explaining latent rep-
resentations with a corpus of examples. Adv. Neural Inf. Process. Syst. 34,
12154–12166 (2021) .
[46] Kompa, B., Snoek, J. & Beam, A. L. Second opinion needed: Communicating
uncertainty in medical machine learning. npj Digit. Med. 4(1), 4 (2021). https:
//doi.org/10.1038/s41746-020-00367-3 .
[47] Helou, M. A., DiazGranados, D., Ryan, M. S. & Cyrus, J. W. Uncertainty
in decision making in medicine: A scoping review and thematic analysis of
conceptual models. Acad. Med. 95(1) (2020) .
[48] Vovk, V., Gammerman, A. & Shafer, G. Algorithmic learning in a random world
(Springer Science & Business Media, 2005).
[49] Vovk, V. Conditional validity of inductive conformal predictors. In: Asian
Conference on Machine Learning 475–490 (2012) .
[50] Papadopoulos, H., Vovk, V. & Gammerman, A. Regression conformal prediction
with nearest neighbours. J. Artif. Intell. Res. 40, 815–840 (2011) .
[51] Johansson, U., S¨ onstr¨ od, C. & Linusson, H. Efficient conformal regressors using
bagged neural nets. In: 2015 International Joint Conference on Neural Networks
1–8 (2015) .
[52] Seedat, N., Jeffares, A., Imrie, F. & van der Schaar, M. Improving adaptive
conformal prediction using self-supervised learning. In: Proceedings of The 26th
International Conference on Artificial Intelligence and Statistics (2023) .
[53] Angelopoulos, A., Bates, S., Malik, J. & Jordan, M. I. Uncertainty sets for
image classifiers using conformal prediction. In: International Conference on
Learning Representations (2021) .
20 AutoPrognosis-Multimodal
[54] Argenziano, G. et al. Epiluminescence microscopy for the diagnosis of doubtful
melanocytic skin lesions: Comparison of the ABCD rule of dermatoscopy and
a new 7-point checklist based on pattern analysis. Arch. Dermatol. 134 (12),
1563–1570 (1998). https://doi.org/10.1001/archderm.134.12.1563 .
[55] Abbasi, N. R. et al. Early diagnosis of cutaneous melanoma: Revisiting the
ABCD criteria. JAMA 292(22), 2771–2776 (2004) .
[56] Pacheco, A. G. et al. PAD-UFES-20: A skin lesion dataset composed of patient
data and clinical images collected from smartphones. Data Brief 32, 106221
(2020). https://doi.org/10.1016/j.dib.2020.106221 .
[57] Macneal, P. & Patel, B. C. Congenital melanocytic nevi. StatPearls Publishing,
Treasure Island (FL) (2020) .
[58] Zalaudek, I. et al. Frequency of dermoscopic nevus subtypes by age and body
site: A cross-sectional study. Arch. Dermatol. 147(6), 663–670 (2011). https:
//doi.org/10.1001/archdermatol.2011.149 .
[59] Soenksen, L. R. et al. Integrated multimodal artificial intelligence framework
for healthcare applications. npj Digit. Med. 5(1), 149 (2022). https://doi.org/
10.1038/s41746-022-00689-4 .
[60] Wang, Y. et al. Automated multimodal machine learning for esophageal variceal
bleeding prediction based on endoscopy and structured data. J. Digit. Imaging
36(1), 326–338 (2023). https://doi.org/10.1007/s10278-022-00724-6 .
[61] Tang, Z. et al. AutoGluon-Multimodal (AutoMM): Supercharging multimodal
AutoML with foundation models. In: International Conference on Automated
Machine Learning (2024) .
AutoPrognosis-Multimodal 21
Table S.1 :Imaging models included in AutoPrognosis-M. CNN -
Convolutional Neural Network. ViT - Vision Transformer.
Model Type # Param.Pretraining
DataEmbedding
sizeRef.
ResNet18 CNN 11.7 M ImageNet-1k 512 [30]
ResNet34 CNN 21.8 M ImageNet-1k 512 [30]
ResNet50 CNN 25 M ImageNet-1k 2048 [30]
ResNet101 CNN 44.5 M ImageNet-1k 2048 [30]
ResNet152 CNN 60.2 M ImageNet-1k 2048 [30]
EfficientNetB0 CNN 5.3 M ImageNet-1k 320 [31]
EfficientNetB1 CNN 7.8 M ImageNet-1k 320 [31]
EfficientNetB2 CNN 9.2 M ImageNet-1k 352 [31]
EfficientNetB3 CNN 12 M ImageNet-1k 384 [31]
EfficientNetB4 CNN 19 M ImageNet-1k 448 [31]
EfficientNetB5 CNN 30 M ImageNet-1k 512 [31]
MobileNetV2 CNN 3.4 M ImageNet-1k 320 [32]
ViTBase ViT-B/16 86 M ImageNet-1k 768 [33]
ViTLarge ViT-L/16 307 M ImageNet-21k 1024 [33]
DinoV2Small ViT-S/14 22 M LVD-142M 384 [36]
DinoV2Base ViT-B/14 86 M LVD-142M 768 [36]
DinoV2Large ViT-L/14 307 M LVD-142M 1024 [36]
22 AutoPrognosis-Multimodal
Table S.2 : Clinical variables in the PAD-UFES-20 dataset (n=2,298).
Diagnosis
Basal Cell Carcinoma (BCC) 845 (36.8%)
Squamous Cell Carcinoma (SCC) 192 (8.4%)
Melanoma (MEL) 52 (2.3%)
Actinic Keratosis (ACK) 730 (31.8%)
Melanocytic Nevus (NEV) 244 (10.6%)
Seborrheic Keratosis (SEK) 235 (10.2%)
Age
6-29 92 (4.0%)
30-49 386 (16.8%)
50-69 1,098 (47.8%)
70-94 722 (31.4%)
Region
Face 570 (24.5%)
Forearm 392 (17.1%)
Chest 280 (12.2%)
Back 248 (10.8%)
Arm 192 (8.4%)
Nose 158 (6.9%)
Hand 126 (5.5%)
Neck 93 (4.0%)
Thigh 73 (3.2%)
Ear 73 (3.2%)
Abdomen 36 (1.6%)
Lip 23 (1.0%)
Scalp 18 (0.8%)
Foot 16 (0.7%)
Itch
Yes 1,455 (63.3%)
No 837 (36.4%)
Unknown 6 (0.3%)
Grew
Yes 925 (40.2%)
No 971 (42.3%)
Unknown 402 (17.5%)
Hurt
Yes 397 (17.3%)
No 1,891 (82.3%)
Unknown 10 (0.4%)
Changed
Yes 202 (0.9%)
No 1,700 (74.0%)
Unknown 396 (17.2%)
Bleed
Yes 614 (26.7%)
No 1,678 (73.0%)
Unknown 6 (0.3%)
Elevation
Yes 1,433 (62.4%)
No 863 (37.6%)
Unknown 2 (0.1%)
AutoPrognosis-Multimodal 23
Table S.3 :Late fusion skin legion classification performance. The best
result for each modality is in bold. The best non-ensemble approach for each
modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 74.0% 68.0% 0.921 0.656 87.8% 0.946 0.867 0.755
ResNet34 73.2% 67.1% 0.920 0.638 87.7% 0.946 0.867 0.753
ResNet50 73.6% 69.8% 0.925 0.674 87.8% 0.943 0.867 0.754
ResNet101 73.6% 68.4% 0.926 0.665 86.8% 0.942 0.855 0.734
ResNet152 75.5% 70.2% 0.928 0.684 88.1% 0.944 0.870 0.760
EfficientNetB0 75.2% 69.3% 0.925 0.665 87.9% 0.947 0.867 0.756
EfficientNetB1 75.5% 71.3% 0.929 0.693 88.1% 0.949 0.870 0.762
EfficientNetB2 75.5% 69.4% 0.927 0.668 87.6% 0.944 0.864 0.751
EfficientNetB3 74.7% 71.0% 0.928 0.685 88.1% 0.946 0.869 0.760
EfficientNetB4 75.4% 69.9% 0.928 0.672 88.0% 0.946 0.868 0.758
EfficientNetB5 76.9% 72.0% 0.928 0.696 87.9% 0.948 0.867 0.757
MobileNetV2 72.2% 65.6% 0.912 0.627 87.1% 0.939 0.857 0.739
ViTBase 76.6% 71.6% 0.937 0.700 87.3% 0.948 0.861 0.744
ViTLarge 76.3% 71.2% 0.936 0.697 88.0% 0.950 0.869 0.759
DinoV2Small 76.8% 70.9% 0.937 0.695 89.2% 0.950 0.883 0.782
DinoV2Base 77.0% 72.8% 0.935 0.706 88.5% 0.951 0.875 0.767
DinoV2Large 77.7% 72.3% 0.935 0.697 87.5% 0.948 0.864 0.749
Ensemble 79.0% 74.7% 0.939 0.730 89.1% 0.954 0.882 0.781
Table S.4 :Early fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 59.9% 59.2% 0.879 0.558 81.8% 0.899 0.803 0.635
ResNet34 58.1% 56.3% 0.865 0.541 80.9% 0.884 0.795 0.614
ResNet50 62.8% 61.7% 0.891 0.590 84.1% 0.908 0.832 0.679
ResNet101 66.8% 63.4% 0.904 0.617 84.4% 0.921 0.833 0.685
ResNet152 69.1% 64.6% 0.910 0.636 83.3% 0.904 0.821 0.663
EfficientNetB0 66.0% 61.2% 0.884 0.601 83.4% 0.903 0.822 0.665
EfficientNetB1 64.3% 60.8% 0.884 0.586 82.8% 0.903 0.816 0.655
EfficientNetB2 63.8% 58.7% 0.884 0.577 80.3% 0.882 0.786 0.602
EfficientNetB3 64.1% 58.8% 0.882 0.569 81.6% 0.896 0.801 0.629
EfficientNetB4 66.4% 62.2% 0.894 0.607 82.9% 0.902 0.818 0.656
EfficientNetB5 66.3% 61.2% 0.893 0.603 82.0% 0.898 0.807 0.638
MobileNetV2 64.4% 59.4% 0.880 0.576 82.1% 0.898 0.808 0.641
ViTBase 58.1% 55.2% 0.820 0.517 80.7% 0.881 0.792 0.612
ViTLarge 70.1% 66.6% 0.915 0.653 84.1% 0.914 0.829 0.680
DinoV2Small 70.9% 68.1% 0.918 0.657 85.7% 0.922 0.847 0.713
DinoV2Base 69.1% 64.8% 0.904 0.635 83.5% 0.912 0.821 0.669
DinoV2Large 70.4% 62.8% 0.906 0.630 83.8% 0.915 0.829 0.674
Ensemble 74.7% 70.2% 0.930 0.701 86.7% 0.936 0.856 0.731
24 AutoPrognosis-Multimodal
Table S.5 :Joint fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 65.8% 61.6% 0.899 0.588 83.4% 0.911 0.823 0.667
ResNet34 62.8% 61.6% 0.889 0.575 82.1% 0.891 0.809 0.639
ResNet50 66.1% 60.1% 0.879 0.568 84.3% 0.909 0.833 0.684
ResNet101 67.5% 61.5% 0.892 0.595 83.9% 0.911 0.827 0.675
ResNet152 68.8% 66.3% 0.913 0.642 85.3% 0.921 0.842 0.704
EfficientNetB0 62.9% 64.0% 0.899 0.605 84.7% 0.921 0.833 0.691
EfficientNetB1 66.1% 65.1% 0.905 0.624 85.4% 0.926 0.843 0.705
EfficientNetB2 68.3% 63.9% 0.912 0.620 84.0% 0.914 0.828 0.677
EfficientNetB3 68.1% 65.3% 0.913 0.634 84.8% 0.920 0.837 0.693
EfficientNetB4 69.0% 66.2% 0.915 0.644 86.3% 0.933 0.853 0.724
EfficientNetB5 71.0% 66.2% 0.922 0.648 87.3% 0.936 0.863 0.744
MobileNetV2 61.9% 60.5% 0.894 0.572 83.3% 0.908 0.821 0.665
ViTBase 64.9% 63.6% 0.898 0.600 83.3% 0.909 0.822 0.665
ViTLarge 72.6% 68.4% 0.930 0.676 87.5% 0.940 0.866 0.748
DinoV2Small 69.6% 66.4% 0.915 0.651 86.2% 0.929 0.856 0.725
DinoV2Base 73.8% 71.4% 0.930 0.698 87.0% 0.935 0.861 0.740
DinoV2Large 73.8% 68.2% 0.933 0.678 86.6% 0.941 0.857 0.733
Ensemble 75.6% 71.9% 0.937 0.716 88.0% 0.951 0.880 0.775 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | data availability. AutoPrognosis-M is available at https:
//github.com/vanderschaarlab/AutoPrognosis-Multimodal. PAD-UFES-20 is
freely available at https://data.mendeley.com/datasets/zr7vgbcyr2/1 (DOI:
10.17632/zr7vgbcyr2.1) [56]. All preprocessing and the splits used for
our experiments can be found at https://github.com/vanderschaarlab/
AutoPrognosis-Multimodal.
References
[1] Abr` amoff, M. D., Lavin, P. T., Birch, M., Shah, N. & Folk, J. C. Pivotal
trial of an autonomous AI-based diagnostic system for detection of diabetic
retinopathy in primary care offices. npj Digit. Med. 1(1), 39 (2018). https:
//doi.org/10.1038/s41746-018-0040-6 .
[2] Rajpurkar, P., Chen, E., Banerjee, O. & Topol, E. J. AI in health and medicine.
Nat. Med. 28(1), 31–38 (2022). https://doi.org/10.1038/s41591-021-01614-0 .
[3] Kline, A. et al. Multimodal machine learning in precision health: A scop-
ing review. npj Digit. Med. 5(1), 171 (2022). https://doi.org/10.1038/
16 AutoPrognosis-Multimodal
s41746-022-00712-8 .
[4] Huang, S.-C., Pareek, A., Seyyedi, S., Banerjee, I. & Lungren, M. P. Fusion of
medical imaging and electronic health records using deep learning: A systematic
review and implementation guidelines. npj Digit. Med. 3(1), 136 (2020). https:
//doi.org/10.1038/s41746-020-00341-z .
[5] Leslie, A. & Jones, P. R., A. J.and Goddard. The influence of clinical informa-
tion on the reporting of CT by radiologists. Br. J. Radiol. 73(874), 1052–1055
(2000). https://doi.org/10.1259/bjr.73.874.11271897 .
[6] Castillo, C., Steffens, T., Sim, L. & Caffery, L. The effect of clinical information
on radiology reporting: A systematic review. J. Med. Radiat. Sci. 68(1), 60–74
(2021). https://doi.org/10.1002/jmrs.424 .
[7] Boonn, W. W. & Langlotz, C. P. Radiologist use of and perceived need for
patient data access. J. Digit. Imaging 22(4), 357–362 (2009). https://doi.org/
10.1007/s10278-008-9115-2 .
[8] Wang, M. Y., Asanad, S., Asanad, K., Karanjia, R. & Sadun, A. A. Value of
medical history in ophthalmology: A study of diagnostic accuracy. J. Curr.
Ophthalmol. 30(4), 359–364 (2018). https://doi.org/https://doi.org/10.1016/
j.joco.2018.09.001 .
[9] Ombrello, M. J., Sikora, K. A. & Kastner, D. L. Genetics, genomics, and their
relevance to pathology and therapy. Best Pract. Res.: Clin. Rheumatol. 28(2),
175–189 (2014). https://doi.org/https://doi.org/10.1016/j.berh.2014.05.001 .
[10] Bergenmar, M., Hansson, J. & Brandberg, Y. Detection of nodular and super-
ficial spreading melanoma with tumour thickness ≤2.0 mm - an interview
study. Eur. J. Cancer Prev. 11(1), 49–55 (2002). https://doi.org/10.1097/
00008469-200202000-00007 .
[11] Li, P., Hu, Y. & Liu, Z.-P. Prediction of cardiovascular diseases by integrating
multi-modal features with machine learning methods. Biomed. Signal Pro-
cess. Control. 66, 102474 (2021). https://doi.org/https://doi.org/10.1016/j.
bspc.2021.102474 .
[12] Liu, Y. et al. A deep learning system for differential diagnosis of skin dis-
eases. Nat. Med. 26(6), 900–908 (2020). URL https://doi.org/10.1038/
s41591-020-0842-3. https://doi.org/10.1038/s41591-020-0842-3 .
[13] Yala, A., Lehman, C., Schuster, T., Portnoi, T. & Barzilay, R. A deep learn-
ing mammography-based model for improved breast cancer risk prediction.
Radiology 292(1), 60–66 (2019). https://doi.org/10.1148/radiol.2019182716 .
[14] Kyono, T., Gilbert, F. J. & van der Schaar, M. Improving workflow efficiency
for mammography using machine learning. J. Am. Coll. Radiol. 17(1), 56–63
(2020). https://doi.org/10.1016/j.jacr.2019.05.012 .
AutoPrognosis-Multimodal 17
[15] Wu, J. et al. Radiological tumour classification across imaging modality and
histology. Nat. Mach. Intell. 3(9), 787–798 (2021). https://doi.org/10.1038/
s42256-021-00377-0 .
[16] Imrie, F., Cebere, B., McKinney, E. F. & van der Schaar, M. AutoProgno-
sis 2.0: Democratizing diagnostic and prognostic modeling in healthcare with
automated machine learning. PLOS Digit. Health 2(6), e0000276 (2023).
https://doi.org/10.1371/journal.pdig.0000276 .
[17] Alaa, A. M., Bolton, T., Di Angelantonio, E., Rudd, J. H. F. & van der Schaar,
M. Cardiovascular disease risk prediction using automated machine learning: A
prospective study of 423,604 UK Biobank participants. PLoS One 14(5), 1–17
(2019). https://doi.org/10.1371/journal.pone.0213653 .
[18] Imrie, F., Rauba, P. & van der Schaar, M. Redefining digital health interfaces
with large language models. arXiv preprint arXiv:2310.03560 (2023) .
[19] Alaa, A. M. & van der Schaar, M. Prognostication and risk factors for cystic
fibrosis via automated machine learning. Sci. Rep. 8(1), 11242 (2018). https:
//doi.org/10.1038/s41598-018-29523-2 .
[20] Alaa, A. M., Gurdasani, D., Harris, A. L., Rashbass, J. & van der Schaar,
M. Machine learning to guide the use of adjuvant therapies for breast can-
cer. Nat. Mach. Intell. 3(8), 716–726 (2021). https://doi.org/10.1038/
s42256-021-00353-8 .
[21] Callender, T. et al. Assessing eligibility for lung cancer screening using parsimo-
nious ensemble machine learning models: A development and validation study.
PLOS Med. 20(10), e1004287 (2023). https://doi.org/10.1371/journal.pmed.
1004287 .
[22] Feurer, M. et al. Efficient and robust automated machine learning. Adv. Neural
Inf. Process. Syst. 28, 2755–2763 (2015) .
[23] Thornton, C., Hutter, F., Hoos, H. H. & Leyton-Brown, K. Auto-WEKA: Com-
bined selection and hyperparameter optimization of classification algorithms.
Proceedings of the 19th ACM SIGKDD International Conference on Knowledge
Discovery and Data Mining 847–855 (2013). https://doi.org/10.1145/2487575.
2487629 .
[24] Olson, R. S. & Moore, J. H. TPOT: A tree-based pipeline optimization tool
for automating machine learning. In: International Conference on Machine
Learning - AutoML Workshop 66–74 (2016) .
[25] Imrie, F., Davis, R. & van der Schaar, M. Multiple stakeholders drive diverse
interpretability requirements for machine learning in healthcare. Nat. Mach.
Intell. 5(8), 824–829 (2023). https://doi.org/10.1038/s42256-023-00698-2 .
[26] Callender, T. & van der Schaar, M. Automated machine learning as a partner
in predictive modelling. Lancet Digit. Health 5(5), e254–e256 (2023). https:
//doi.org/10.1016/S2589-7500(23)00054-7 .
18 AutoPrognosis-Multimodal
[27] Waring, J., Lindvall, C. & Umeton, R. Automated machine learning: Review
of the state-of-the-art and opportunities for healthcare. Artif. Intell. Med. 104,
101822 (2020) .
[28] van Buuren, S. & Groothuis-Oudshoorn, K. mice: Multivariate imputation by
chained equations in R. J. Stat. Softw. 45(3), 1–67 (2011). https://doi.org/
10.18637/jss.v045.i03 .
[29] Stekhoven, D. J. & B¨ uhlmann, P. MissForest—non-parametric missing value
imputation for mixed-type data. Bioinformatics 28(1), 112–118 (2011). https:
//doi.org/10.1093/bioinformatics/btr597 .
[30] He, K., Zhang, X., Ren, S. & Sun, J. Deep residual learning for image recogni-
tion. In: Proceedings of the IEEE Conference on Computer Vision and Pattern
Recognition 770–778 (2016) .
[31] Tan, M. & Le, Q. EfficientNet: Rethinking model scaling for convolutional
neural networks. In: International Conference on Machine Learning 6105–6114
(2019) .
[32] Sandler, M., Howard, A., Zhu, M., Zhmoginov, A. & Chen, L.-C. MobileNetV2:
Inverted residuals and linear bottlenecks. In: Proceedings of the IEEE Confer-
ence on Computer Vision and Pattern Recognition 4510–4520 (2018) .
[33] Dosovitskiy, A. et al. An image is worth 16x16 words: Transformers for image
recognition at scale. In: International Conference on Learning Representations
(2021) .
[34] Weiss, K., Khoshgoftaar, T. M. & Wang, D. A survey of transfer learning. J.
Big Data 3, 1–40 (2016) .
[35] Zhuang, F. et al. A comprehensive survey on transfer learning. Proc. IEEE
109(1), 43–76 (2020) .
[36] Oquab, M. et al. DINOv2: Learning robust visual features without supervision.
Trans. Mach. Learn. Res. (2024) .
[37] Baltruˇ saitis, T., Ahuja, C. & Morency, L.-P. Multimodal machine learning: A
survey and taxonomy. IEEE Trans. Pattern Anal. Mach. Intell. 41(2), 423–443
(2019). https://doi.org/10.1109/TPAMI.2018.2798607 .
[38] Sharma, R., Pavlovic, V. I. & Huang, T. S. Toward multimodal human-
computer interface. Proc. IEEE 86(5), 853–869 (1998) .
[39] Stahlschmidt, S. R., Ulfenborg, B. & Synnergren, J. Multimodal deep learning
for biomedical data fusion: A review. Brief. Bioinform. 23(2), bbab569 (2022) .
[40] Krogh, A. & Vedelsby, J. Neural network ensembles, cross validation, and active
learning. Adv. Neural Inf. Process. Syst. 7(1994) .
AutoPrognosis-Multimodal 19
[41] Akiba, T., Sano, S., Yanase, T., Ohta, T. & Koyama, M. Optuna: A next-
generation hyperparameter optimization framework. In: Proceedings of the
25th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining 2623–2631 (2019) .
[42] Medicines & Healthcare products Regulatory Agency. Soft-
ware and ai as a medical device change programme -
roadmap (2023). URL https://www.gov.uk/government/
publications/software-and-ai-as-a-medical-device-change-programme/
software-and-ai-as-a-medical-device-change-programme-roadmap. Updated
14 June 2023 .
[43] Lundberg, S. M. & Lee, S.-I. A unified approach to interpreting model
predictions. Adv. Neural Inf. Process. Syst. 30(2017) .
[44] Sundararajan, M., Taly, A. & Yan, Q. Axiomatic attribution for deep networks.
In: International Conference on Machine Learning 3319–3328 (2017) .
[45] Crabbe, J., Qian, Z., Imrie, F. & van der Schaar, M. Explaining latent rep-
resentations with a corpus of examples. Adv. Neural Inf. Process. Syst. 34,
12154–12166 (2021) .
[46] Kompa, B., Snoek, J. & Beam, A. L. Second opinion needed: Communicating
uncertainty in medical machine learning. npj Digit. Med. 4(1), 4 (2021). https:
//doi.org/10.1038/s41746-020-00367-3 .
[47] Helou, M. A., DiazGranados, D., Ryan, M. S. & Cyrus, J. W. Uncertainty
in decision making in medicine: A scoping review and thematic analysis of
conceptual models. Acad. Med. 95(1) (2020) .
[48] Vovk, V., Gammerman, A. & Shafer, G. Algorithmic learning in a random world
(Springer Science & Business Media, 2005).
[49] Vovk, V. Conditional validity of inductive conformal predictors. In: Asian
Conference on Machine Learning 475–490 (2012) .
[50] Papadopoulos, H., Vovk, V. & Gammerman, A. Regression conformal prediction
with nearest neighbours. J. Artif. Intell. Res. 40, 815–840 (2011) .
[51] Johansson, U., S¨ onstr¨ od, C. & Linusson, H. Efficient conformal regressors using
bagged neural nets. In: 2015 International Joint Conference on Neural Networks
1–8 (2015) .
[52] Seedat, N., Jeffares, A., Imrie, F. & van der Schaar, M. Improving adaptive
conformal prediction using self-supervised learning. In: Proceedings of The 26th
International Conference on Artificial Intelligence and Statistics (2023) .
[53] Angelopoulos, A., Bates, S., Malik, J. & Jordan, M. I. Uncertainty sets for
image classifiers using conformal prediction. In: International Conference on
Learning Representations (2021) .
20 AutoPrognosis-Multimodal
[54] Argenziano, G. et al. Epiluminescence microscopy for the diagnosis of doubtful
melanocytic skin lesions: Comparison of the ABCD rule of dermatoscopy and
a new 7-point checklist based on pattern analysis. Arch. Dermatol. 134 (12),
1563–1570 (1998). https://doi.org/10.1001/archderm.134.12.1563 .
[55] Abbasi, N. R. et al. Early diagnosis of cutaneous melanoma: Revisiting the
ABCD criteria. JAMA 292(22), 2771–2776 (2004) .
[56] Pacheco, A. G. et al. PAD-UFES-20: A skin lesion dataset composed of patient
data and clinical images collected from smartphones. Data Brief 32, 106221
(2020). https://doi.org/10.1016/j.dib.2020.106221 .
[57] Macneal, P. & Patel, B. C. Congenital melanocytic nevi. StatPearls Publishing,
Treasure Island (FL) (2020) .
[58] Zalaudek, I. et al. Frequency of dermoscopic nevus subtypes by age and body
site: A cross-sectional study. Arch. Dermatol. 147(6), 663–670 (2011). https:
//doi.org/10.1001/archdermatol.2011.149 .
[59] Soenksen, L. R. et al. Integrated multimodal artificial intelligence framework
for healthcare applications. npj Digit. Med. 5(1), 149 (2022). https://doi.org/
10.1038/s41746-022-00689-4 .
[60] Wang, Y. et al. Automated multimodal machine learning for esophageal variceal
bleeding prediction based on endoscopy and structured data. J. Digit. Imaging
36(1), 326–338 (2023). https://doi.org/10.1007/s10278-022-00724-6 .
[61] Tang, Z. et al. AutoGluon-Multimodal (AutoMM): Supercharging multimodal
AutoML with foundation models. In: International Conference on Automated
Machine Learning (2024) .
AutoPrognosis-Multimodal 21
Table S.1 :Imaging models included in AutoPrognosis-M. CNN -
Convolutional Neural Network. ViT - Vision Transformer.
Model Type # Param.Pretraining
DataEmbedding
sizeRef.
ResNet18 CNN 11.7 M ImageNet-1k 512 [30]
ResNet34 CNN 21.8 M ImageNet-1k 512 [30]
ResNet50 CNN 25 M ImageNet-1k 2048 [30]
ResNet101 CNN 44.5 M ImageNet-1k 2048 [30]
ResNet152 CNN 60.2 M ImageNet-1k 2048 [30]
EfficientNetB0 CNN 5.3 M ImageNet-1k 320 [31]
EfficientNetB1 CNN 7.8 M ImageNet-1k 320 [31]
EfficientNetB2 CNN 9.2 M ImageNet-1k 352 [31]
EfficientNetB3 CNN 12 M ImageNet-1k 384 [31]
EfficientNetB4 CNN 19 M ImageNet-1k 448 [31]
EfficientNetB5 CNN 30 M ImageNet-1k 512 [31]
MobileNetV2 CNN 3.4 M ImageNet-1k 320 [32]
ViTBase ViT-B/16 86 M ImageNet-1k 768 [33]
ViTLarge ViT-L/16 307 M ImageNet-21k 1024 [33]
DinoV2Small ViT-S/14 22 M LVD-142M 384 [36]
DinoV2Base ViT-B/14 86 M LVD-142M 768 [36]
DinoV2Large ViT-L/14 307 M LVD-142M 1024 [36]
22 AutoPrognosis-Multimodal
Table S.2 : Clinical variables in the PAD-UFES-20 dataset (n=2,298).
Diagnosis
Basal Cell Carcinoma (BCC) 845 (36.8%)
Squamous Cell Carcinoma (SCC) 192 (8.4%)
Melanoma (MEL) 52 (2.3%)
Actinic Keratosis (ACK) 730 (31.8%)
Melanocytic Nevus (NEV) 244 (10.6%)
Seborrheic Keratosis (SEK) 235 (10.2%)
Age
6-29 92 (4.0%)
30-49 386 (16.8%)
50-69 1,098 (47.8%)
70-94 722 (31.4%)
Region
Face 570 (24.5%)
Forearm 392 (17.1%)
Chest 280 (12.2%)
Back 248 (10.8%)
Arm 192 (8.4%)
Nose 158 (6.9%)
Hand 126 (5.5%)
Neck 93 (4.0%)
Thigh 73 (3.2%)
Ear 73 (3.2%)
Abdomen 36 (1.6%)
Lip 23 (1.0%)
Scalp 18 (0.8%)
Foot 16 (0.7%)
Itch
Yes 1,455 (63.3%)
No 837 (36.4%)
Unknown 6 (0.3%)
Grew
Yes 925 (40.2%)
No 971 (42.3%)
Unknown 402 (17.5%)
Hurt
Yes 397 (17.3%)
No 1,891 (82.3%)
Unknown 10 (0.4%)
Changed
Yes 202 (0.9%)
No 1,700 (74.0%)
Unknown 396 (17.2%)
Bleed
Yes 614 (26.7%)
No 1,678 (73.0%)
Unknown 6 (0.3%)
Elevation
Yes 1,433 (62.4%)
No 863 (37.6%)
Unknown 2 (0.1%)
AutoPrognosis-Multimodal 23
Table S.3 :Late fusion skin legion classification performance. The best
result for each modality is in bold. The best non-ensemble approach for each
modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 74.0% 68.0% 0.921 0.656 87.8% 0.946 0.867 0.755
ResNet34 73.2% 67.1% 0.920 0.638 87.7% 0.946 0.867 0.753
ResNet50 73.6% 69.8% 0.925 0.674 87.8% 0.943 0.867 0.754
ResNet101 73.6% 68.4% 0.926 0.665 86.8% 0.942 0.855 0.734
ResNet152 75.5% 70.2% 0.928 0.684 88.1% 0.944 0.870 0.760
EfficientNetB0 75.2% 69.3% 0.925 0.665 87.9% 0.947 0.867 0.756
EfficientNetB1 75.5% 71.3% 0.929 0.693 88.1% 0.949 0.870 0.762
EfficientNetB2 75.5% 69.4% 0.927 0.668 87.6% 0.944 0.864 0.751
EfficientNetB3 74.7% 71.0% 0.928 0.685 88.1% 0.946 0.869 0.760
EfficientNetB4 75.4% 69.9% 0.928 0.672 88.0% 0.946 0.868 0.758
EfficientNetB5 76.9% 72.0% 0.928 0.696 87.9% 0.948 0.867 0.757
MobileNetV2 72.2% 65.6% 0.912 0.627 87.1% 0.939 0.857 0.739
ViTBase 76.6% 71.6% 0.937 0.700 87.3% 0.948 0.861 0.744
ViTLarge 76.3% 71.2% 0.936 0.697 88.0% 0.950 0.869 0.759
DinoV2Small 76.8% 70.9% 0.937 0.695 89.2% 0.950 0.883 0.782
DinoV2Base 77.0% 72.8% 0.935 0.706 88.5% 0.951 0.875 0.767
DinoV2Large 77.7% 72.3% 0.935 0.697 87.5% 0.948 0.864 0.749
Ensemble 79.0% 74.7% 0.939 0.730 89.1% 0.954 0.882 0.781
Table S.4 :Early fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 59.9% 59.2% 0.879 0.558 81.8% 0.899 0.803 0.635
ResNet34 58.1% 56.3% 0.865 0.541 80.9% 0.884 0.795 0.614
ResNet50 62.8% 61.7% 0.891 0.590 84.1% 0.908 0.832 0.679
ResNet101 66.8% 63.4% 0.904 0.617 84.4% 0.921 0.833 0.685
ResNet152 69.1% 64.6% 0.910 0.636 83.3% 0.904 0.821 0.663
EfficientNetB0 66.0% 61.2% 0.884 0.601 83.4% 0.903 0.822 0.665
EfficientNetB1 64.3% 60.8% 0.884 0.586 82.8% 0.903 0.816 0.655
EfficientNetB2 63.8% 58.7% 0.884 0.577 80.3% 0.882 0.786 0.602
EfficientNetB3 64.1% 58.8% 0.882 0.569 81.6% 0.896 0.801 0.629
EfficientNetB4 66.4% 62.2% 0.894 0.607 82.9% 0.902 0.818 0.656
EfficientNetB5 66.3% 61.2% 0.893 0.603 82.0% 0.898 0.807 0.638
MobileNetV2 64.4% 59.4% 0.880 0.576 82.1% 0.898 0.808 0.641
ViTBase 58.1% 55.2% 0.820 0.517 80.7% 0.881 0.792 0.612
ViTLarge 70.1% 66.6% 0.915 0.653 84.1% 0.914 0.829 0.680
DinoV2Small 70.9% 68.1% 0.918 0.657 85.7% 0.922 0.847 0.713
DinoV2Base 69.1% 64.8% 0.904 0.635 83.5% 0.912 0.821 0.669
DinoV2Large 70.4% 62.8% 0.906 0.630 83.8% 0.915 0.829 0.674
Ensemble 74.7% 70.2% 0.930 0.701 86.7% 0.936 0.856 0.731
24 AutoPrognosis-Multimodal
Table S.5 :Joint fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 65.8% 61.6% 0.899 0.588 83.4% 0.911 0.823 0.667
ResNet34 62.8% 61.6% 0.889 0.575 82.1% 0.891 0.809 0.639
ResNet50 66.1% 60.1% 0.879 0.568 84.3% 0.909 0.833 0.684
ResNet101 67.5% 61.5% 0.892 0.595 83.9% 0.911 0.827 0.675
ResNet152 68.8% 66.3% 0.913 0.642 85.3% 0.921 0.842 0.704
EfficientNetB0 62.9% 64.0% 0.899 0.605 84.7% 0.921 0.833 0.691
EfficientNetB1 66.1% 65.1% 0.905 0.624 85.4% 0.926 0.843 0.705
EfficientNetB2 68.3% 63.9% 0.912 0.620 84.0% 0.914 0.828 0.677
EfficientNetB3 68.1% 65.3% 0.913 0.634 84.8% 0.920 0.837 0.693
EfficientNetB4 69.0% 66.2% 0.915 0.644 86.3% 0.933 0.853 0.724
EfficientNetB5 71.0% 66.2% 0.922 0.648 87.3% 0.936 0.863 0.744
MobileNetV2 61.9% 60.5% 0.894 0.572 83.3% 0.908 0.821 0.665
ViTBase 64.9% 63.6% 0.898 0.600 83.3% 0.909 0.822 0.665
ViTLarge 72.6% 68.4% 0.930 0.676 87.5% 0.940 0.866 0.748
DinoV2Small 69.6% 66.4% 0.915 0.651 86.2% 0.929 0.856 0.725
DinoV2Base 73.8% 71.4% 0.930 0.698 87.0% 0.935 0.861 0.740
DinoV2Large 73.8% 68.2% 0.933 0.678 86.6% 0.941 0.857 0.733
Ensemble 75.6% 71.9% 0.937 0.716 88.0% 0.951 0.880 0.775 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | model architectures and associated hyperparameters, which
must be set appropriately for the specific task and data being considered. Fail-
ure to do so can significantly degrade performance; however, this often requires
significant ML knowledge and expertise to do so effectively. This challenge is
further compounded in the multimodal setting by the different possible ways
of integrating data from multiple sources.
To address this, our framework employs AutoML [23] to efficiently and
effectively search the model and hyperparameter space. AutoPrognosis-M con-
structs powerful ensemble multimodal ML models designed for the specific
problem and data under consideration. While incorporating multiple modal-
ities can improve predictive power, this may not always be the case or a
modality might be particularly expensive to acquire. Thus, it is important to
understand the importance of each modality individually, and the added value
of including an additional modality (Fig. 1a-b). AutoPrognosis-M can opti-
mize both unimodal models and multimodal models, allowing the value of each
modality to be assessed, both separately and in combination with other sources
of information, as well as enabling models to be debugged and understood
using techniques from explainable AI (Fig. 2).
AutoPrognosis-Multimodal 5
By automating the optimization of ML pipelines across multiple modalities
and determining the most suitable way of combining the information from dis-
tinct sources, we reduce the barrier for non-ML experts, such as clinicians and
healthcare professionals, to build powerful multimodal ML models for problems
in the healthcare and medicine domains. We believe that AutoPrognosis-M
significantly simplifies the process of training and validating multimodal ML
models without compromising on the expressiveness or quality of the ML
models considered.
Automated Machine Learning
AutoML aims to simplify and automate the process of designing and train-
ing ML models, thereby reducing the technical capabilities required to develop
effective models. Human practitioners have biases about what model architec-
tures or hyperparameters will provide the best results for a specific task. While
this might be helpful in some cases, often it will not and can cause inconsistency
in the quality of the final predictive system [26]. AutoML helps minimize these
biases by automatically searching over a more general set of models, hyper-
parameters, and other design choices to optimize a given objective function,
returning the best configurations found. Beyond simply minimizing human
biases, AutoML reduces the demand for human experts and has been shown
to typically match or exceed the skilled human performance [27].
Unimodal approaches
Tabular
We implement the tabular component of our multimodal framework using
AutoPrognosis 2.0 [16]. In contrast to many other approaches for learning from
tabular data, we consider full ML pipelines , rather than just predictive models,
consisting of missing data imputation, feature processing, model selection, and
hyperparameter optimization. AutoPrognosis includes implementations for 22
classification algorithms, nine imputation algorithms, including mean imputa-
tion, MICE [28], and MissForest [29], five dimensionality reduction, such as
PCA, and six feature scaling algorithms. The best-performing pipelines are
then combined into an ensemble via either a learned weighting or stacking,
where a meta-model is trained on the output of the underlying pipelines. For
further detail, we refer the reader to Imrie et al. [16]
Imaging
For imaging tasks, we employ a several distinct model architectures to cater to
a wide range of diagnostic and prognostic applications. Specifically, we utilized
Convolutional Neural Networks (CNNs), including ResNet [30], EfficientNet
[31], and MobileNetV2 [32], as well as Vision Transformers (ViTs) [33]. Each
model architecture is available in several sizes to be able to handle different
6 AutoPrognosis-Multimodal
-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Unimodal
ModelUnimodal
Model
Prediction Prediction
Combine
Final
Prediction
(a) Late Fusion-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Feature
ExtractorFeature
Extractor
Predictor
Final
Prediction
(b) Early FusionExtracted Features Extracted Features
Combine-
-
-
-
--
-
-
-
--
-
-
-
-Tabular Data Medical Image
Feature
ExtractorFeature
Extractor
Predictor
Final
Prediction
(c) Joint FusionExtracted Features Extracted Features
Combine
LossLoss Loss
Loss LossLoss Loss
Fig. 3 :Illustration of the three types of multimodal fusion. (a) Late
fusion combines the predictions of separate unimodal models. (b) Early fusion
trains a predictive model on the combination of fixed extracted features. (c)
Joint fusion flexibly integrates multiple modalities, learning to extract repre-
sentations and make predictions simultaneously in an end-to-end manner.
task complexities. A full list of the 17 imaging models provided, together with
additional details, can be found in Table S.1.
While general-purpose models for tabular data do not exist, the transfer-
ability of imaging models has been shown in a diverse range of disciplines
[34, 35], and can be particularly effective when there is limited available data
for a particular problem. Pretrained models are especially useful when the
available data for a specific task is scarce or when computational resources are
limited. They allow one to leverage learned features and patterns from vast
datasets, potentially improving performance on related tasks.
While most models are pretrained in a supervised manner, self-supervised
pretraining has been shown to improve performance on many classification
tasks. Thus, in addition to supervised ViT [33], we also consider DINOv2 [36].
One approach to using pretrained models for new prediction tasks is to extract
a fixed representation and train a new classification head on the available task-
specific data. However, often these representations are not well adapted for
the specific data under consideration, especially when transferring from the
natural image to the medical image domain. In this case, we can train these
models further by fine-tuning the entire model on the available data. Fine-
tuning is most important when the target task or domain is related but not
identical to the one on which the model was originally trained by adapting
the generalized capabilities of the pretrained model to specific needs without
the necessity of training a model from scratch. The optimal training strategy
depends on the specific task, availability of data, and computational resources.
AutoPrognosis-M can be used to train vision models from scratch, use their
existing representations, or finetune on the available data.
AutoPrognosis-Multimodal 7
Multimodal data integration
Multimodal ML seeks to train a model that effectively integrates multiple
types of data to enable more accurate predictions than can be obtained using
any single modality. Modalities can exhibit different relationships, including
redundancy, depending on the interactions between the information contained
in each source [37], which can additionally vary in complexity. Thus a key
challenge is discerning the relation between modalities and learning how to
integrate modalities most effectively.
We can typically decompose multimodal architectures into two compo-
nents: modality-specific representations and a joint prediction [37]. Multimodal
learning strategies differ primarily in the nature of these components and
whether they are jointly or separately learned. Three main multimodal strate-
gies exist and are incorporated in AutoPrognosis-M: Late Fusion, Early Fusion,
and Joint Fusion (Fig. 3).
Late Fusion
Late fusion is an ensemble-based approach that combines predictions from
multiple unimodal models, and thus is sometimes referred to as decision-
level fusion [38] (Fig. 3a). Each modality is processed independently using a
modality-specific model before the predictions are combined. This allows the
user to find the best classifier for each modality independently and evaluate
whether each modality has predictive power for the original task. However, this
has the drawback of not permitting interactions between modalities before the
final output, which could result in suboptimal performance when the relation-
ship between modalities is crucial for making accurate predictions or decisions.
One benefit of late fusion is the ability to incorporate new modalities by adding
an additional unimodal model and retraining only the ensembling step. We
implement late fusion using a weighted combination of unimodal tabular and
imaging models.
Early fusion
Early fusion necessitates the translation of each modality into a representation
that can be combined using a fusion module, such as concatenation, into a
single, unified representation (Fig. 3b). The combined representation is then
used as input to train a separate predictive model.
Compared to late fusion, early fusion allows interactions between different
modalities to be captured by the predictive model. However, the represen-
tations are fixed and translating different data types into effective (latent)
representations to form a unified representation can be challenging, especially
when dealing with heterogeneous data sources with differing scales, dimensions,
or types of information.
For image data, a common strategy is to use an intermediate (or the last)
layer of a vision model that was either trained to solve the relevant prediction
task or a general-purpose imaging model. For tabular data, especially if the
8 AutoPrognosis-Multimodal
number of features is relatively modest, the representation step can be skipped
and the original features are directly combined with the latent representations
extracted from the other modalities. We used concatenation to combine the
imaging and tabular features and trained a fully connected neural network on
this representation.
Joint Fusion
The fixed, independent representations used in early fusion may not capture
relevant factors for the joint prediction task. Joint fusion [4] (or intermediate
fusion [39]) aims to improve these representations using joint optimization
to enable both cross-modal relationships and modality-specific features to be
learned using end-to-end training (Fig. 3c). The added flexibility of joint fusion
can come at the cost of potentially overfitting, especially in the limited data
setting.
The most popular approaches for joint fusion use differentiable unimodal
models to produce latent representations that are combined via concatenation
and passed to a prediction head. The system is then trained in an end-to-
end manner, either from scratch or using pre-trained unimodal models. We
implement joint fusion similarly to early fusion, except we train end-to-end.
Fusion Ensembles
One major challenge is determining which fusion approach is best. Further, no
individual fusion approach may be universally best for all patients. Ensembling
has repeatedly been shown to lead to improved model performance, even when
multiple copies of the same model are trained, but can be particularly bene-
ficial when different approaches are combined due to the increased diversity
of predictions [40]. The three fusion approaches learn to combine the informa-
tion from multiple modalities in distinct ways. Thus combining the strengths
of these different strategies via an ensembling approach could improve both
the absolute performance and the robustness of the final model. We combine
the best-performing unimodal and multimodal fusion approaches in a weighted
ensemble. All ensembles were determined using Bayesian optimization [41]. We
refer to this ensemble as AutoPrognosis-M in our experiments.
Explainability
Models must be thoroughly understood and debugged to validate the under-
lying logic of the model, engender model trust from both clinical users and
patients [25], and satisfy regulatory requirements prior to clinical use [42]. This
is particularly true in the multimodal setting, where we wish to understand
what information is being used from each modality and for which patients each
modality is contributing to the model output. Consequently, AutoPrognosis-M
contains multiple classes of explainability techniques to enable ML mod-
els to be better understood. We have included feature-based interpretability
methods, such as SHAP [43] and Integrated Gradients [44], that allow us to
AutoPrognosis-Multimodal 9
understand the importance of individual features, as well as an example-based
interpretability method, SimplEx [45], that explains the model output for a
particular sample with examples of similar instances, similar to case-based
reasoning.
Uncertainty estimation
Quantifying the uncertainty of predictions is another critical component
in engendering model trust with both clinicians and patients, and can be
used both to protect against likely inaccurate predictions and inform clinical
decision-making [46, 47]. We adopted the conformal prediction framework for
uncertainty quantification. Conformal prediction produces statistically valid
prediction intervals or sets for any underlying predictor while making mini-
mal assumptions [48]. We used inductive conformal prediction [49], which uses
a calibration set to determine the width of prediction intervals or the neces-
sary size of the prediction sets, with local adaptivity to adjust the interval or
set to the specific example [50–52]. For our experiments, we used regularized
adaptive prediction sets [53].
Experiments
We demonstrate the application of AutoPrognosis-M to multimodal healthcare
data with the example of skin lesion diagnosis. This task is inherently a mul-
timodal process: primary care physicians, dermatologists, or other clinicians
use multiple factors to determine a diagnosis. Visual inspection has formed a
crucial element in lesion diagnosis, for example the “ABCD” rule or the ELM
7-point checklist [54]. These approaches have been refined to include other
characteristics beyond the appearance of the lesion at a single point in time,
such as evolution [55]. Beyond visual examination, clinicians also consider
medical history and other factors, such as itching and bleeding [10].
Data
Experiments were conducted using PAD-UFES-20 [56]. The dataset contains
2,298 skin lesion images from 1,373 patients in Brazil. Images of lesions were
captured from smartphones and each image is associated with 21 tabular fea-
tures, including the patient’s age, the anatomical region where the lesion is
located, demographic information, and other characteristics of the legion, such
as whether it itched, bled, or had grown. An overview of the clinical features
can be found in Table S.2. Further details can be found in the publication
describing the dataset [56].
Skin lesions are classified as one of six different diagnoses, three of which are
cancerous (Basal Cell Carcinoma, Squamous Cell Carcinoma, and Melanoma)
and three are non-cancerous (Actinic Keratosis, Melanocytic Nevus, and Seb-
orrheic Keratosis). As is common in studies of skin lesions, there are substantial
10 AutoPrognosis-Multimodal
Table 1 :Unimodal skin legion classification performance. The best
result for each modality is in bold. The best non-ensemble approach for each
modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
Tabular
Log. Reg. 63.6% 63.3% 0.890 0.559 83.0% 0.904 0.814 0.657
Random Forest 65.2% 54.0% 0.865 0.535 83.0% 0.903 0.810 0.662
XGBoost 66.5% 54.4% 0.875 0.545 81.3% 0.885 0.797 0.623
CatBoost 64.3% 57.2% 0.877 0.545 83.4% 0.902 0.822 0.667
MLP 69.7% 52.8% 0.878 0.526 83.1% 0.902 0.819 0.663
AutoPrognosis 69.4% 61.9% 0.891 0.580 83.9% 0.909 0.825 0.676
Imaging
ResNet18 59.8% 57.8% 0.885 0.547 81.9% 0.897 0.808 0.637
ResNet34 57.4% 54.5% 0.873 0.517 80.3% 0.881 0.790 0.603
ResNet50 60.7% 60.0% 0.888 0.562 82.0% 0.888 0.811 0.637
ResNet101 60.3% 56.6% 0.886 0.543 81.6% 0.883 0.802 0.628
ResNet152 63.6% 59.6% 0.895 0.578 82.1% 0.892 0.810 0.640
EfficientNetB0 64.3% 60.8% 0.899 0.577 82.4% 0.900 0.807 0.645
EfficientNetB1 65.5% 63.7% 0.901 0.602 82.6% 0.899 0.811 0.648
EfficientNetB2 65.1% 59.7% 0.899 0.578 81.5% 0.888 0.801 0.628
EfficientNetB3 64.2% 62.6% 0.902 0.598 81.9% 0.898 0.805 0.635
EfficientNetB4 66.7% 62.1% 0.899 0.602 81.9% 0.897 0.807 0.635
EfficientNetB5 66.7% 62.8% 0.904 0.609 82.6% 0.903 0.810 0.649
MobileNetV2 58.4% 54.5% 0.868 0.512 79.6% 0.877 0.779 0.590
ViTBase 67.1% 65.0% 0.917 0.618 82.9% 0.913 0.816 0.657
ViTLarge 68.1% 65.2% 0.916 0.631 84.1% 0.916 0.831 0.682
DinoV2Small 68.1% 65.0% 0.913 0.630 84.2% 0.912 0.834 0.683
DinoV2Base 68.5% 65.9% 0.914 0.639 84.0% 0.913 0.833 0.679
DinoV2Large 69.0% 65.8% 0.916 0.640 84.4% 0.913 0.834 0.686
Imaging ensemble 71.6% 69.4% 0.927 0.672 85.3% 0.927 0.845 0.706
differences in the number of lesions with each diagnosis, resulting in class imbal-
ance (Table S.2). Aggregating the diagnoses into cancerous and non-cancerous
almost eliminates this imbalance (47% cancerous, 53% non-cancerous). To
demonstrate the suitability of our framework for balanced and imbalanced
classification scenarios, we explore both the task of predicting the specific diag-
noses and the binary determination of whether a given lesion is cancerous. We
assessed lesion categorization usin accuracy, balanced accuracy, area under the
receiver operating curve (AUROC), and macro F1 score, and assessed can-
cer diagnosis using accuracy, AUROC, F1 score and Matthew’s correlation
coefficient (MCC).
To account for the presence of multiple images for some patients and
the imbalance in incidence of different diagnoses, we conducted 5-fold cross-
validation with stratified sampling, ensuring all images from the same patient
were contained in the same fold. Additionally, we used 20% of the training
set of each fold to optimize hyperparameters and ensemble weights. 13 clinical
variables had substantial levels of missingness (c. 35%) and this missingness
was often strongly associated with diagnosis. Consequently, we retained only
features without this missingness. Some other features had entries recorded
AutoPrognosis-Multimodal 11
as “unknown,” corresponding to the patient being asked the question but not
knowing the answer. This was the case for six features, with an occurrence
between 0.1% and 17%. This resulted in eight tabular variables being retained.
Categorical variables were one-hot encoded, yielding 27 clinical features and
one image for each sample.
How predictive is each modality in isolation?
Collecting additional information is never without expense. This can be finan-
cial, time, or even adverse effects of collecting the information. Thus it is
critical to understand whether a modality is necessary and brings additional
predictive power. Therefore, we first used AutoPrognosis-M to optimize ML
pipelines for each modality separately to quantify the value of imaging and clin-
ical features individually. Both the clinical variables and lesion images exhibit
some predictive power for lesion categorization and cancer diagnosis (Table
1), with the individual imaging models outperforming the tabular models for
lesion categorization while achieving similar results for cancer diagnosis.
Tabular. We tested several classification models in isolation, as well as
the performance of AutoPrognosis-M on just the tabular modality, which is
equivalent to AutoPrognosis [16]. Overall, AutoPrognosis outperformed any
individual tabular model, in particular for cancer diagnosis, demonstrating
the importance of AutoML and ensembling (Table 1). However, the relative
outperformance over logistic regression for lesion categorization and CatBoost
for cancer diagnosis was relatively minor, perhaps reflecting the nature of the
structured information available.
Imaging. The different imaging architectures displayed significant vari-
ability in performance across the lesion categorization and cancer diagnosis
prediction tasks, however several trends could be observed. The vision trans-
former architectures (ViT and DINOv2) outperformed the CNN-based models
(ResNet, EfficientNet, MobileNet) almost universally across both tasks. One
explanation beyond the model architecture could be the pre-training set, which
differed between the transformer and CNN models (see Table S.1). Increas-
ing the size of models typically led to improvements in performance for the
transformer models, although the largest models did not necessarily improve
performance (e.g. DINOv2Large vs. DINOv2Base), while the trend was less
clear for the CNN-based models. All model architectures consistently under-
performed when trained from initialization, thus all results shown are from
fine-tuning pre-trained models.
Ensembling the best-performing image models resulted in a substantial
increase in performance across all metrics for both prediction tasks. While
the transformers outperformed the CNNs individually, many of the ensembles
contained CNN-based approaches, demonstrating the importance of diversity
in ensemble learning.
12 AutoPrognosis-Multimodal
Table 2 :Skin legion classification performance. All multimodal
approaches outperform the unimodal baselines. AutoPrognosis-M achieves the
best results.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
Tabular ensemble 69.4% 61.9% 0.891 0.580 83.9% 0.909 0.825 0.676
Best image model 68.5% 65.9% 0.914 0.639 84.4% 0.913 0.834 0.686
Imaging ensemble 71.6% 69.4% 0.927 0.672 85.3% 0.927 0.845 0.706
Best late fusion 77.0% 72.8% 0.935 0.706 89.2% 0.950 0.883 0.782
Late fusion ensemble 79.0% 74.7% 0.939 0.730 89.1% 0.954 0.882 0.781
Best early fusion 70.9% 68.1% 0.918 0.657 85.7% 0.922 0.847 0.713
Early fusion ensemble 74.7% 70.2% 0.930 0.701 86.7% 0.936 0.856 0.731
Best joint fusion 73.8% 71.4% 0.930 0.698 87.5% 0.940 0.866 0.748
Joint fusion ensemble 75.6% 71.9% 0.937 0.716 88.8% 0.951 0.880 0.775
AutoPrognosis-M 80.6% 75.8% 0.945 0.758 89.8% 0.956 0.889 0.794
What benefit does multimodal ML provide?
Now that we have shown that each modality has a potential predictive capa-
bility for skin lesion diagnoses, we sought to quantify what, if any, benefit
incorporating both modalities when issuing predictions provides. To do this,
we assessed each of the multimodal strategies included in AutoPrognosis-M.
All three fusion approaches demonstrate significant improvements over the
unimodal classifiers, demonstrating the importance of integrating data from
multiple sources. In Table 2, we report the best single model for each fusion
strategy, together with the impact of ensembling the best-performing models as
measured on the held-out portion of the training set. The impact of combining
the modalities varied across the various model architectures, with the results
also differing for each of the fusion strategies, late (Table S.3), early (Table
S.4), and joint (Table S.5).
Perhaps surprisingly, late fusion outperformed both early and joint fusion,
with early fusion the worst-performing fusion approach. This is likely a conse-
quence of the relatively strong predictive power of the tabular features and the
number of samples available, but could also reveal the nature of the relationship
between the two modalities. Again, ensembling the best-performing models for
each fusion strategy provides a relatively small but consistent improvement,
except for the cancer diagnosis task for late fusion, where the best individual
model performed similarly to the ensemble.
AutoPrognosis-M leverages the power of each fusion strategy and the uni-
modal models by combining them in an ensemble. This approach performed
best across both tasks as measured by any metric, improving the performance
over any one fusion approach alone. Despite late fusion outperforming the other
multimodal and unimodal approaches, it was not always selected as the most
important component in the ensemble and the largest weight assigned to any
of the five strategies (two unimodal, three fusion) was 39%, further reinforcing
the importance of diversity.
AutoPrognosis-Multimodal 13
0% 20% 40% 60% 80% 100%
Proportion Selected0%2%4%6%8%10%12%14%16%Absolute % gain in Bal. Acc.
T abular onlyMultimodalSelective Acquisition
(a) Lesion categorization
0% 20% 40% 60% 80% 100%
Proportion Selected0%1%2%3%4%5%6%7%Absolute % gain in Accuracy
T abular onlyMultimodalSelective Acquisition (b) Cancer diagnosis
Fig. 4 : Selective acquisition of images based on conformal prediction. By
acquiring images for around 20% of samples with the highest predicted uncer-
tainty based on the tabular features, we capture c. 55% and 65% of the
improvement of the multimodal classifier for (a) lesion categorization and (b)
cancer diagnosis, respectively. We approach the performance of the multimodal
classifier by acquiring images for around half of all patients.
When are additional modalities most helpful?
While we have shown multimodal systems significantly outperform unimodal
approaches for lesion categorization and cancer diagnosis, we might not require
all modalities for all patients. As mentioned previously, there might be down-
sides to collecting additional information, thus identifying when we would
benefit is both important and often a key clinical decision, since modalities are
typically acquired sequentially.
We demonstrate how AutoPrognosis-M can be used to answer this question.
We assumed access initially to the clinical features and wanted to identify for
which patients to acquire an image of the lesion. We used conformal prediction
to estimate the uncertainty of each prediction and chose to acquire images for
the patients with the highest uncertainty.
By acquiring images for around 20% of samples with the highest predicted
uncertainty based on the tabular features, we can capture around two-thirds
of the total improvement of the multimodal ensemble classifier for the cancer
diagnosis task (Fig. 4b) and over half for the lesion categorization task (Fig.
4a). Acquiring lesion images for around 50% of patients results in coming close
to matching the performance of the multimodal classifier, thereby halving the
number of images needed to be collected.
Understanding the information provided by each
modality
Understanding why predictions were issued is incredibly important across med-
ical contexts. We demonstrate how the interpretability techniques included in
14 AutoPrognosis-Multimodal
bleed_T
ruehurt_T
rueage itch_T
rueelevation_T
rueregion_NOSE changed_False grew_T
rue−0.1−0.0500.050.10.15Image Attributions - Image only Attributions - Joint fusion Tabular Attributions - Joint fusion
Label: BCC Pred: {BCC: 0.18, ACK: 0.00, NEV : 0.70,
SEK: 0.11, SCC: 0.00, MEL: 0.00}Pred: {BCC: 0.55, ACK: 0.01, NEV : 0.43,
SEK: 0.00, SCC: 0.01, MEL: 0.00}
Fig. 5 : Comparison of explanations for unimodal and multimodal models
using integrated gradients. The original image (left, img id: PAT 521984412)
together with attributions for the unimodal (center left) and joint fusion Effi-
cientNetB4 models (center right and right).
AutoPrognosis-M can be used to analyze the rationale for predictions across
multiple modalities. We used integrated gradients [44] to analyze the pre-
dictions from the image-only and joint fusion variants of EfficientNetB4. An
example is shown in Fig. 5.
The image-only model incorrectly classifies the lesion as Melanocytic Nevus
(NEV, non-cancerous), while the joint fusion model correctly identifies the
lesion as Basal Cell Carcinoma (BCC, cancerous). The image attributions (Fig.
5 center) are somewhat similar, both placing the most importance on the lesion,
although there are minor differences in several areas. Importantly, the clinical
variables allow the multimodal approach to correct the image-only prediction.
NEV is typically asymptomatic [57] and more common in younger individu-
als [58]. The patient reported the lesion had bled, hurt, and itched, which the
multimodal model correctly identified made NEV less likely and increased the
chance of BCC, offset by the relatively young age of the patient (32) which
reduced the magnitude of the BCC prediction. This example clearly demon-
strates the importance of incorporating both modalities and the understanding
that explainability methods can provide.
Discussion
Predictive modeling has the potential to support clinical decision-making and
improve outcomes. However, incorporating multiple types of data into compu-
tational approaches is not yet widespread in medicine and healthcare. In this
paper, we demonstrated the utility of AutoPrognosis-M for developing clin-
ical models from multimodal data using AutoML. Our framework simplifies
the application of multimodal fusion strategies, automatically determining the
best strategy for the available data and clinical application.
We have shown how AutoPrognosis-M can be used to perform unimodal
analysis for tabular and imaging data, enabling clinicians to understand when
multimodal approaches will provide benefit. Beyond prediction, we used uncer-
tainty estimation to determine for which patients additional information is
necessary and explainability techniques to improve model understanding.
AutoPrognosis-Multimodal 15
The use of AutoML frameworks such as AutoPrognosis-M can aid in model
development, but does not alter the necessity to ensure models are suitably
validated to ensure they exhibit the desired characteristics, such as being accu-
rate, reliable, and fair. As with any learning algorithm, significant care must
be taken by the user to ensure appropriate study design and data curation,
without which an inaccurate or biased model could be developed which could
have adverse effects on patient health.
While there have been bespoke multimodal ML systems developed, few
general-purpose frameworks exist. HAIM [59] is an early fusion approach
using user-defined pre-trained feature-extraction models to extract represen-
tations that are concatenated and passed to an XGBoost model. Wang et
al. proposed a multimodal approach for esophageal variceal bleeding predic-
tion [60]. They first trained an imaging model and then used automated
machine learning to develop a classifier based on structured clinical data and
the output of the imaging model. Finally, AutoGluon-Multimodal [61] enables
fine-tuning of pretrained models across multiple modalities, combining their
outputs via late fusion. In contrast, AutoPrognosis-M incorporates multiple
fusion approaches, including both early and late fusion as possible strategies,
while our experiments highlight the limitations of only considering a single
fusion strategy.
While in this paper, we demonstrated the application of AutoPrognosis-M
to the problem of diagnosing skin lesions using smartphone images and clinical
variables, our framework is generally applicable and can naturally be extended
to additional modalities and both new unimodal models and fusion strategies.
We believe AutoPrognosis-M represents a powerful tool for clinicians and ML
experts when working with data from multiple modalities and hope our aids
the adoption of multimodal ML methods in healthcare and medicine.
Code and data availability. AutoPrognosis-M is available at https:
//github.com/vanderschaarlab/AutoPrognosis-Multimodal. PAD-UFES-20 is
freely available at https://data.mendeley.com/datasets/zr7vgbcyr2/1 (DOI:
10.17632/zr7vgbcyr2.1) [56]. All preprocessing and the splits used for
our experiments can be found at https://github.com/vanderschaarlab/
AutoPrognosis-Multimodal.
References
[1] Abr` amoff, M. D., Lavin, P. T., Birch, M., Shah, N. & Folk, J. C. Pivotal
trial of an autonomous AI-based diagnostic system for detection of diabetic
retinopathy in primary care offices. npj Digit. Med. 1(1), 39 (2018). https:
//doi.org/10.1038/s41746-018-0040-6 .
[2] Rajpurkar, P., Chen, E., Banerjee, O. & Topol, E. J. AI in health and medicine.
Nat. Med. 28(1), 31–38 (2022). https://doi.org/10.1038/s41591-021-01614-0 .
[3] Kline, A. et al. Multimodal machine learning in precision health: A scop-
ing review. npj Digit. Med. 5(1), 171 (2022). https://doi.org/10.1038/
16 AutoPrognosis-Multimodal
s41746-022-00712-8 .
[4] Huang, S.-C., Pareek, A., Seyyedi, S., Banerjee, I. & Lungren, M. P. Fusion of
medical imaging and electronic health records using deep learning: A systematic
review and implementation guidelines. npj Digit. Med. 3(1), 136 (2020). https:
//doi.org/10.1038/s41746-020-00341-z .
[5] Leslie, A. & Jones, P. R., A. J.and Goddard. The influence of clinical informa-
tion on the reporting of CT by radiologists. Br. J. Radiol. 73(874), 1052–1055
(2000). https://doi.org/10.1259/bjr.73.874.11271897 .
[6] Castillo, C., Steffens, T., Sim, L. & Caffery, L. The effect of clinical information
on radiology reporting: A systematic review. J. Med. Radiat. Sci. 68(1), 60–74
(2021). https://doi.org/10.1002/jmrs.424 .
[7] Boonn, W. W. & Langlotz, C. P. Radiologist use of and perceived need for
patient data access. J. Digit. Imaging 22(4), 357–362 (2009). https://doi.org/
10.1007/s10278-008-9115-2 .
[8] Wang, M. Y., Asanad, S., Asanad, K., Karanjia, R. & Sadun, A. A. Value of
medical history in ophthalmology: A study of diagnostic accuracy. J. Curr.
Ophthalmol. 30(4), 359–364 (2018). https://doi.org/https://doi.org/10.1016/
j.joco.2018.09.001 .
[9] Ombrello, M. J., Sikora, K. A. & Kastner, D. L. Genetics, genomics, and their
relevance to pathology and therapy. Best Pract. Res.: Clin. Rheumatol. 28(2),
175–189 (2014). https://doi.org/https://doi.org/10.1016/j.berh.2014.05.001 .
[10] Bergenmar, M., Hansson, J. & Brandberg, Y. Detection of nodular and super-
ficial spreading melanoma with tumour thickness ≤2.0 mm - an interview
study. Eur. J. Cancer Prev. 11(1), 49–55 (2002). https://doi.org/10.1097/
00008469-200202000-00007 .
[11] Li, P., Hu, Y. & Liu, Z.-P. Prediction of cardiovascular diseases by integrating
multi-modal features with machine learning methods. Biomed. Signal Pro-
cess. Control. 66, 102474 (2021). https://doi.org/https://doi.org/10.1016/j.
bspc.2021.102474 .
[12] Liu, Y. et al. A deep learning system for differential diagnosis of skin dis-
eases. Nat. Med. 26(6), 900–908 (2020). URL https://doi.org/10.1038/
s41591-020-0842-3. https://doi.org/10.1038/s41591-020-0842-3 .
[13] Yala, A., Lehman, C., Schuster, T., Portnoi, T. & Barzilay, R. A deep learn-
ing mammography-based model for improved breast cancer risk prediction.
Radiology 292(1), 60–66 (2019). https://doi.org/10.1148/radiol.2019182716 .
[14] Kyono, T., Gilbert, F. J. & van der Schaar, M. Improving workflow efficiency
for mammography using machine learning. J. Am. Coll. Radiol. 17(1), 56–63
(2020). https://doi.org/10.1016/j.jacr.2019.05.012 .
AutoPrognosis-Multimodal 17
[15] Wu, J. et al. Radiological tumour classification across imaging modality and
histology. Nat. Mach. Intell. 3(9), 787–798 (2021). https://doi.org/10.1038/
s42256-021-00377-0 .
[16] Imrie, F., Cebere, B., McKinney, E. F. & van der Schaar, M. AutoProgno-
sis 2.0: Democratizing diagnostic and prognostic modeling in healthcare with
automated machine learning. PLOS Digit. Health 2(6), e0000276 (2023).
https://doi.org/10.1371/journal.pdig.0000276 .
[17] Alaa, A. M., Bolton, T., Di Angelantonio, E., Rudd, J. H. F. & van der Schaar,
M. Cardiovascular disease risk prediction using automated machine learning: A
prospective study of 423,604 UK Biobank participants. PLoS One 14(5), 1–17
(2019). https://doi.org/10.1371/journal.pone.0213653 .
[18] Imrie, F., Rauba, P. & van der Schaar, M. Redefining digital health interfaces
with large language models. arXiv preprint arXiv:2310.03560 (2023) .
[19] Alaa, A. M. & van der Schaar, M. Prognostication and risk factors for cystic
fibrosis via automated machine learning. Sci. Rep. 8(1), 11242 (2018). https:
//doi.org/10.1038/s41598-018-29523-2 .
[20] Alaa, A. M., Gurdasani, D., Harris, A. L., Rashbass, J. & van der Schaar,
M. Machine learning to guide the use of adjuvant therapies for breast can-
cer. Nat. Mach. Intell. 3(8), 716–726 (2021). https://doi.org/10.1038/
s42256-021-00353-8 .
[21] Callender, T. et al. Assessing eligibility for lung cancer screening using parsimo-
nious ensemble machine learning models: A development and validation study.
PLOS Med. 20(10), e1004287 (2023). https://doi.org/10.1371/journal.pmed.
1004287 .
[22] Feurer, M. et al. Efficient and robust automated machine learning. Adv. Neural
Inf. Process. Syst. 28, 2755–2763 (2015) .
[23] Thornton, C., Hutter, F., Hoos, H. H. & Leyton-Brown, K. Auto-WEKA: Com-
bined selection and hyperparameter optimization of classification algorithms.
Proceedings of the 19th ACM SIGKDD International Conference on Knowledge
Discovery and Data Mining 847–855 (2013). https://doi.org/10.1145/2487575.
2487629 .
[24] Olson, R. S. & Moore, J. H. TPOT: A tree-based pipeline optimization tool
for automating machine learning. In: International Conference on Machine
Learning - AutoML Workshop 66–74 (2016) .
[25] Imrie, F., Davis, R. & van der Schaar, M. Multiple stakeholders drive diverse
interpretability requirements for machine learning in healthcare. Nat. Mach.
Intell. 5(8), 824–829 (2023). https://doi.org/10.1038/s42256-023-00698-2 .
[26] Callender, T. & van der Schaar, M. Automated machine learning as a partner
in predictive modelling. Lancet Digit. Health 5(5), e254–e256 (2023). https:
//doi.org/10.1016/S2589-7500(23)00054-7 .
18 AutoPrognosis-Multimodal
[27] Waring, J., Lindvall, C. & Umeton, R. Automated machine learning: Review
of the state-of-the-art and opportunities for healthcare. Artif. Intell. Med. 104,
101822 (2020) .
[28] van Buuren, S. & Groothuis-Oudshoorn, K. mice: Multivariate imputation by
chained equations in R. J. Stat. Softw. 45(3), 1–67 (2011). https://doi.org/
10.18637/jss.v045.i03 .
[29] Stekhoven, D. J. & B¨ uhlmann, P. MissForest—non-parametric missing value
imputation for mixed-type data. Bioinformatics 28(1), 112–118 (2011). https:
//doi.org/10.1093/bioinformatics/btr597 .
[30] He, K., Zhang, X., Ren, S. & Sun, J. Deep residual learning for image recogni-
tion. In: Proceedings of the IEEE Conference on Computer Vision and Pattern
Recognition 770–778 (2016) .
[31] Tan, M. & Le, Q. EfficientNet: Rethinking model scaling for convolutional
neural networks. In: International Conference on Machine Learning 6105–6114
(2019) .
[32] Sandler, M., Howard, A., Zhu, M., Zhmoginov, A. & Chen, L.-C. MobileNetV2:
Inverted residuals and linear bottlenecks. In: Proceedings of the IEEE Confer-
ence on Computer Vision and Pattern Recognition 4510–4520 (2018) .
[33] Dosovitskiy, A. et al. An image is worth 16x16 words: Transformers for image
recognition at scale. In: International Conference on Learning Representations
(2021) .
[34] Weiss, K., Khoshgoftaar, T. M. & Wang, D. A survey of transfer learning. J.
Big Data 3, 1–40 (2016) .
[35] Zhuang, F. et al. A comprehensive survey on transfer learning. Proc. IEEE
109(1), 43–76 (2020) .
[36] Oquab, M. et al. DINOv2: Learning robust visual features without supervision.
Trans. Mach. Learn. Res. (2024) .
[37] Baltruˇ saitis, T., Ahuja, C. & Morency, L.-P. Multimodal machine learning: A
survey and taxonomy. IEEE Trans. Pattern Anal. Mach. Intell. 41(2), 423–443
(2019). https://doi.org/10.1109/TPAMI.2018.2798607 .
[38] Sharma, R., Pavlovic, V. I. & Huang, T. S. Toward multimodal human-
computer interface. Proc. IEEE 86(5), 853–869 (1998) .
[39] Stahlschmidt, S. R., Ulfenborg, B. & Synnergren, J. Multimodal deep learning
for biomedical data fusion: A review. Brief. Bioinform. 23(2), bbab569 (2022) .
[40] Krogh, A. & Vedelsby, J. Neural network ensembles, cross validation, and active
learning. Adv. Neural Inf. Process. Syst. 7(1994) .
AutoPrognosis-Multimodal 19
[41] Akiba, T., Sano, S., Yanase, T., Ohta, T. & Koyama, M. Optuna: A next-
generation hyperparameter optimization framework. In: Proceedings of the
25th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining 2623–2631 (2019) .
[42] Medicines & Healthcare products Regulatory Agency. Soft-
ware and ai as a medical device change programme -
roadmap (2023). URL https://www.gov.uk/government/
publications/software-and-ai-as-a-medical-device-change-programme/
software-and-ai-as-a-medical-device-change-programme-roadmap. Updated
14 June 2023 .
[43] Lundberg, S. M. & Lee, S.-I. A unified approach to interpreting model
predictions. Adv. Neural Inf. Process. Syst. 30(2017) .
[44] Sundararajan, M., Taly, A. & Yan, Q. Axiomatic attribution for deep networks.
In: International Conference on Machine Learning 3319–3328 (2017) .
[45] Crabbe, J., Qian, Z., Imrie, F. & van der Schaar, M. Explaining latent rep-
resentations with a corpus of examples. Adv. Neural Inf. Process. Syst. 34,
12154–12166 (2021) .
[46] Kompa, B., Snoek, J. & Beam, A. L. Second opinion needed: Communicating
uncertainty in medical machine learning. npj Digit. Med. 4(1), 4 (2021). https:
//doi.org/10.1038/s41746-020-00367-3 .
[47] Helou, M. A., DiazGranados, D., Ryan, M. S. & Cyrus, J. W. Uncertainty
in decision making in medicine: A scoping review and thematic analysis of
conceptual models. Acad. Med. 95(1) (2020) .
[48] Vovk, V., Gammerman, A. & Shafer, G. Algorithmic learning in a random world
(Springer Science & Business Media, 2005).
[49] Vovk, V. Conditional validity of inductive conformal predictors. In: Asian
Conference on Machine Learning 475–490 (2012) .
[50] Papadopoulos, H., Vovk, V. & Gammerman, A. Regression conformal prediction
with nearest neighbours. J. Artif. Intell. Res. 40, 815–840 (2011) .
[51] Johansson, U., S¨ onstr¨ od, C. & Linusson, H. Efficient conformal regressors using
bagged neural nets. In: 2015 International Joint Conference on Neural Networks
1–8 (2015) .
[52] Seedat, N., Jeffares, A., Imrie, F. & van der Schaar, M. Improving adaptive
conformal prediction using self-supervised learning. In: Proceedings of The 26th
International Conference on Artificial Intelligence and Statistics (2023) .
[53] Angelopoulos, A., Bates, S., Malik, J. & Jordan, M. I. Uncertainty sets for
image classifiers using conformal prediction. In: International Conference on
Learning Representations (2021) .
20 AutoPrognosis-Multimodal
[54] Argenziano, G. et al. Epiluminescence microscopy for the diagnosis of doubtful
melanocytic skin lesions: Comparison of the ABCD rule of dermatoscopy and
a new 7-point checklist based on pattern analysis. Arch. Dermatol. 134 (12),
1563–1570 (1998). https://doi.org/10.1001/archderm.134.12.1563 .
[55] Abbasi, N. R. et al. Early diagnosis of cutaneous melanoma: Revisiting the
ABCD criteria. JAMA 292(22), 2771–2776 (2004) .
[56] Pacheco, A. G. et al. PAD-UFES-20: A skin lesion dataset composed of patient
data and clinical images collected from smartphones. Data Brief 32, 106221
(2020). https://doi.org/10.1016/j.dib.2020.106221 .
[57] Macneal, P. & Patel, B. C. Congenital melanocytic nevi. StatPearls Publishing,
Treasure Island (FL) (2020) .
[58] Zalaudek, I. et al. Frequency of dermoscopic nevus subtypes by age and body
site: A cross-sectional study. Arch. Dermatol. 147(6), 663–670 (2011). https:
//doi.org/10.1001/archdermatol.2011.149 .
[59] Soenksen, L. R. et al. Integrated multimodal artificial intelligence framework
for healthcare applications. npj Digit. Med. 5(1), 149 (2022). https://doi.org/
10.1038/s41746-022-00689-4 .
[60] Wang, Y. et al. Automated multimodal machine learning for esophageal variceal
bleeding prediction based on endoscopy and structured data. J. Digit. Imaging
36(1), 326–338 (2023). https://doi.org/10.1007/s10278-022-00724-6 .
[61] Tang, Z. et al. AutoGluon-Multimodal (AutoMM): Supercharging multimodal
AutoML with foundation models. In: International Conference on Automated
Machine Learning (2024) .
AutoPrognosis-Multimodal 21
Table S.1 :Imaging models included in AutoPrognosis-M. CNN -
Convolutional Neural Network. ViT - Vision Transformer.
Model Type # Param.Pretraining
DataEmbedding
sizeRef.
ResNet18 CNN 11.7 M ImageNet-1k 512 [30]
ResNet34 CNN 21.8 M ImageNet-1k 512 [30]
ResNet50 CNN 25 M ImageNet-1k 2048 [30]
ResNet101 CNN 44.5 M ImageNet-1k 2048 [30]
ResNet152 CNN 60.2 M ImageNet-1k 2048 [30]
EfficientNetB0 CNN 5.3 M ImageNet-1k 320 [31]
EfficientNetB1 CNN 7.8 M ImageNet-1k 320 [31]
EfficientNetB2 CNN 9.2 M ImageNet-1k 352 [31]
EfficientNetB3 CNN 12 M ImageNet-1k 384 [31]
EfficientNetB4 CNN 19 M ImageNet-1k 448 [31]
EfficientNetB5 CNN 30 M ImageNet-1k 512 [31]
MobileNetV2 CNN 3.4 M ImageNet-1k 320 [32]
ViTBase ViT-B/16 86 M ImageNet-1k 768 [33]
ViTLarge ViT-L/16 307 M ImageNet-21k 1024 [33]
DinoV2Small ViT-S/14 22 M LVD-142M 384 [36]
DinoV2Base ViT-B/14 86 M LVD-142M 768 [36]
DinoV2Large ViT-L/14 307 M LVD-142M 1024 [36]
22 AutoPrognosis-Multimodal
Table S.2 : Clinical variables in the PAD-UFES-20 dataset (n=2,298).
Diagnosis
Basal Cell Carcinoma (BCC) 845 (36.8%)
Squamous Cell Carcinoma (SCC) 192 (8.4%)
Melanoma (MEL) 52 (2.3%)
Actinic Keratosis (ACK) 730 (31.8%)
Melanocytic Nevus (NEV) 244 (10.6%)
Seborrheic Keratosis (SEK) 235 (10.2%)
Age
6-29 92 (4.0%)
30-49 386 (16.8%)
50-69 1,098 (47.8%)
70-94 722 (31.4%)
Region
Face 570 (24.5%)
Forearm 392 (17.1%)
Chest 280 (12.2%)
Back 248 (10.8%)
Arm 192 (8.4%)
Nose 158 (6.9%)
Hand 126 (5.5%)
Neck 93 (4.0%)
Thigh 73 (3.2%)
Ear 73 (3.2%)
Abdomen 36 (1.6%)
Lip 23 (1.0%)
Scalp 18 (0.8%)
Foot 16 (0.7%)
Itch
Yes 1,455 (63.3%)
No 837 (36.4%)
Unknown 6 (0.3%)
Grew
Yes 925 (40.2%)
No 971 (42.3%)
Unknown 402 (17.5%)
Hurt
Yes 397 (17.3%)
No 1,891 (82.3%)
Unknown 10 (0.4%)
Changed
Yes 202 (0.9%)
No 1,700 (74.0%)
Unknown 396 (17.2%)
Bleed
Yes 614 (26.7%)
No 1,678 (73.0%)
Unknown 6 (0.3%)
Elevation
Yes 1,433 (62.4%)
No 863 (37.6%)
Unknown 2 (0.1%)
AutoPrognosis-Multimodal 23
Table S.3 :Late fusion skin legion classification performance. The best
result for each modality is in bold. The best non-ensemble approach for each
modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 74.0% 68.0% 0.921 0.656 87.8% 0.946 0.867 0.755
ResNet34 73.2% 67.1% 0.920 0.638 87.7% 0.946 0.867 0.753
ResNet50 73.6% 69.8% 0.925 0.674 87.8% 0.943 0.867 0.754
ResNet101 73.6% 68.4% 0.926 0.665 86.8% 0.942 0.855 0.734
ResNet152 75.5% 70.2% 0.928 0.684 88.1% 0.944 0.870 0.760
EfficientNetB0 75.2% 69.3% 0.925 0.665 87.9% 0.947 0.867 0.756
EfficientNetB1 75.5% 71.3% 0.929 0.693 88.1% 0.949 0.870 0.762
EfficientNetB2 75.5% 69.4% 0.927 0.668 87.6% 0.944 0.864 0.751
EfficientNetB3 74.7% 71.0% 0.928 0.685 88.1% 0.946 0.869 0.760
EfficientNetB4 75.4% 69.9% 0.928 0.672 88.0% 0.946 0.868 0.758
EfficientNetB5 76.9% 72.0% 0.928 0.696 87.9% 0.948 0.867 0.757
MobileNetV2 72.2% 65.6% 0.912 0.627 87.1% 0.939 0.857 0.739
ViTBase 76.6% 71.6% 0.937 0.700 87.3% 0.948 0.861 0.744
ViTLarge 76.3% 71.2% 0.936 0.697 88.0% 0.950 0.869 0.759
DinoV2Small 76.8% 70.9% 0.937 0.695 89.2% 0.950 0.883 0.782
DinoV2Base 77.0% 72.8% 0.935 0.706 88.5% 0.951 0.875 0.767
DinoV2Large 77.7% 72.3% 0.935 0.697 87.5% 0.948 0.864 0.749
Ensemble 79.0% 74.7% 0.939 0.730 89.1% 0.954 0.882 0.781
Table S.4 :Early fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 59.9% 59.2% 0.879 0.558 81.8% 0.899 0.803 0.635
ResNet34 58.1% 56.3% 0.865 0.541 80.9% 0.884 0.795 0.614
ResNet50 62.8% 61.7% 0.891 0.590 84.1% 0.908 0.832 0.679
ResNet101 66.8% 63.4% 0.904 0.617 84.4% 0.921 0.833 0.685
ResNet152 69.1% 64.6% 0.910 0.636 83.3% 0.904 0.821 0.663
EfficientNetB0 66.0% 61.2% 0.884 0.601 83.4% 0.903 0.822 0.665
EfficientNetB1 64.3% 60.8% 0.884 0.586 82.8% 0.903 0.816 0.655
EfficientNetB2 63.8% 58.7% 0.884 0.577 80.3% 0.882 0.786 0.602
EfficientNetB3 64.1% 58.8% 0.882 0.569 81.6% 0.896 0.801 0.629
EfficientNetB4 66.4% 62.2% 0.894 0.607 82.9% 0.902 0.818 0.656
EfficientNetB5 66.3% 61.2% 0.893 0.603 82.0% 0.898 0.807 0.638
MobileNetV2 64.4% 59.4% 0.880 0.576 82.1% 0.898 0.808 0.641
ViTBase 58.1% 55.2% 0.820 0.517 80.7% 0.881 0.792 0.612
ViTLarge 70.1% 66.6% 0.915 0.653 84.1% 0.914 0.829 0.680
DinoV2Small 70.9% 68.1% 0.918 0.657 85.7% 0.922 0.847 0.713
DinoV2Base 69.1% 64.8% 0.904 0.635 83.5% 0.912 0.821 0.669
DinoV2Large 70.4% 62.8% 0.906 0.630 83.8% 0.915 0.829 0.674
Ensemble 74.7% 70.2% 0.930 0.701 86.7% 0.936 0.856 0.731
24 AutoPrognosis-Multimodal
Table S.5 :Joint fusion skin legion classification performance. The
best result for each modality is in bold. The best non-ensemble approach for
each modality is underlined.
Lesion Categorization (6-way) Cancer Diagnosis (Binary)
Method Acc. Bal. Acc. AUROC F1 Acc. AUROC F1 MCC
ResNet18 65.8% 61.6% 0.899 0.588 83.4% 0.911 0.823 0.667
ResNet34 62.8% 61.6% 0.889 0.575 82.1% 0.891 0.809 0.639
ResNet50 66.1% 60.1% 0.879 0.568 84.3% 0.909 0.833 0.684
ResNet101 67.5% 61.5% 0.892 0.595 83.9% 0.911 0.827 0.675
ResNet152 68.8% 66.3% 0.913 0.642 85.3% 0.921 0.842 0.704
EfficientNetB0 62.9% 64.0% 0.899 0.605 84.7% 0.921 0.833 0.691
EfficientNetB1 66.1% 65.1% 0.905 0.624 85.4% 0.926 0.843 0.705
EfficientNetB2 68.3% 63.9% 0.912 0.620 84.0% 0.914 0.828 0.677
EfficientNetB3 68.1% 65.3% 0.913 0.634 84.8% 0.920 0.837 0.693
EfficientNetB4 69.0% 66.2% 0.915 0.644 86.3% 0.933 0.853 0.724
EfficientNetB5 71.0% 66.2% 0.922 0.648 87.3% 0.936 0.863 0.744
MobileNetV2 61.9% 60.5% 0.894 0.572 83.3% 0.908 0.821 0.665
ViTBase 64.9% 63.6% 0.898 0.600 83.3% 0.909 0.822 0.665
ViTLarge 72.6% 68.4% 0.930 0.676 87.5% 0.940 0.866 0.748
DinoV2Small 69.6% 66.4% 0.915 0.651 86.2% 0.929 0.856 0.725
DinoV2Base 73.8% 71.4% 0.930 0.698 87.0% 0.935 0.861 0.740
DinoV2Large 73.8% 68.2% 0.933 0.678 86.6% 0.941 0.857 0.733
Ensemble 75.6% 71.9% 0.937 0.716 88.0% 0.951 0.880 0.775 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18181v1 | http://arxiv.org/pdf/2407.18181v1 | Gene Regulatory Network Inference from Pre-trained Single-Cell Transcriptomics Transformer with Joint Graph Learning | Sindhura Kommu, Yizhi Wang, Yue Wang, Xuan Wang | 2024-07-25 | Abstract
Inferring gene regulatory networks (GRNs) from
single-cell RNA sequencing (scRNA-seq) data is
a complex challenge that requires capturing the
intricate relationships between genes and their
regulatory interactions. In this study, we tackle
this challenge by leveraging the single-cell BERT-
based pre-trained transformer model (scBERT),
trained on extensive unlabeled scRNA-seq data,
to augment structured biological knowledge from
existing GRNs. We introduce a novel joint graph
learning approach scTransNet that combines the
rich contextual representations learned by pre-
trained single-cell language models with the struc-
tured knowledge encoded in GRNs using graph
neural networks (GNNs). By integrating these
two modalities, our approach effectively reasons
over both the gene expression level constraints
provided by the scRNA-seq data and the struc-
tured biological knowledge inherent in GRNs.
We evaluate scTransNet on human cell bench-
mark datasets from the BEELINE study with cell
type-specific ground truth networks. The results
demonstrate superior performance over current
state-of-the-art baselines, offering a deeper under-
standing of cellular regulatory mechanisms.
1. | Introduction
Single-cell RNA sequencing (scRNA-seq) has transformed
the exploration of gene expression patterns at the individual
cell level (Jovic et al., 2022), offering an unprecedented op-
portunity to unravel the intricate regulatory mechanisms gov-
erning cellular identity and function (Pratapa et al., 2020).
1Department of Computer Science, Virginia Polytechnic In-
stitute and State University, Blacksburg, V A, United States
2Department of Electrical and Computer Engineering, Vir-
ginia Polytechnic Institute and State University, Arlington, V A,
United States. Correspondence to: Sindhura Kommu <sind-
[email protected] >, Yizhi Wang <[email protected] >, Yue Wang <yue-
[email protected] >, Xuan Wang <[email protected] >.
ICML 2024 AI for Science workshop , Vienna, Austria. PMLR 235,
2024. Copyright 2024 by the author(s).One such promising application is the inference of gene
regulatory networks (GRNs) which represent the complex
interplay between transcription factors (TFs) and their down-
stream target genes (Akers & Murali, 2021; Cramer, 2019).
A precise understanding of GRNs is crucial for understand-
ing cellular processes, molecular functions, and ultimately,
developing effective therapeutic interventions (Biswas et al.,
2021).
However, inferring GRNs from scRNA-seq data is challeng-
ing due to cell heterogeneity (Wagner et al., 2016), cell cycle
effects (Buettner et al., 2015), and high sparsity caused by
dropout events (Kharchenko et al., 2014), which can impact
accuracy and robustness. Additionally, the availability of
labeled scRNA-seq data corresponding to a GRN is limited,
making it challenging to train models from scratch. Tra-
ditional unsupervised or self-supervised models, while not
reliant on label information, often struggle to effectively
handle the noise, dropouts, high sparsity, and high dimen-
sionality characteristics of scRNA-seq data (Moerman et al.,
2019; Matsumoto et al., 2017; Zeng et al., 2023). Super-
vised methods are also proposed for GRN reconstruction
(Zhao et al., 2022; Shu et al., 2022; KC et al., 2019; Chen &
Liu, 2022a) but struggle to handle batch effects and fail to
leverage latent gene-gene interaction information effectively
limiting their generalization capabilities.
Recent advancements in large language models (LLMs) and
the pre-training followed by fine-tuning paradigm (Devlin
et al., 2019; OpenAI, 2023) have significantly contributed to
the development of transformer-based architectures tailored
for scRNA-seq data analysis (Yang et al., 2022; Cui et al.,
2024; Chen et al., 2023; Theodoris et al., 2023). These mod-
els effectively leverage vast amounts of unlabeled scRNA-
seq data to learn contextual representations and capture
intricate latent interactions between genes. To address the
limitations of the current methods, we effectively leverage
one of these large-scale pre-trained transformer models,
namely scBERT (Yang et al., 2022), which has been pre-
trained on large-scale unlabelled scRNA-seq data to learn
domain-irrelevant gene expression patterns and interactions
from the whole genome expression. By fine-tuning scBERT
on user specific scRNA-seq datasets, we can mitigate batch
effects and capture latent gene-gene interactions for down-
1arXiv:2407.18181v1 [cs.LG] 25 Jul 2024
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
stream tasks.
We propose an innovative knowledge-aware supervised
GRN inference framework, scTransNet (see Figure 1),
which integrates pre-trained single-cell language models
with structured knowledge of GRNs. Our approach com-
bines gene representations learned from scBERT with graph
representations derived from the corresponding GRNs, cre-
ating a unified context-aware and knowledge-aware repre-
sentation (Feng et al., 2020). This joint learning approach
enables us to surpass the accuracy of current state-of-the-art
methods in supervised GRN inference. By harnessing the
power of pre-trained transformer models and incorporat-
ing biological knowledge from diverse data sources, such
as gene expression data and gene regulatory networks, our
approach paves the way for more precise and robust GRN
inference. Ultimately, this methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. | Section not found | Related Work
Several | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. Related Work
Several | methods are also proposed for GRN reconstruction
(Zhao et al., 2022; Shu et al., 2022; KC et al., 2019; Chen &
Liu, 2022a) but struggle to handle batch effects and fail to
leverage latent gene-gene interaction information effectively
limiting their generalization capabilities.
Recent advancements in large language models (LLMs) and
the pre-training followed by fine-tuning paradigm (Devlin
et al., 2019; OpenAI, 2023) have significantly contributed to
the development of transformer-based architectures tailored
for scRNA-seq data analysis (Yang et al., 2022; Cui et al.,
2024; Chen et al., 2023; Theodoris et al., 2023). These mod-
els effectively leverage vast amounts of unlabeled scRNA-
seq data to learn contextual representations and capture
intricate latent interactions between genes. To address the
limitations of the current methods, we effectively leverage
one of these large-scale pre-trained transformer models,
namely scBERT (Yang et al., 2022), which has been pre-
trained on large-scale unlabelled scRNA-seq data to learn
domain-irrelevant gene expression patterns and interactions
from the whole genome expression. By fine-tuning scBERT
on user specific scRNA-seq datasets, we can mitigate batch
effects and capture latent gene-gene interactions for down-
1arXiv:2407.18181v1 [cs.LG] 25 Jul 2024
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
stream tasks.
We propose an innovative knowledge-aware supervised
GRN inference framework, scTransNet (see Figure 1),
which integrates pre-trained single-cell language models
with structured knowledge of GRNs. Our approach com-
bines gene representations learned from scBERT with graph
representations derived from the corresponding GRNs, cre-
ating a unified context-aware and knowledge-aware repre-
sentation (Feng et al., 2020). This joint learning approach
enables us to surpass the accuracy of current state-of-the-art
methods in supervised GRN inference. By harnessing the
power of pre-trained transformer models and incorporat-
ing biological knowledge from diverse data sources, such
as gene expression data and gene regulatory networks, our
approach paves the way for more precise and robust GRN
inference. Ultimately, this methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. Related Work
Several methods have been developed to infer GRNs from
scRNA-seq data, broadly categorized into unsupervised and
supervised methods.
Unsupervised methods primarily include information
theory-based, model-based, and machine learning-based
approaches. Information theory-based methods, such as
mutual information (MI) (Margolin et al., 2006), Pearson
correlation coefficient (PCC) (Salleh et al., 2015; Raza &
Jaiswal, 2013), and partial information decomposition and
context (PIDC) (Chan et al., 2017), conduct correlation anal-
yses under the assumption that the strength of the correlation
between genes is is positively correlated with the likelihood
of regulation between them. Model-based approaches, such
as SCODE (Matsumoto et al., 2017), involve fitting gene ex-
pression profiles to models that describe gene relationships,
which are then used to reconstruct GRNs (Shu et al., 2021;
Tsai et al., 2020).
Machine learning-based unsupervised methods, like GE-
NIE3 (Huynh-Thu et al., 2010) and GRNBoost2 (Moerman
et al., 2019), utilize tree-based algorithms to infer GRNs.
These methods are integrated into tools like SCENIC (Aibar
et al., 2017; Van de Sande et al., 2020), employing tree rules
to learn regulatory relationships by iteratively excluding
one gene at a time to determine its associations with other
genes. Despite not requiring labeled data, these unsuper-
vised methods often struggle with the noise, dropouts, high
sparsity, and high dimensionality typical of scRNA-seq data.
Additionally, the computational expense and scalability is-
sues of these tree-based methods, due to the necessity of
segmenting input data and iteratively establishing multiple
models, present further challenges for large datasets.Supervised methods , including DGRNS (Zhao et al., 2022),
convolutional neural network for co-expression (CNNC)
(Yuan & Bar-Joseph, 2019), and DeepDRIM (Chen et al.,
2021), have been developed to address the increasing scale
and inherent complexity of scRNA-seq data. Compared
with unsupervised learning, supervised models are capable
of detecting much more subtle differences between positive
and negative pairs (Yuan & Bar-Joseph, 2019).
DGRNS (Zhao et al., 2022) combines recurrent neural net-
works (RNNs) for extracting temporal features and convolu-
tional neural networks (CNNs) for extracting spatial features
to infer GRNs. CNNC (Yuan & Bar-Joseph, 2019) converts
the identification of gene regulation into an image classifi-
cation task by transforming the expression values of gene
pairs into histograms and using a CNN for classification.
However, the performance of CNNC (Yuan & Bar-Joseph,
2019) is hindered by the issue of transitive interactions. To
address this, DeepDRIM (Chen et al., 2021) considers the
information from neighboring genes and converts TF–gene
pairs and neighboring genes into histograms as additional
inputs, thereby reducing the occurrence of transitive inter-
actions to some extent. Despite their success there exist
certain limitations to the employment of CNN model-based
approaches for GRN reconstruction. First of all, the genera-
tion of image data not only gives rise to unanticipated noise
but also conceals certain original data features. Addition-
ally, this process is time-consuming, and since it changes the
format of scRNA-seq data, the predictions made by these
CNN-based computational approaches cannot be wholly
explained.
In addition to CNN-based methods, there are also other
approaches such as GNE (Kc et al., 2019) and GRN-
Transformer (Shu et al., 2022). GNE (gene network embed-
ding) (Kc et al., 2019) is a deep learning method based on
multilayer perceptron (MLP) for GRN inference applied to
microarray data. It utilizes one-hot gene ID vectors from the
gene topology to capture topological information, which is
often inefficient due to the highly sparse nature of the result-
ing one-hot feature vector. GRN-Transformer (Shu et al.,
2022) constructs a weakly supervised learning framework
based on axial transformer to infer cell-type-specific GRNs
from scRNA-seq data and generic GRNs derived from the
bulk data.
More recently, graph neural networks (GNNs) (Wu et al.,
2020), which are effective in capturing the topology of gene
networks, have been introduced into GRN prediction meth-
ods. For instance, GENELink (Chen & Liu, 2022b) treats
GRN inference as a link prediction problem and uses graph
attention networks to predict the probability of interaction
between two gene nodes. However, existing methods often
suffer from limitations such as improper handling of batch
effects, difficulty in leveraging latent gene-gene interaction
2
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
information, and making simplistic assumptions, which can
impair their generalization and robustness.
3. Approach
As shown in (Figure 1), our approach contains four parts:
BERT encoding, Attentive Pooling, GRN encoding with
GNNs and Output layer. The input scRNA-seq datasets are
processed into a cell-by-gene matrix, X∈RN×T, where
each element represents the read count of an RNA molecule.
Specifically, for scRNA-seq data, the element denotes the
RNA abundance for gene t∈ {0,1, ..., T}in cell n∈
{0,1, ..., N}. In subsequent sections, we will refer to this
matrix as the raw count matrix. Let us denote the sequence
of gene tokens as {g1, ..., g T}, where T is the total number
of genes.
scBERTEncoder
Graph Encoder
GeneCellInput (scRNA-seq)
…Cell 1 geneembeddingsCell 2 geneembeddingsCell n geneembeddingsAttention Scores Attentive Pooling
g1g2
gT…Pooled gene embeddings (Zg)
Gene regulatory Network Node FeaturesMulti-hop Message Passingg1g2g3
⍺12⍺13Node RepresentationFinal Output LayerLink Prediction
Figure 1. Overview of scTransNet framework for supervised
GRN inference with BERT Encoding Layer (top left; Section 3.1),
Attentive Pooling (top right; Section 3.2), GRN encoding with
GNNs (bottom left; Section 3.3) and Final Output layer (bottom
right; Section 3.4) . It augments the output from graph encoder
(for knowledge understanding) with scBERT encoder (for contex-
tual understanding) to infer regulatory interdependencies between
genes.
3.1. BERT Encoding Layer
(Yang et al., 2022; Cui et al., 2024; Chen et al., 2023;
Theodoris et al., 2023) show that pre-trained transformer
models have a strong understanding of gene-gene interac-
tions across cells and have achieved state-of-the-art results
on a variety of single-cell processing tasks. We use scBERT
(Yang et al., 2022) as the backbone, which is a successful
pre-trained model with the advantage of capturing long-
distance dependency as it uses Performer (Choromanski
et al., 2022) to improve the scalability of the model to toler-
ate over 16,000 gene inputs.
The scBERT model adopts the advanced paradigm of BERT
and tailors the architecture to solve single-cell data analysis.The connections of this model with BERT are given as fol-
lows. First, scBERT follows BERT’s revolutionary method
to conduct self-supervised pre-training (Devlin et al., 2019)
and uses Transformer as the model backbone (Choromanski
et al., 2022). Second, the design of embeddings in scBERT
is similar to BERT in some aspects while having unique
features to leverage gene knowledge. From this perspective,
the gene expression embedding could be viewed as the to-
ken embedding of BERT. As shuffling the columns of the
input does not change its meaning (like the extension of
BERT to understand tabular data with TaBERT (Yin et al.,
2020)), absolute positions are meaningless for gene. In-
stead gene2vec is used to produce gene embeddings, which
could be viewed as relative embeddings (Du et al., 2019)
that capture the semantic similarities between any of two
genes. Third, Transformer with global receptive field could
effectively learn global representation and long-range de-
pendency without absolute position information, achieving
excellent performance on non-sequential data (such as im-
ages, tables) (Parmar et al., 2018; Yin et al., 2020).
In spite of the gene embedding, there is also a challenge on
how to utilize the transcription level of each gene, which is
actually a single continuous variable. The gene expression
could also be considered as the occurrence of each gene that
has already been well-documented in a biological system.
Drawing from bag-of-words (Zhang et al., 2010) insight,
the conventionally used term-frequency-analysis method is
applied that discretizes the continuous expression variables
by binning, and converts them into 200-dimensional vectors,
which are then used as token embeddings for the scBERT
model.
For each token gtin a cell, we construct its input represen-
tation as:
h0
t=embgene 2vec(gt) +embexpr(gt) (1)
where embgene 2vec(gt)represents gene2vec embedding
(Du et al., 2019) of gene gtanalogous to position embedding
in BERT and embexpr(gt)represents expression embedding
of the gene expression of gtanalogous to token embedding
in BERT.
Such input representations are then fed into L successive
Transformer encoder blocks, i.e.,
hl
t=Transformer (hl−1
t), l= 1,2, ..., L, (2)
so as to generate deep, context-aware representations for
genes. The final hidden states {hL
t}T
t=1are taken as the
output of this layer (Devlin et al., 2019; Vaswani et al.,
2023).
3.2. Attentive Pooling
After extracting the BERT encodings we further utilize the
attention scores across cells from the model to select the
3
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
most representative cells for pooling of each gene represen-
tation. For each input gene token gtwe get the embeddings
for all cells denoted as {hL
t(n)}N
n=1, where N is the number
of cells.
The quadratic computational complexity of the BERT
model, with the Transformer as its foundational unit, does
not scale efficiently for long sequences. Given that the num-
ber of genes in scRNA-seq data can exceed 20,000, this lim-
itation becomes significant. To address this issue, scBERT
employs a matrix decomposition variant of the Transformer,
known as Performer (Choromanski et al., 2022), to handle
longer sequence lengths. In a regular Transformer, the dot-
product attention mechanism maps Q, K, and V , which are
the encoded representations of the input queries, keys, and
values for each unit. The bidirectional attention matrix is
formulated as follows:
Att(Q, K, V ) =D−1(QKT)V,
D=diag(QKT1L)(3)
where Q=WqX,K=WKX,V=WVXare linear
transformations of the input X; WQ,WKandWVare the
weight matrices as parameters; 1Lis the all-ones vector of
length L; and diag(.) is a diagonal matrix with the input
vector as the diagonal.
The attention matrix in Performer is described as follows:
ˆAtt(Q, K, V ) =ˆD−1(Q′((K′)TV)),
ˆD=diag(Q′((K′)T1L))(4)
where Q′=ϕ(Q),K′=ϕ(K), and the function ϕ(x)is
defined as:
ϕ(X) =c√mf(ωTX) (5)
where c is a positive constant, ωis a random feature matrix,
and m is the dimensionality of the matrix.
The attention weights can be obtained from equation 3,
modified by replacing V with V0, where V0contains one-
hot indicators for each position index. All the attention
matrices are integrated into one matrix by taking an element-
wise average across all attention matrices in multi-head
multi-layer Performers. In this average attention matrix for
each cell, A(i, j)represents how much attention from gene
i was paid to gene j. To focus on the importance of genes
to each cell n, the attention matrix is summed along the
columns into an attention-sum vector an, and its length is
equal to the number of genes. These attention scores of
genegtare obtained across cells and normalized denoted as
{an
t}N
n=1
These normalized scores are used for weighted aggrega-
tion of gene embeddings across cells. We aggregate each
cell’s gene representations together into one gene-level cellembedding such that the updated matrix is of the form
Z∈RT×d, where d is the dimension of the output gene
embedding.
Zg[t] =⊕N
i=1hL
t(n)·an
t (6)
3.3. GRN encoding with GNNs
In this module, we use raw count matrix as the features of
the genes. Subsequently, we utilize graph convolutional
network (GCN)-based interaction graph encoders to learn
gene features by leveraging the underlying structure of the
gene interaction graph.
Let us denote the prior network as G={V, E}, where V is
the set of nodes and E is the set of edges. To perform the
reasoning on this prior gene regulatory network G, our GNN
module builds on the graph attention framework (GAT)
(Velickovic et al., 2017), which induces node representations
via iterative message passing between neighbors on the
graph. In each layer of this GNN, the current representation
of the node embeddings {vl−1
1, ..., vl−1
T}is fed into the layer
to perform a round of information propagation between
nodes in the graph and yield pre-fused node embeddings for
each node:
{˜v1l, ...,˜vTl}=GNN ({vl−1
1, ..., vl−1
T})
for l = 1, ..., M(7)
Specifically, for each layer l, we update the representation
˜vtlof each node by
˜vtl=fn(X
vs∈ηvt∪{vt}αstmst) +vtl−1(8)
where ηvtrepresents the neighborhood of an arbitrary node
vt,mstdenotes the message one of its neighbors vspasses
tovt,αstis an attention weight that scales the message mst,
andfnis a 2-layer MLP. The messages mstbetween nodes
allow entity information from a node to affect the model’s
representation of its neighbors, and are computed in the
following manner:
rst=fr(˜rst,us,ut) (9)
mst=fm(v(l−1)
s,us,rst) (10)
where us,utare node type embeddings, ˜rstis a relationem-
bedding for the relation connecting vsandvt,fris a 2-
layer MLP, and fmis a linear transformation. The attention
weights αstscale the contribution of each neighbor’s mes-
sage by its importance, and are computed as follows:
qs=fq(v(l−1)
s,us) (11)
kt=fk(v(l−1)
t,ut,rst) (12)
4
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
αst=exp (γst)P
vs∈ηvt∪{vt}exp (γst), γst=q⊺
skt√
D(13)
where fqandfkare linear transformations and us,ut,rst
are defined the same as above.
3.4. Final Output Layer
In the final output layer, we concatenate the input gene
representations Zgfrom the BERT encoding layer with the
graph representation of each gene from GNN to get the final
gene embedding.
We input these final embeddings of pairwise genes i and j
into two channels with the same structure. Each channel is
composed of MLPs to further encode representations to low-
dimensional vectors which serve for downstream similarity
measurement or causal inference between genes.
4. | Experimental Setup
4.1. Benchmark scRNA-seq datasets
The performance of scTransNet is evaluated on two human
cell types using single-cell RNA-sequencing (scRNA-seq)
datasets from the BEELINE study (Pratapa et al., 2020):
human embryonic stem cells (hESC (Yuan & Bar-Joseph,
2019)) and human mature hepatocytes (hHEP (Camp et al.,
2017)). The cell-type-specific ChIP-seq ground-truth net-
works are used as a reference for these datasets. The scRNA-
seq datasets are preprocessed following the approach de-
scribed in the (Pratapa et al., 2020), focusing on inferring
interactions outgoing from transcription factors (TFs). The
most significantly varying genes are selected, including
all TFs with a corrected P-value (Bonferroni method) of
variance below 0.01. Specifically, 500 and 1000 of the
most varying genes are chosen for gene regulatory network
(GRN) inference. The scRNA-seq datasets can be accessed
from the Gene Expression Omnibus (GEO) with accession
numbers GSE81252 (hHEP) and GSE75748 (hESC). The
evaluation compares the inferred gene regulatory networks
to known ChIP-seq ground-truth networks specific to these
cell types.
4.2. Implementation and Training details
Data Preparation We utilized the benchmark networks
that containing labeled directed regulatory dependencies
between gene pairs. These dependencies were classified as
positive samples (labeled 1) if present in the network, and
negative samples (labeled 0) if absent. Due to the inherent
network density, the number of negative samples signifi-
cantly outnumbered positive samples. To address the class
imbalance, known transcription factor (TF)-gene pairs are
split into training (2/3), and test (1/3) sets. Positive training
samples were randomly selected from the known TF-genepairs. Moreover, 10% of TF-gene pairs are randomly se-
lected from training samples for validation. The remaining
positive pairs formed the positive test set. Negative samples
were generated using the following strategies: 1) Unlabeled
interactions: All unobserved TF-gene interactions outside
the labeled files were considered negative instances. 2)
Hard negative sampling: To enhance model learning during
training, we employed a uniformly random negative sam-
pling strategy within the training set. This involved creating
”hard negative samples” by pairing each positive sample
(g1, g2) with a negative sample (g1, g3), where both share
the same gene g1. This approach injects more discrimina-
tive information and accelerates training. 3) Information
leakage prevention: Negative test samples were randomly
selected from the remaining negative instances after gen-
erating the training and validation sets. This ensured no
information leakage from the test set to the training process.
The positive-to-negative sample ratio in each dataset was
adjusted to reflect the network density i.e.
Positive
Negative=NetworkDensity
1−NetworkDensity(14)
Model Training To account for the class imbalance, we
adopted two performance metrics: Area Under the Receiver
Operating Characteristic Curve (AUROC) and Area Under
the Precision-Recall Curve (AUPRC). The supervised model
was trained for 100 iterations with a learning rate of 0.003.
The Graph Neural Network (GNN) architecture comprised
two layers with hidden layer sizes of 256 and 128 units,
respectively.
Evaluation All reported | Section not found | data analysis (Yang et al., 2022; Cui et al.,
2024; Chen et al., 2023; Theodoris et al., 2023). These mod-
els effectively leverage vast amounts of unlabeled scRNA-
seq data to learn contextual representations and capture
intricate latent interactions between genes. To address the
limitations of the current methods, we effectively leverage
one of these large-scale pre-trained transformer models,
namely scBERT (Yang et al., 2022), which has been pre-
trained on large-scale unlabelled scRNA-seq data to learn
domain-irrelevant gene expression patterns and interactions
from the whole genome expression. By fine-tuning scBERT
on user specific scRNA-seq datasets, we can mitigate batch
effects and capture latent gene-gene interactions for down-
1arXiv:2407.18181v1 [cs.LG] 25 Jul 2024
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
stream tasks.
We propose an innovative knowledge-aware supervised
GRN inference framework, scTransNet (see Figure 1),
which integrates pre-trained single-cell language models
with structured knowledge of GRNs. Our approach com-
bines gene representations learned from scBERT with graph
representations derived from the corresponding GRNs, cre-
ating a unified context-aware and knowledge-aware repre-
sentation (Feng et al., 2020). This joint learning approach
enables us to surpass the accuracy of current state-of-the-art
methods in supervised GRN inference. By harnessing the
power of pre-trained transformer models and incorporat-
ing biological knowledge from diverse data sources, such
as gene expression data and gene regulatory networks, our
approach paves the way for more precise and robust GRN
inference. Ultimately, this methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. Related Work
Several methods have been developed to infer GRNs from
scRNA-seq data, broadly categorized into unsupervised and
supervised methods.
Unsupervised methods primarily include information
theory-based, model-based, and machine learning-based
approaches. Information theory-based methods, such as
mutual information (MI) (Margolin et al., 2006), Pearson
correlation coefficient (PCC) (Salleh et al., 2015; Raza &
Jaiswal, 2013), and partial information decomposition and
context (PIDC) (Chan et al., 2017), conduct correlation anal-
yses under the assumption that the strength of the correlation
between genes is is positively correlated with the likelihood
of regulation between them. Model-based approaches, such
as SCODE (Matsumoto et al., 2017), involve fitting gene ex-
pression profiles to models that describe gene relationships,
which are then used to reconstruct GRNs (Shu et al., 2021;
Tsai et al., 2020).
Machine learning-based unsupervised methods, like GE-
NIE3 (Huynh-Thu et al., 2010) and GRNBoost2 (Moerman
et al., 2019), utilize tree-based algorithms to infer GRNs.
These methods are integrated into tools like SCENIC (Aibar
et al., 2017; Van de Sande et al., 2020), employing tree rules
to learn regulatory relationships by iteratively excluding
one gene at a time to determine its associations with other
genes. Despite not requiring labeled data, these unsuper-
vised methods often struggle with the noise, dropouts, high
sparsity, and high dimensionality typical of scRNA-seq data.
Additionally, the computational expense and scalability is-
sues of these tree-based methods, due to the necessity of
segmenting input data and iteratively establishing multiple
models, present further challenges for large datasets.Supervised methods , including DGRNS (Zhao et al., 2022),
convolutional neural network for co-expression (CNNC)
(Yuan & Bar-Joseph, 2019), and DeepDRIM (Chen et al.,
2021), have been developed to address the increasing scale
and inherent complexity of scRNA-seq data. Compared
with unsupervised learning, supervised models are capable
of detecting much more subtle differences between positive
and negative pairs (Yuan & Bar-Joseph, 2019).
DGRNS (Zhao et al., 2022) combines recurrent neural net-
works (RNNs) for extracting temporal features and convolu-
tional neural networks (CNNs) for extracting spatial features
to infer GRNs. CNNC (Yuan & Bar-Joseph, 2019) converts
the identification of gene regulation into an image classifi-
cation task by transforming the expression values of gene
pairs into histograms and using a CNN for classification.
However, the performance of CNNC (Yuan & Bar-Joseph,
2019) is hindered by the issue of transitive interactions. To
address this, DeepDRIM (Chen et al., 2021) considers the
information from neighboring genes and converts TF–gene
pairs and neighboring genes into histograms as additional
inputs, thereby reducing the occurrence of transitive inter-
actions to some extent. Despite their success there exist
certain limitations to the employment of CNN model-based
approaches for GRN reconstruction. First of all, the genera-
tion of image data not only gives rise to unanticipated noise
but also conceals certain original data features. Addition-
ally, this process is time-consuming, and since it changes the
format of scRNA-seq data, the predictions made by these
CNN-based computational approaches cannot be wholly
explained.
In addition to CNN-based methods, there are also other
approaches such as GNE (Kc et al., 2019) and GRN-
Transformer (Shu et al., 2022). GNE (gene network embed-
ding) (Kc et al., 2019) is a deep learning method based on
multilayer perceptron (MLP) for GRN inference applied to
microarray data. It utilizes one-hot gene ID vectors from the
gene topology to capture topological information, which is
often inefficient due to the highly sparse nature of the result-
ing one-hot feature vector. GRN-Transformer (Shu et al.,
2022) constructs a weakly supervised learning framework
based on axial transformer to infer cell-type-specific GRNs
from scRNA-seq data and generic GRNs derived from the
bulk data.
More recently, graph neural networks (GNNs) (Wu et al.,
2020), which are effective in capturing the topology of gene
networks, have been introduced into GRN prediction meth-
ods. For instance, GENELink (Chen & Liu, 2022b) treats
GRN inference as a link prediction problem and uses graph
attention networks to predict the probability of interaction
between two gene nodes. However, existing methods often
suffer from limitations such as improper handling of batch
effects, difficulty in leveraging latent gene-gene interaction
2
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
information, and making simplistic assumptions, which can
impair their generalization and robustness.
3. Approach
As shown in (Figure 1), our approach contains four parts:
BERT encoding, Attentive Pooling, GRN encoding with
GNNs and Output layer. The input scRNA-seq datasets are
processed into a cell-by-gene matrix, X∈RN×T, where
each element represents the read count of an RNA molecule.
Specifically, for scRNA-seq data, the element denotes the
RNA abundance for gene t∈ {0,1, ..., T}in cell n∈
{0,1, ..., N}. In subsequent sections, we will refer to this
matrix as the raw count matrix. Let us denote the sequence
of gene tokens as {g1, ..., g T}, where T is the total number
of genes.
scBERTEncoder
Graph Encoder
GeneCellInput (scRNA-seq)
…Cell 1 geneembeddingsCell 2 geneembeddingsCell n geneembeddingsAttention Scores Attentive Pooling
g1g2
gT…Pooled gene embeddings (Zg)
Gene regulatory Network Node FeaturesMulti-hop Message Passingg1g2g3
⍺12⍺13Node RepresentationFinal Output LayerLink Prediction
Figure 1. Overview of scTransNet framework for supervised
GRN inference with BERT Encoding Layer (top left; Section 3.1),
Attentive Pooling (top right; Section 3.2), GRN encoding with
GNNs (bottom left; Section 3.3) and Final Output layer (bottom
right; Section 3.4) . It augments the output from graph encoder
(for knowledge understanding) with scBERT encoder (for contex-
tual understanding) to infer regulatory interdependencies between
genes.
3.1. BERT Encoding Layer
(Yang et al., 2022; Cui et al., 2024; Chen et al., 2023;
Theodoris et al., 2023) show that pre-trained transformer
models have a strong understanding of gene-gene interac-
tions across cells and have achieved state-of-the-art | results
demonstrate superior performance over current
state-of-the-art baselines, offering a deeper under-
standing of cellular regulatory mechanisms.
1. Introduction
Single-cell RNA sequencing (scRNA-seq) has transformed
the exploration of gene expression patterns at the individual
cell level (Jovic et al., 2022), offering an unprecedented op-
portunity to unravel the intricate regulatory mechanisms gov-
erning cellular identity and function (Pratapa et al., 2020).
1Department of Computer Science, Virginia Polytechnic In-
stitute and State University, Blacksburg, V A, United States
2Department of Electrical and Computer Engineering, Vir-
ginia Polytechnic Institute and State University, Arlington, V A,
United States. Correspondence to: Sindhura Kommu <sind-
[email protected] >, Yizhi Wang <[email protected] >, Yue Wang <yue-
[email protected] >, Xuan Wang <[email protected] >.
ICML 2024 AI for Science workshop , Vienna, Austria. PMLR 235,
2024. Copyright 2024 by the author(s).One such promising application is the inference of gene
regulatory networks (GRNs) which represent the complex
interplay between transcription factors (TFs) and their down-
stream target genes (Akers & Murali, 2021; Cramer, 2019).
A precise understanding of GRNs is crucial for understand-
ing cellular processes, molecular functions, and ultimately,
developing effective therapeutic interventions (Biswas et al.,
2021).
However, inferring GRNs from scRNA-seq data is challeng-
ing due to cell heterogeneity (Wagner et al., 2016), cell cycle
effects (Buettner et al., 2015), and high sparsity caused by
dropout events (Kharchenko et al., 2014), which can impact
accuracy and robustness. Additionally, the availability of
labeled scRNA-seq data corresponding to a GRN is limited,
making it challenging to train models from scratch. Tra-
ditional unsupervised or self-supervised models, while not
reliant on label information, often struggle to effectively
handle the noise, dropouts, high sparsity, and high dimen-
sionality characteristics of scRNA-seq data (Moerman et al.,
2019; Matsumoto et al., 2017; Zeng et al., 2023). Super-
vised methods are also proposed for GRN reconstruction
(Zhao et al., 2022; Shu et al., 2022; KC et al., 2019; Chen &
Liu, 2022a) but struggle to handle batch effects and fail to
leverage latent gene-gene interaction information effectively
limiting their generalization capabilities.
Recent advancements in large language models (LLMs) and
the pre-training followed by fine-tuning paradigm (Devlin
et al., 2019; OpenAI, 2023) have significantly contributed to
the development of transformer-based architectures tailored
for scRNA-seq data analysis (Yang et al., 2022; Cui et al.,
2024; Chen et al., 2023; Theodoris et al., 2023). These mod-
els effectively leverage vast amounts of unlabeled scRNA-
seq data to learn contextual representations and capture
intricate latent interactions between genes. To address the
limitations of the current methods, we effectively leverage
one of these large-scale pre-trained transformer models,
namely scBERT (Yang et al., 2022), which has been pre-
trained on large-scale unlabelled scRNA-seq data to learn
domain-irrelevant gene expression patterns and interactions
from the whole genome expression. By fine-tuning scBERT
on user specific scRNA-seq datasets, we can mitigate batch
effects and capture latent gene-gene interactions for down-
1arXiv:2407.18181v1 [cs.LG] 25 Jul 2024
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
stream tasks.
We propose an innovative knowledge-aware supervised
GRN inference framework, scTransNet (see Figure 1),
which integrates pre-trained single-cell language models
with structured knowledge of GRNs. Our approach com-
bines gene representations learned from scBERT with graph
representations derived from the corresponding GRNs, cre-
ating a unified context-aware and knowledge-aware repre-
sentation (Feng et al., 2020). This joint learning approach
enables us to surpass the accuracy of current state-of-the-art
methods in supervised GRN inference. By harnessing the
power of pre-trained transformer models and incorporat-
ing biological knowledge from diverse data sources, such
as gene expression data and gene regulatory networks, our
approach paves the way for more precise and robust GRN
inference. Ultimately, this methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. Related Work
Several methods have been developed to infer GRNs from
scRNA-seq data, broadly categorized into unsupervised and
supervised methods.
Unsupervised methods primarily include information
theory-based, model-based, and machine learning-based
approaches. Information theory-based methods, such as
mutual information (MI) (Margolin et al., 2006), Pearson
correlation coefficient (PCC) (Salleh et al., 2015; Raza &
Jaiswal, 2013), and partial information decomposition and
context (PIDC) (Chan et al., 2017), conduct correlation anal-
yses under the assumption that the strength of the correlation
between genes is is positively correlated with the likelihood
of regulation between them. Model-based approaches, such
as SCODE (Matsumoto et al., 2017), involve fitting gene ex-
pression profiles to models that describe gene relationships,
which are then used to reconstruct GRNs (Shu et al., 2021;
Tsai et al., 2020).
Machine learning-based unsupervised methods, like GE-
NIE3 (Huynh-Thu et al., 2010) and GRNBoost2 (Moerman
et al., 2019), utilize tree-based algorithms to infer GRNs.
These methods are integrated into tools like SCENIC (Aibar
et al., 2017; Van de Sande et al., 2020), employing tree rules
to learn regulatory relationships by iteratively excluding
one gene at a time to determine its associations with other
genes. Despite not requiring labeled data, these unsuper-
vised methods often struggle with the noise, dropouts, high
sparsity, and high dimensionality typical of scRNA-seq data.
Additionally, the computational expense and scalability is-
sues of these tree-based methods, due to the necessity of
segmenting input data and iteratively establishing multiple
models, present further challenges for large datasets.Supervised methods , including DGRNS (Zhao et al., 2022),
convolutional neural network for co-expression (CNNC)
(Yuan & Bar-Joseph, 2019), and DeepDRIM (Chen et al.,
2021), have been developed to address the increasing scale
and inherent complexity of scRNA-seq data. Compared
with unsupervised learning, supervised models are capable
of detecting much more subtle differences between positive
and negative pairs (Yuan & Bar-Joseph, 2019).
DGRNS (Zhao et al., 2022) combines recurrent neural net-
works (RNNs) for extracting temporal features and convolu-
tional neural networks (CNNs) for extracting spatial features
to infer GRNs. CNNC (Yuan & Bar-Joseph, 2019) converts
the identification of gene regulation into an image classifi-
cation task by transforming the expression values of gene
pairs into histograms and using a CNN for classification.
However, the performance of CNNC (Yuan & Bar-Joseph,
2019) is hindered by the issue of transitive interactions. To
address this, DeepDRIM (Chen et al., 2021) considers the
information from neighboring genes and converts TF–gene
pairs and neighboring genes into histograms as additional
inputs, thereby reducing the occurrence of transitive inter-
actions to some extent. Despite their success there exist
certain limitations to the employment of CNN model-based
approaches for GRN reconstruction. First of all, the genera-
tion of image data not only gives rise to unanticipated noise
but also conceals certain original data features. Addition-
ally, this process is time-consuming, and since it changes the
format of scRNA-seq data, the predictions made by these
CNN-based computational approaches cannot be wholly
explained.
In addition to CNN-based methods, there are also other
approaches such as GNE (Kc et al., 2019) and GRN-
Transformer (Shu et al., 2022). GNE (gene network embed-
ding) (Kc et al., 2019) is a deep learning method based on
multilayer perceptron (MLP) for GRN inference applied to
microarray data. It utilizes one-hot gene ID vectors from the
gene topology to capture topological information, which is
often inefficient due to the highly sparse nature of the result-
ing one-hot feature vector. GRN-Transformer (Shu et al.,
2022) constructs a weakly supervised learning framework
based on axial transformer to infer cell-type-specific GRNs
from scRNA-seq data and generic GRNs derived from the
bulk data.
More recently, graph neural networks (GNNs) (Wu et al.,
2020), which are effective in capturing the topology of gene
networks, have been introduced into GRN prediction meth-
ods. For instance, GENELink (Chen & Liu, 2022b) treats
GRN inference as a link prediction problem and uses graph
attention networks to predict the probability of interaction
between two gene nodes. However, existing methods often
suffer from limitations such as improper handling of batch
effects, difficulty in leveraging latent gene-gene interaction
2
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
information, and making simplistic assumptions, which can
impair their generalization and robustness.
3. Approach
As shown in (Figure 1), our approach contains four parts:
BERT encoding, Attentive Pooling, GRN encoding with
GNNs and Output layer. The input scRNA-seq datasets are
processed into a cell-by-gene matrix, X∈RN×T, where
each element represents the read count of an RNA molecule.
Specifically, for scRNA-seq data, the element denotes the
RNA abundance for gene t∈ {0,1, ..., T}in cell n∈
{0,1, ..., N}. In subsequent sections, we will refer to this
matrix as the raw count matrix. Let us denote the sequence
of gene tokens as {g1, ..., g T}, where T is the total number
of genes.
scBERTEncoder
Graph Encoder
GeneCellInput (scRNA-seq)
…Cell 1 geneembeddingsCell 2 geneembeddingsCell n geneembeddingsAttention Scores Attentive Pooling
g1g2
gT…Pooled gene embeddings (Zg)
Gene regulatory Network Node FeaturesMulti-hop Message Passingg1g2g3
⍺12⍺13Node RepresentationFinal Output LayerLink Prediction
Figure 1. Overview of scTransNet framework for supervised
GRN inference with BERT Encoding Layer (top left; Section 3.1),
Attentive Pooling (top right; Section 3.2), GRN encoding with
GNNs (bottom left; Section 3.3) and Final Output layer (bottom
right; Section 3.4) . It augments the output from graph encoder
(for knowledge understanding) with scBERT encoder (for contex-
tual understanding) to infer regulatory interdependencies between
genes.
3.1. BERT Encoding Layer
(Yang et al., 2022; Cui et al., 2024; Chen et al., 2023;
Theodoris et al., 2023) show that pre-trained transformer
models have a strong understanding of gene-gene interac-
tions across cells and have achieved state-of-the-art results
on a variety of single-cell processing tasks. We use scBERT
(Yang et al., 2022) as the backbone, which is a successful
pre-trained model with the advantage of capturing long-
distance dependency as it uses Performer (Choromanski
et al., 2022) to improve the scalability of the model to toler-
ate over 16,000 gene inputs.
The scBERT model adopts the advanced paradigm of BERT
and tailors the architecture to solve single-cell data analysis.The connections of this model with BERT are given as fol-
lows. First, scBERT follows BERT’s revolutionary method
to conduct self-supervised pre-training (Devlin et al., 2019)
and uses Transformer as the model backbone (Choromanski
et al., 2022). Second, the design of embeddings in scBERT
is similar to BERT in some aspects while having unique
features to leverage gene knowledge. From this perspective,
the gene expression embedding could be viewed as the to-
ken embedding of BERT. As shuffling the columns of the
input does not change its meaning (like the extension of
BERT to understand tabular data with TaBERT (Yin et al.,
2020)), absolute positions are meaningless for gene. In-
stead gene2vec is used to produce gene embeddings, which
could be viewed as relative embeddings (Du et al., 2019)
that capture the semantic similarities between any of two
genes. Third, Transformer with global receptive field could
effectively learn global representation and long-range de-
pendency without absolute position information, achieving
excellent performance on non-sequential data (such as im-
ages, tables) (Parmar et al., 2018; Yin et al., 2020).
In spite of the gene embedding, there is also a challenge on
how to utilize the transcription level of each gene, which is
actually a single continuous variable. The gene expression
could also be considered as the occurrence of each gene that
has already been well-documented in a biological system.
Drawing from bag-of-words (Zhang et al., 2010) insight,
the conventionally used term-frequency-analysis method is
applied that discretizes the continuous expression variables
by binning, and converts them into 200-dimensional vectors,
which are then used as token embeddings for the scBERT
model.
For each token gtin a cell, we construct its input represen-
tation as:
h0
t=embgene 2vec(gt) +embexpr(gt) (1)
where embgene 2vec(gt)represents gene2vec embedding
(Du et al., 2019) of gene gtanalogous to position embedding
in BERT and embexpr(gt)represents expression embedding
of the gene expression of gtanalogous to token embedding
in BERT.
Such input representations are then fed into L successive
Transformer encoder blocks, i.e.,
hl
t=Transformer (hl−1
t), l= 1,2, ..., L, (2)
so as to generate deep, context-aware representations for
genes. The final hidden states {hL
t}T
t=1are taken as the
output of this layer (Devlin et al., 2019; Vaswani et al.,
2023).
3.2. Attentive Pooling
After extracting the BERT encodings we further utilize the
attention scores across cells from the model to select the
3
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
most representative cells for pooling of each gene represen-
tation. For each input gene token gtwe get the embeddings
for all cells denoted as {hL
t(n)}N
n=1, where N is the number
of cells.
The quadratic computational complexity of the BERT
model, with the Transformer as its foundational unit, does
not scale efficiently for long sequences. Given that the num-
ber of genes in scRNA-seq data can exceed 20,000, this lim-
itation becomes significant. To address this issue, scBERT
employs a matrix decomposition variant of the Transformer,
known as Performer (Choromanski et al., 2022), to handle
longer sequence lengths. In a regular Transformer, the dot-
product attention mechanism maps Q, K, and V , which are
the encoded representations of the input queries, keys, and
values for each unit. The bidirectional attention matrix is
formulated as follows:
Att(Q, K, V ) =D−1(QKT)V,
D=diag(QKT1L)(3)
where Q=WqX,K=WKX,V=WVXare linear
transformations of the input X; WQ,WKandWVare the
weight matrices as parameters; 1Lis the all-ones vector of
length L; and diag(.) is a diagonal matrix with the input
vector as the diagonal.
The attention matrix in Performer is described as follows:
ˆAtt(Q, K, V ) =ˆD−1(Q′((K′)TV)),
ˆD=diag(Q′((K′)T1L))(4)
where Q′=ϕ(Q),K′=ϕ(K), and the function ϕ(x)is
defined as:
ϕ(X) =c√mf(ωTX) (5)
where c is a positive constant, ωis a random feature matrix,
and m is the dimensionality of the matrix.
The attention weights can be obtained from equation 3,
modified by replacing V with V0, where V0contains one-
hot indicators for each position index. All the attention
matrices are integrated into one matrix by taking an element-
wise average across all attention matrices in multi-head
multi-layer Performers. In this average attention matrix for
each cell, A(i, j)represents how much attention from gene
i was paid to gene j. To focus on the importance of genes
to each cell n, the attention matrix is summed along the
columns into an attention-sum vector an, and its length is
equal to the number of genes. These attention scores of
genegtare obtained across cells and normalized denoted as
{an
t}N
n=1
These normalized scores are used for weighted aggrega-
tion of gene embeddings across cells. We aggregate each
cell’s gene representations together into one gene-level cellembedding such that the updated matrix is of the form
Z∈RT×d, where d is the dimension of the output gene
embedding.
Zg[t] =⊕N
i=1hL
t(n)·an
t (6)
3.3. GRN encoding with GNNs
In this module, we use raw count matrix as the features of
the genes. Subsequently, we utilize graph convolutional
network (GCN)-based interaction graph encoders to learn
gene features by leveraging the underlying structure of the
gene interaction graph.
Let us denote the prior network as G={V, E}, where V is
the set of nodes and E is the set of edges. To perform the
reasoning on this prior gene regulatory network G, our GNN
module builds on the graph attention framework (GAT)
(Velickovic et al., 2017), which induces node representations
via iterative message passing between neighbors on the
graph. In each layer of this GNN, the current representation
of the node embeddings {vl−1
1, ..., vl−1
T}is fed into the layer
to perform a round of information propagation between
nodes in the graph and yield pre-fused node embeddings for
each node:
{˜v1l, ...,˜vTl}=GNN ({vl−1
1, ..., vl−1
T})
for l = 1, ..., M(7)
Specifically, for each layer l, we update the representation
˜vtlof each node by
˜vtl=fn(X
vs∈ηvt∪{vt}αstmst) +vtl−1(8)
where ηvtrepresents the neighborhood of an arbitrary node
vt,mstdenotes the message one of its neighbors vspasses
tovt,αstis an attention weight that scales the message mst,
andfnis a 2-layer MLP. The messages mstbetween nodes
allow entity information from a node to affect the model’s
representation of its neighbors, and are computed in the
following manner:
rst=fr(˜rst,us,ut) (9)
mst=fm(v(l−1)
s,us,rst) (10)
where us,utare node type embeddings, ˜rstis a relationem-
bedding for the relation connecting vsandvt,fris a 2-
layer MLP, and fmis a linear transformation. The attention
weights αstscale the contribution of each neighbor’s mes-
sage by its importance, and are computed as follows:
qs=fq(v(l−1)
s,us) (11)
kt=fk(v(l−1)
t,ut,rst) (12)
4
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
αst=exp (γst)P
vs∈ηvt∪{vt}exp (γst), γst=q⊺
skt√
D(13)
where fqandfkare linear transformations and us,ut,rst
are defined the same as above.
3.4. Final Output Layer
In the final output layer, we concatenate the input gene
representations Zgfrom the BERT encoding layer with the
graph representation of each gene from GNN to get the final
gene embedding.
We input these final embeddings of pairwise genes i and j
into two channels with the same structure. Each channel is
composed of MLPs to further encode representations to low-
dimensional vectors which serve for downstream similarity
measurement or causal inference between genes.
4. Experimental Setup
4.1. Benchmark scRNA-seq datasets
The performance of scTransNet is evaluated on two human
cell types using single-cell RNA-sequencing (scRNA-seq)
datasets from the BEELINE study (Pratapa et al., 2020):
human embryonic stem cells (hESC (Yuan & Bar-Joseph,
2019)) and human mature hepatocytes (hHEP (Camp et al.,
2017)). The cell-type-specific ChIP-seq ground-truth net-
works are used as a reference for these datasets. The scRNA-
seq datasets are preprocessed following the approach de-
scribed in the (Pratapa et al., 2020), focusing on inferring
interactions outgoing from transcription factors (TFs). The
most significantly varying genes are selected, including
all TFs with a corrected P-value (Bonferroni method) of
variance below 0.01. Specifically, 500 and 1000 of the
most varying genes are chosen for gene regulatory network
(GRN) inference. The scRNA-seq datasets can be accessed
from the Gene Expression Omnibus (GEO) with accession
numbers GSE81252 (hHEP) and GSE75748 (hESC). The
evaluation compares the inferred gene regulatory networks
to known ChIP-seq ground-truth networks specific to these
cell types.
4.2. Implementation and Training details
Data Preparation We utilized the benchmark networks
that containing labeled directed regulatory dependencies
between gene pairs. These dependencies were classified as
positive samples (labeled 1) if present in the network, and
negative samples (labeled 0) if absent. Due to the inherent
network density, the number of negative samples signifi-
cantly outnumbered positive samples. To address the class
imbalance, known transcription factor (TF)-gene pairs are
split into training (2/3), and test (1/3) sets. Positive training
samples were randomly selected from the known TF-genepairs. Moreover, 10% of TF-gene pairs are randomly se-
lected from training samples for validation. The remaining
positive pairs formed the positive test set. Negative samples
were generated using the following strategies: 1) Unlabeled
interactions: All unobserved TF-gene interactions outside
the labeled files were considered negative instances. 2)
Hard negative sampling: To enhance model learning during
training, we employed a uniformly random negative sam-
pling strategy within the training set. This involved creating
”hard negative samples” by pairing each positive sample
(g1, g2) with a negative sample (g1, g3), where both share
the same gene g1. This approach injects more discrimina-
tive information and accelerates training. 3) Information
leakage prevention: Negative test samples were randomly
selected from the remaining negative instances after gen-
erating the training and validation sets. This ensured no
information leakage from the test set to the training process.
The positive-to-negative sample ratio in each dataset was
adjusted to reflect the network density i.e.
Positive
Negative=NetworkDensity
1−NetworkDensity(14)
Model Training To account for the class imbalance, we
adopted two performance metrics: Area Under the Receiver
Operating Characteristic Curve (AUROC) and Area Under
the Precision-Recall Curve (AUPRC). The supervised model
was trained for 100 iterations with a learning rate of 0.003.
The Graph Neural Network (GNN) architecture comprised
two layers with hidden layer sizes of 256 and 128 units,
respectively.
Evaluation All reported results are based solely on predic-
tions from the held-out test set. To ensure a fair comparison,
identical training and validation sets were utilized for all
evaluated supervised methods. This approach eliminates
potential bias introduced by different data splits.
4.3. Baseline Methods
To assess the effectiveness of our model in predicting GRNs,
we compare our model scTransNet against the existing base-
line methods commonly used for inferring GRNs, as fol-
lows:
•GNNLink (Mao et al., 2023) is a graph neural network
model that uses a GCN-based interaction graph encoder
to capture gene expression patterns.
• GENELink (Chen & Liu, 2022b) proposes a graph atten-
tion network (GAT) approach to infer potential GRNs by
leveraging the graph structure of gene regulatory interac-
tions.
•GNE (gene network embedding) (Kc et al., 2019) pro-
poses a multilayer perceptron (MLP) approach to encode
5
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
0.880.850.790.670.680.6270.510.470.510.50.490.50.870.820.830.80.640.520.490.490.50.470.520.54hESChHEPOursGNNLinkGENELinkGNECNNCDeepDRIMGRN-TransformerPCCMISCODEGRNBoost2GENIE3hESChHEP0.870.80.780.680.720.560.670.470.510.510.480.490.870.840.850.810.660.630.580.490.490.480.520.54TFs with most-varying 500 genesTFs with most-varying 1000 genes
hESChHEPOursGNNLinkGENELinkGNECNNCDeepDRIMGRN-TransformerPCCMISCODEGRNBoost2GENIE3hESChHEPTFs with most-varying 500 genesTFs with most-varying 1000 genesLowHigh0.60.520.480.340.250.130.150.140.150.150.150.150.780.750.690.650.460.390.350.350.350.330.380.380.590.510.50.340.270.190.160.140.150.150.140.150.780.780.70.660.490.460.530.340.340.330.370.38A)B)
Figure 2. Summary of the GRN prediction performance of scTransNet in the (A) AUROC metric (top) (B) and the AUPRC metric (bottom).
Our evaluation is conducted on two human single-cell RNA sequencing (scRNA-seq) datasets, with a cell-type-specific ground-truth
network. The scRNA-seq datasets consist of significantly varying transcription factors (TFs) and the 500 or 1000 most-varying genes.
both gene expression profiles and network topology for
predicting gene dependencies.
•CNNC (Yuan & Bar-Joseph, 2019) proposes inferring
GRNs using deep convolutional neural networks (CNNs).
•DeepDRIM (Chen et al., 2021) is a supervised deep neural
network that utilizes images representing the expression
distribution of joint gene pairs as input for binary classifi-
cation of regulatory relationships, considering both target
TF-gene pairs and potential neighbor genes.
•GRN-transformer (Shu et al., 2022) is a weakly super-
vised learning method that utilizes axial transformers to
infer cell type-specific GRNs from single-cell RNA-seq
data and generic GRNs.
•Pearson correlation coefficient (PCC) (Salleh et al., 2015;
Raza & Jaiswal, 2013) is a traditional statistical method
for measuring the linear correlation between two variables,
often used as a baseline for GRN inference.
•Mutual information (MI) (Margolin et al., 2006) is an
information-theoretic measure of the mutual dependence
between two random variables, also used as a baseline for
GRN inference.
•SCODE (Matsumoto et al., 2017) is a computational
method for inferring GRNs from single-cell RNA-seq
data using a Bayesian framework.
•GRNBoost2 (Moerman et al., 2019) is a gradient boosting-
based method for GRN inference.•GENIE3 (Huynh-Thu et al., 2010) is a random forest-
based machine learning method that constructs GRNs
based on regression weight coefficients, and won the
DREAM5 In Silico Network Challenge in 2010.
These methods represent a diverse range of approaches, in-
cluding traditional statistical methods, machine learning
techniques, and deep learning models, for inferring gene
regulatory networks from various types of data, such as
bulk and single-cell RNA-seq, as well as incorporating ad-
ditional information like network topology and chromatin
accessibility.
5. Results
5.1. Performance on benchmark datasets
The results (see Figure 2) demonstrate that scTransNet
outperforms state-of-the-art baseline methods across all
four benchmark datasets, achieving superior performance
in terms of both AUROC and AUPRC evaluation metrics.
Notably, scTransNet’s AUROC values are approximately
5.4%and7.4%higher on average compared to the second-
best methods, namely GNNLink (Mao et al., 2023) and
GENELink (Chen & Liu, 2022b), respectively. Similarly, sc-
TransNet’s AUPRC values show an impressive improvement
of approximately 7.4%and16% on average over GNNLink
and GENELink, respectively.
To gain further insights, we analyzed scTransNet’s final
gene regulatory network (GRN) predictions and compared
them with those from GENELink. Our analysis revealed
6
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Table 1. Comparison of average AUROC and AUPRC evaluation metrics on human benchmark datasets, validating the roles of the GNN
encoder, scBERT encoder, and Attentive Pooling using the cell-type-specific ChIP-seq network for our proposed method.
w/o GNN encoder w/o scBERT encoder w/o Attentive Pooling scTransNet
Dataset AUROC AUPRC AUROC AUPRC AUROC AUPRC AUROC AUPRC
hESC 0.842 0.544 0.853 0.572 0.860 0.569 0.880 0.595
hHEP 0.830 0.725 0.854 0.753 0.862 0.683 0.870 0.780
that scTransNet effectively captured all the gene regulatory
interactions predicted by GENELink. This finding suggests
that by incorporating joint learning, scTransNet does not
introduce additional noise to the predictive power of the
graph representations. Instead, it enhances the predictive
capability through the scBERT encoder in its architecture.
Figure 3 provides a visualization of a partial subgraph of
the ground truth GRN, highlighting the predictions made
by scTransNet that were not captured by GENELink, which
solely relies on graphs for predicting gene-gene interactions.
Additionally, the figure visualizes the ground truth labels
that scTransNet failed to capture. In summary, the compara-
tive analysis demonstrates that scTransNet effectively cap-
tures all the regulatory interactions predicted by GENELink
while leveraging joint learning to improve predictive perfor-
mance. The visualization illustrates the additional interac-
tions scTransNet could predict beyond GENELink, as well
as the ground truth interactions it missed, providing insights
into the strengths and limitations of the proposed method.
5.2. | Section not found | Discussion and Ablations
To evaluate the effectiveness of jointly learning from pre-
trained scRNA-seq language models (Yang et al., 2022),
which capture rich contextual representations, and Gene
Regulatory Networks (GRNs), which encode structured bi-
ological knowledge, we compare the average Area Under
the Receiver Operating Characteristic Curve (AUROC) and
Area Under the Precision-Recall Curve (AUPRC) metrics
with and without these encoders across the four human cell
type benchmark datasets (Pratapa et al., 2020). The aver-
age AUROC and AUPRC scores are calculated across both
the TFs+500 highly variable genes and TFs+1000 highly
variable genes datasets for each human cell data type (i.e,
hESC (human embryonic stem cells) and hHEP (human
mature hepatocytes)). Additionally, we validate the impor-
tance of incorporating Attentive Pooling (Section 3.2) by
contrasting the results when using average pooling of gene
embeddings across cells instead of attentive pooling. Consis-
tent parameter settings are employed across all four human
cell benchmark datasets, with Cell-type-specific ChIP-seq
network data serving as the ground truth.
Effect of Graph Neural Network Component: The re-
sults demonstrate the significant impact of incorporating
SOX2 NANOG
EOMESHNRNPD
CCNB2RBPJ
HSD17B1 ISL1OTX2
NUP35AR1D4BKIF23
FAM117B
Edge detected by scT ransNet
Edge not detected by scT ransNetTranscription Factor
Target GeneFigure 3. GRN prediction performance of scTransNet on a partial
ground truth subgraph. Solid line edges depict ground truth regu-
latory interactions correctly predicted by scTransNet but missed
by the baseline GENELink method, which relies solely on graph
representations. Notably, scTransNet effectively identified all reg-
ulatory links predicted by GENELink (not visualized). Dotted line
edges represent ground truth interactions that scTransNet failed
to capture reveal its | Section not found | Section not found | limitations of the current methods, we effectively leverage
one of these large-scale pre-trained transformer models,
namely scBERT (Yang et al., 2022), which has been pre-
trained on large-scale unlabelled scRNA-seq data to learn
domain-irrelevant gene expression patterns and interactions
from the whole genome expression. By fine-tuning scBERT
on user specific scRNA-seq datasets, we can mitigate batch
effects and capture latent gene-gene interactions for down-
1arXiv:2407.18181v1 [cs.LG] 25 Jul 2024
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
stream tasks.
We propose an innovative knowledge-aware supervised
GRN inference framework, scTransNet (see Figure 1),
which integrates pre-trained single-cell language models
with structured knowledge of GRNs. Our approach com-
bines gene representations learned from scBERT with graph
representations derived from the corresponding GRNs, cre-
ating a unified context-aware and knowledge-aware repre-
sentation (Feng et al., 2020). This joint learning approach
enables us to surpass the accuracy of current state-of-the-art
methods in supervised GRN inference. By harnessing the
power of pre-trained transformer models and incorporat-
ing biological knowledge from diverse data sources, such
as gene expression data and gene regulatory networks, our
approach paves the way for more precise and robust GRN
inference. Ultimately, this methodology offers deeper in-
sights into cellular regulatory mechanisms, advancing our
understanding of gene regulation.
2. Related Work
Several methods have been developed to infer GRNs from
scRNA-seq data, broadly categorized into unsupervised and
supervised methods.
Unsupervised methods primarily include information
theory-based, model-based, and machine learning-based
approaches. Information theory-based methods, such as
mutual information (MI) (Margolin et al., 2006), Pearson
correlation coefficient (PCC) (Salleh et al., 2015; Raza &
Jaiswal, 2013), and partial information decomposition and
context (PIDC) (Chan et al., 2017), conduct correlation anal-
yses under the assumption that the strength of the correlation
between genes is is positively correlated with the likelihood
of regulation between them. Model-based approaches, such
as SCODE (Matsumoto et al., 2017), involve fitting gene ex-
pression profiles to models that describe gene relationships,
which are then used to reconstruct GRNs (Shu et al., 2021;
Tsai et al., 2020).
Machine learning-based unsupervised methods, like GE-
NIE3 (Huynh-Thu et al., 2010) and GRNBoost2 (Moerman
et al., 2019), utilize tree-based algorithms to infer GRNs.
These methods are integrated into tools like SCENIC (Aibar
et al., 2017; Van de Sande et al., 2020), employing tree rules
to learn regulatory relationships by iteratively excluding
one gene at a time to determine its associations with other
genes. Despite not requiring labeled data, these unsuper-
vised methods often struggle with the noise, dropouts, high
sparsity, and high dimensionality typical of scRNA-seq data.
Additionally, the computational expense and scalability is-
sues of these tree-based methods, due to the necessity of
segmenting input data and iteratively establishing multiple
models, present further challenges for large datasets.Supervised methods , including DGRNS (Zhao et al., 2022),
convolutional neural network for co-expression (CNNC)
(Yuan & Bar-Joseph, 2019), and DeepDRIM (Chen et al.,
2021), have been developed to address the increasing scale
and inherent complexity of scRNA-seq data. Compared
with unsupervised learning, supervised models are capable
of detecting much more subtle differences between positive
and negative pairs (Yuan & Bar-Joseph, 2019).
DGRNS (Zhao et al., 2022) combines recurrent neural net-
works (RNNs) for extracting temporal features and convolu-
tional neural networks (CNNs) for extracting spatial features
to infer GRNs. CNNC (Yuan & Bar-Joseph, 2019) converts
the identification of gene regulation into an image classifi-
cation task by transforming the expression values of gene
pairs into histograms and using a CNN for classification.
However, the performance of CNNC (Yuan & Bar-Joseph,
2019) is hindered by the issue of transitive interactions. To
address this, DeepDRIM (Chen et al., 2021) considers the
information from neighboring genes and converts TF–gene
pairs and neighboring genes into histograms as additional
inputs, thereby reducing the occurrence of transitive inter-
actions to some extent. Despite their success there exist
certain limitations to the employment of CNN model-based
approaches for GRN reconstruction. First of all, the genera-
tion of image data not only gives rise to unanticipated noise
but also conceals certain original data features. Addition-
ally, this process is time-consuming, and since it changes the
format of scRNA-seq data, the predictions made by these
CNN-based computational approaches cannot be wholly
explained.
In addition to CNN-based methods, there are also other
approaches such as GNE (Kc et al., 2019) and GRN-
Transformer (Shu et al., 2022). GNE (gene network embed-
ding) (Kc et al., 2019) is a deep learning method based on
multilayer perceptron (MLP) for GRN inference applied to
microarray data. It utilizes one-hot gene ID vectors from the
gene topology to capture topological information, which is
often inefficient due to the highly sparse nature of the result-
ing one-hot feature vector. GRN-Transformer (Shu et al.,
2022) constructs a weakly supervised learning framework
based on axial transformer to infer cell-type-specific GRNs
from scRNA-seq data and generic GRNs derived from the
bulk data.
More recently, graph neural networks (GNNs) (Wu et al.,
2020), which are effective in capturing the topology of gene
networks, have been introduced into GRN prediction meth-
ods. For instance, GENELink (Chen & Liu, 2022b) treats
GRN inference as a link prediction problem and uses graph
attention networks to predict the probability of interaction
between two gene nodes. However, existing methods often
suffer from limitations such as improper handling of batch
effects, difficulty in leveraging latent gene-gene interaction
2
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
information, and making simplistic assumptions, which can
impair their generalization and robustness.
3. Approach
As shown in (Figure 1), our approach contains four parts:
BERT encoding, Attentive Pooling, GRN encoding with
GNNs and Output layer. The input scRNA-seq datasets are
processed into a cell-by-gene matrix, X∈RN×T, where
each element represents the read count of an RNA molecule.
Specifically, for scRNA-seq data, the element denotes the
RNA abundance for gene t∈ {0,1, ..., T}in cell n∈
{0,1, ..., N}. In subsequent sections, we will refer to this
matrix as the raw count matrix. Let us denote the sequence
of gene tokens as {g1, ..., g T}, where T is the total number
of genes.
scBERTEncoder
Graph Encoder
GeneCellInput (scRNA-seq)
…Cell 1 geneembeddingsCell 2 geneembeddingsCell n geneembeddingsAttention Scores Attentive Pooling
g1g2
gT…Pooled gene embeddings (Zg)
Gene regulatory Network Node FeaturesMulti-hop Message Passingg1g2g3
⍺12⍺13Node RepresentationFinal Output LayerLink Prediction
Figure 1. Overview of scTransNet framework for supervised
GRN inference with BERT Encoding Layer (top left; Section 3.1),
Attentive Pooling (top right; Section 3.2), GRN encoding with
GNNs (bottom left; Section 3.3) and Final Output layer (bottom
right; Section 3.4) . It augments the output from graph encoder
(for knowledge understanding) with scBERT encoder (for contex-
tual understanding) to infer regulatory interdependencies between
genes.
3.1. BERT Encoding Layer
(Yang et al., 2022; Cui et al., 2024; Chen et al., 2023;
Theodoris et al., 2023) show that pre-trained transformer
models have a strong understanding of gene-gene interac-
tions across cells and have achieved state-of-the-art results
on a variety of single-cell processing tasks. We use scBERT
(Yang et al., 2022) as the backbone, which is a successful
pre-trained model with the advantage of capturing long-
distance dependency as it uses Performer (Choromanski
et al., 2022) to improve the scalability of the model to toler-
ate over 16,000 gene inputs.
The scBERT model adopts the advanced paradigm of BERT
and tailors the architecture to solve single-cell data analysis.The connections of this model with BERT are given as fol-
lows. First, scBERT follows BERT’s revolutionary method
to conduct self-supervised pre-training (Devlin et al., 2019)
and uses Transformer as the model backbone (Choromanski
et al., 2022). Second, the design of embeddings in scBERT
is similar to BERT in some aspects while having unique
features to leverage gene knowledge. From this perspective,
the gene expression embedding could be viewed as the to-
ken embedding of BERT. As shuffling the columns of the
input does not change its meaning (like the extension of
BERT to understand tabular data with TaBERT (Yin et al.,
2020)), absolute positions are meaningless for gene. In-
stead gene2vec is used to produce gene embeddings, which
could be viewed as relative embeddings (Du et al., 2019)
that capture the semantic similarities between any of two
genes. Third, Transformer with global receptive field could
effectively learn global representation and long-range de-
pendency without absolute position information, achieving
excellent performance on non-sequential data (such as im-
ages, tables) (Parmar et al., 2018; Yin et al., 2020).
In spite of the gene embedding, there is also a challenge on
how to utilize the transcription level of each gene, which is
actually a single continuous variable. The gene expression
could also be considered as the occurrence of each gene that
has already been well-documented in a biological system.
Drawing from bag-of-words (Zhang et al., 2010) insight,
the conventionally used term-frequency-analysis method is
applied that discretizes the continuous expression variables
by binning, and converts them into 200-dimensional vectors,
which are then used as token embeddings for the scBERT
model.
For each token gtin a cell, we construct its input represen-
tation as:
h0
t=embgene 2vec(gt) +embexpr(gt) (1)
where embgene 2vec(gt)represents gene2vec embedding
(Du et al., 2019) of gene gtanalogous to position embedding
in BERT and embexpr(gt)represents expression embedding
of the gene expression of gtanalogous to token embedding
in BERT.
Such input representations are then fed into L successive
Transformer encoder blocks, i.e.,
hl
t=Transformer (hl−1
t), l= 1,2, ..., L, (2)
so as to generate deep, context-aware representations for
genes. The final hidden states {hL
t}T
t=1are taken as the
output of this layer (Devlin et al., 2019; Vaswani et al.,
2023).
3.2. Attentive Pooling
After extracting the BERT encodings we further utilize the
attention scores across cells from the model to select the
3
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
most representative cells for pooling of each gene represen-
tation. For each input gene token gtwe get the embeddings
for all cells denoted as {hL
t(n)}N
n=1, where N is the number
of cells.
The quadratic computational complexity of the BERT
model, with the Transformer as its foundational unit, does
not scale efficiently for long sequences. Given that the num-
ber of genes in scRNA-seq data can exceed 20,000, this lim-
itation becomes significant. To address this issue, scBERT
employs a matrix decomposition variant of the Transformer,
known as Performer (Choromanski et al., 2022), to handle
longer sequence lengths. In a regular Transformer, the dot-
product attention mechanism maps Q, K, and V , which are
the encoded representations of the input queries, keys, and
values for each unit. The bidirectional attention matrix is
formulated as follows:
Att(Q, K, V ) =D−1(QKT)V,
D=diag(QKT1L)(3)
where Q=WqX,K=WKX,V=WVXare linear
transformations of the input X; WQ,WKandWVare the
weight matrices as parameters; 1Lis the all-ones vector of
length L; and diag(.) is a diagonal matrix with the input
vector as the diagonal.
The attention matrix in Performer is described as follows:
ˆAtt(Q, K, V ) =ˆD−1(Q′((K′)TV)),
ˆD=diag(Q′((K′)T1L))(4)
where Q′=ϕ(Q),K′=ϕ(K), and the function ϕ(x)is
defined as:
ϕ(X) =c√mf(ωTX) (5)
where c is a positive constant, ωis a random feature matrix,
and m is the dimensionality of the matrix.
The attention weights can be obtained from equation 3,
modified by replacing V with V0, where V0contains one-
hot indicators for each position index. All the attention
matrices are integrated into one matrix by taking an element-
wise average across all attention matrices in multi-head
multi-layer Performers. In this average attention matrix for
each cell, A(i, j)represents how much attention from gene
i was paid to gene j. To focus on the importance of genes
to each cell n, the attention matrix is summed along the
columns into an attention-sum vector an, and its length is
equal to the number of genes. These attention scores of
genegtare obtained across cells and normalized denoted as
{an
t}N
n=1
These normalized scores are used for weighted aggrega-
tion of gene embeddings across cells. We aggregate each
cell’s gene representations together into one gene-level cellembedding such that the updated matrix is of the form
Z∈RT×d, where d is the dimension of the output gene
embedding.
Zg[t] =⊕N
i=1hL
t(n)·an
t (6)
3.3. GRN encoding with GNNs
In this module, we use raw count matrix as the features of
the genes. Subsequently, we utilize graph convolutional
network (GCN)-based interaction graph encoders to learn
gene features by leveraging the underlying structure of the
gene interaction graph.
Let us denote the prior network as G={V, E}, where V is
the set of nodes and E is the set of edges. To perform the
reasoning on this prior gene regulatory network G, our GNN
module builds on the graph attention framework (GAT)
(Velickovic et al., 2017), which induces node representations
via iterative message passing between neighbors on the
graph. In each layer of this GNN, the current representation
of the node embeddings {vl−1
1, ..., vl−1
T}is fed into the layer
to perform a round of information propagation between
nodes in the graph and yield pre-fused node embeddings for
each node:
{˜v1l, ...,˜vTl}=GNN ({vl−1
1, ..., vl−1
T})
for l = 1, ..., M(7)
Specifically, for each layer l, we update the representation
˜vtlof each node by
˜vtl=fn(X
vs∈ηvt∪{vt}αstmst) +vtl−1(8)
where ηvtrepresents the neighborhood of an arbitrary node
vt,mstdenotes the message one of its neighbors vspasses
tovt,αstis an attention weight that scales the message mst,
andfnis a 2-layer MLP. The messages mstbetween nodes
allow entity information from a node to affect the model’s
representation of its neighbors, and are computed in the
following manner:
rst=fr(˜rst,us,ut) (9)
mst=fm(v(l−1)
s,us,rst) (10)
where us,utare node type embeddings, ˜rstis a relationem-
bedding for the relation connecting vsandvt,fris a 2-
layer MLP, and fmis a linear transformation. The attention
weights αstscale the contribution of each neighbor’s mes-
sage by its importance, and are computed as follows:
qs=fq(v(l−1)
s,us) (11)
kt=fk(v(l−1)
t,ut,rst) (12)
4
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
αst=exp (γst)P
vs∈ηvt∪{vt}exp (γst), γst=q⊺
skt√
D(13)
where fqandfkare linear transformations and us,ut,rst
are defined the same as above.
3.4. Final Output Layer
In the final output layer, we concatenate the input gene
representations Zgfrom the BERT encoding layer with the
graph representation of each gene from GNN to get the final
gene embedding.
We input these final embeddings of pairwise genes i and j
into two channels with the same structure. Each channel is
composed of MLPs to further encode representations to low-
dimensional vectors which serve for downstream similarity
measurement or causal inference between genes.
4. Experimental Setup
4.1. Benchmark scRNA-seq datasets
The performance of scTransNet is evaluated on two human
cell types using single-cell RNA-sequencing (scRNA-seq)
datasets from the BEELINE study (Pratapa et al., 2020):
human embryonic stem cells (hESC (Yuan & Bar-Joseph,
2019)) and human mature hepatocytes (hHEP (Camp et al.,
2017)). The cell-type-specific ChIP-seq ground-truth net-
works are used as a reference for these datasets. The scRNA-
seq datasets are preprocessed following the approach de-
scribed in the (Pratapa et al., 2020), focusing on inferring
interactions outgoing from transcription factors (TFs). The
most significantly varying genes are selected, including
all TFs with a corrected P-value (Bonferroni method) of
variance below 0.01. Specifically, 500 and 1000 of the
most varying genes are chosen for gene regulatory network
(GRN) inference. The scRNA-seq datasets can be accessed
from the Gene Expression Omnibus (GEO) with accession
numbers GSE81252 (hHEP) and GSE75748 (hESC). The
evaluation compares the inferred gene regulatory networks
to known ChIP-seq ground-truth networks specific to these
cell types.
4.2. Implementation and Training details
Data Preparation We utilized the benchmark networks
that containing labeled directed regulatory dependencies
between gene pairs. These dependencies were classified as
positive samples (labeled 1) if present in the network, and
negative samples (labeled 0) if absent. Due to the inherent
network density, the number of negative samples signifi-
cantly outnumbered positive samples. To address the class
imbalance, known transcription factor (TF)-gene pairs are
split into training (2/3), and test (1/3) sets. Positive training
samples were randomly selected from the known TF-genepairs. Moreover, 10% of TF-gene pairs are randomly se-
lected from training samples for validation. The remaining
positive pairs formed the positive test set. Negative samples
were generated using the following strategies: 1) Unlabeled
interactions: All unobserved TF-gene interactions outside
the labeled files were considered negative instances. 2)
Hard negative sampling: To enhance model learning during
training, we employed a uniformly random negative sam-
pling strategy within the training set. This involved creating
”hard negative samples” by pairing each positive sample
(g1, g2) with a negative sample (g1, g3), where both share
the same gene g1. This approach injects more discrimina-
tive information and accelerates training. 3) Information
leakage prevention: Negative test samples were randomly
selected from the remaining negative instances after gen-
erating the training and validation sets. This ensured no
information leakage from the test set to the training process.
The positive-to-negative sample ratio in each dataset was
adjusted to reflect the network density i.e.
Positive
Negative=NetworkDensity
1−NetworkDensity(14)
Model Training To account for the class imbalance, we
adopted two performance metrics: Area Under the Receiver
Operating Characteristic Curve (AUROC) and Area Under
the Precision-Recall Curve (AUPRC). The supervised model
was trained for 100 iterations with a learning rate of 0.003.
The Graph Neural Network (GNN) architecture comprised
two layers with hidden layer sizes of 256 and 128 units,
respectively.
Evaluation All reported results are based solely on predic-
tions from the held-out test set. To ensure a fair comparison,
identical training and validation sets were utilized for all
evaluated supervised methods. This approach eliminates
potential bias introduced by different data splits.
4.3. Baseline Methods
To assess the effectiveness of our model in predicting GRNs,
we compare our model scTransNet against the existing base-
line methods commonly used for inferring GRNs, as fol-
lows:
•GNNLink (Mao et al., 2023) is a graph neural network
model that uses a GCN-based interaction graph encoder
to capture gene expression patterns.
• GENELink (Chen & Liu, 2022b) proposes a graph atten-
tion network (GAT) approach to infer potential GRNs by
leveraging the graph structure of gene regulatory interac-
tions.
•GNE (gene network embedding) (Kc et al., 2019) pro-
poses a multilayer perceptron (MLP) approach to encode
5
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
0.880.850.790.670.680.6270.510.470.510.50.490.50.870.820.830.80.640.520.490.490.50.470.520.54hESChHEPOursGNNLinkGENELinkGNECNNCDeepDRIMGRN-TransformerPCCMISCODEGRNBoost2GENIE3hESChHEP0.870.80.780.680.720.560.670.470.510.510.480.490.870.840.850.810.660.630.580.490.490.480.520.54TFs with most-varying 500 genesTFs with most-varying 1000 genes
hESChHEPOursGNNLinkGENELinkGNECNNCDeepDRIMGRN-TransformerPCCMISCODEGRNBoost2GENIE3hESChHEPTFs with most-varying 500 genesTFs with most-varying 1000 genesLowHigh0.60.520.480.340.250.130.150.140.150.150.150.150.780.750.690.650.460.390.350.350.350.330.380.380.590.510.50.340.270.190.160.140.150.150.140.150.780.780.70.660.490.460.530.340.340.330.370.38A)B)
Figure 2. Summary of the GRN prediction performance of scTransNet in the (A) AUROC metric (top) (B) and the AUPRC metric (bottom).
Our evaluation is conducted on two human single-cell RNA sequencing (scRNA-seq) datasets, with a cell-type-specific ground-truth
network. The scRNA-seq datasets consist of significantly varying transcription factors (TFs) and the 500 or 1000 most-varying genes.
both gene expression profiles and network topology for
predicting gene dependencies.
•CNNC (Yuan & Bar-Joseph, 2019) proposes inferring
GRNs using deep convolutional neural networks (CNNs).
•DeepDRIM (Chen et al., 2021) is a supervised deep neural
network that utilizes images representing the expression
distribution of joint gene pairs as input for binary classifi-
cation of regulatory relationships, considering both target
TF-gene pairs and potential neighbor genes.
•GRN-transformer (Shu et al., 2022) is a weakly super-
vised learning method that utilizes axial transformers to
infer cell type-specific GRNs from single-cell RNA-seq
data and generic GRNs.
•Pearson correlation coefficient (PCC) (Salleh et al., 2015;
Raza & Jaiswal, 2013) is a traditional statistical method
for measuring the linear correlation between two variables,
often used as a baseline for GRN inference.
•Mutual information (MI) (Margolin et al., 2006) is an
information-theoretic measure of the mutual dependence
between two random variables, also used as a baseline for
GRN inference.
•SCODE (Matsumoto et al., 2017) is a computational
method for inferring GRNs from single-cell RNA-seq
data using a Bayesian framework.
•GRNBoost2 (Moerman et al., 2019) is a gradient boosting-
based method for GRN inference.•GENIE3 (Huynh-Thu et al., 2010) is a random forest-
based machine learning method that constructs GRNs
based on regression weight coefficients, and won the
DREAM5 In Silico Network Challenge in 2010.
These methods represent a diverse range of approaches, in-
cluding traditional statistical methods, machine learning
techniques, and deep learning models, for inferring gene
regulatory networks from various types of data, such as
bulk and single-cell RNA-seq, as well as incorporating ad-
ditional information like network topology and chromatin
accessibility.
5. Results
5.1. Performance on benchmark datasets
The results (see Figure 2) demonstrate that scTransNet
outperforms state-of-the-art baseline methods across all
four benchmark datasets, achieving superior performance
in terms of both AUROC and AUPRC evaluation metrics.
Notably, scTransNet’s AUROC values are approximately
5.4%and7.4%higher on average compared to the second-
best methods, namely GNNLink (Mao et al., 2023) and
GENELink (Chen & Liu, 2022b), respectively. Similarly, sc-
TransNet’s AUPRC values show an impressive improvement
of approximately 7.4%and16% on average over GNNLink
and GENELink, respectively.
To gain further insights, we analyzed scTransNet’s final
gene regulatory network (GRN) predictions and compared
them with those from GENELink. Our analysis revealed
6
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Table 1. Comparison of average AUROC and AUPRC evaluation metrics on human benchmark datasets, validating the roles of the GNN
encoder, scBERT encoder, and Attentive Pooling using the cell-type-specific ChIP-seq network for our proposed method.
w/o GNN encoder w/o scBERT encoder w/o Attentive Pooling scTransNet
Dataset AUROC AUPRC AUROC AUPRC AUROC AUPRC AUROC AUPRC
hESC 0.842 0.544 0.853 0.572 0.860 0.569 0.880 0.595
hHEP 0.830 0.725 0.854 0.753 0.862 0.683 0.870 0.780
that scTransNet effectively captured all the gene regulatory
interactions predicted by GENELink. This finding suggests
that by incorporating joint learning, scTransNet does not
introduce additional noise to the predictive power of the
graph representations. Instead, it enhances the predictive
capability through the scBERT encoder in its architecture.
Figure 3 provides a visualization of a partial subgraph of
the ground truth GRN, highlighting the predictions made
by scTransNet that were not captured by GENELink, which
solely relies on graphs for predicting gene-gene interactions.
Additionally, the figure visualizes the ground truth labels
that scTransNet failed to capture. In summary, the compara-
tive analysis demonstrates that scTransNet effectively cap-
tures all the regulatory interactions predicted by GENELink
while leveraging joint learning to improve predictive perfor-
mance. The visualization illustrates the additional interac-
tions scTransNet could predict beyond GENELink, as well
as the ground truth interactions it missed, providing insights
into the strengths and limitations of the proposed method.
5.2. Discussion and Ablations
To evaluate the effectiveness of jointly learning from pre-
trained scRNA-seq language models (Yang et al., 2022),
which capture rich contextual representations, and Gene
Regulatory Networks (GRNs), which encode structured bi-
ological knowledge, we compare the average Area Under
the Receiver Operating Characteristic Curve (AUROC) and
Area Under the Precision-Recall Curve (AUPRC) metrics
with and without these encoders across the four human cell
type benchmark datasets (Pratapa et al., 2020). The aver-
age AUROC and AUPRC scores are calculated across both
the TFs+500 highly variable genes and TFs+1000 highly
variable genes datasets for each human cell data type (i.e,
hESC (human embryonic stem cells) and hHEP (human
mature hepatocytes)). Additionally, we validate the impor-
tance of incorporating Attentive Pooling (Section 3.2) by
contrasting the results when using average pooling of gene
embeddings across cells instead of attentive pooling. Consis-
tent parameter settings are employed across all four human
cell benchmark datasets, with Cell-type-specific ChIP-seq
network data serving as the ground truth.
Effect of Graph Neural Network Component: The re-
sults demonstrate the significant impact of incorporating
SOX2 NANOG
EOMESHNRNPD
CCNB2RBPJ
HSD17B1 ISL1OTX2
NUP35AR1D4BKIF23
FAM117B
Edge detected by scT ransNet
Edge not detected by scT ransNetTranscription Factor
Target GeneFigure 3. GRN prediction performance of scTransNet on a partial
ground truth subgraph. Solid line edges depict ground truth regu-
latory interactions correctly predicted by scTransNet but missed
by the baseline GENELink method, which relies solely on graph
representations. Notably, scTransNet effectively identified all reg-
ulatory links predicted by GENELink (not visualized). Dotted line
edges represent ground truth interactions that scTransNet failed
to capture reveal its limitations and providing insights for further
improvement. Overall, this highlights scTransNet’s strength in
leveraging joint learning to uncover additional true regulatory in-
teractions beyond graphs.
the Graph Neural Network (GNN) encoder component in
the proposed method. With the GNN encoder, the average
AUROC value across all the human cell type datasets is
87.5%, and the average AUPRC value is 68.7%. In contrast,
without the GNN encoder, the average AUROC drops to
83.6%, and the average AUPRC decreases to 63.4%. The
inclusion of the GNN encoder leads to an improvement of
4.6%in the average AUROC and a notable 8.3%increase in
the average AUPRC. These results highlight the consistent
performance enhancement provided by the GNN encoder
across both AUROC and AUPRC metrics for the human cell
type benchmark datasets. The GNN encoder plays a crucial
role in the architecture as the task is formulated as a super-
vised Gene Regulatory Network (GRN) inference problem,
aiming to identify potential gene regulatory dependencies
7
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
given prior knowledge of the GRN. The GNN models the
regulatory interactions as a graph, learning node represen-
tations that effectively encode the network topology and
gene interdependencies present in the GRN, which serves
as the primary source of biological knowledge. The results
in Table 1 justify the use of this structural graph representa-
tion for understanding the complex regulatory networks in
single-cell transcriptomics data.
Effect of Pre-trained Single-Cell Transcriptomics Trans-
former: The removal of the scBERT encoder also leads
to a drop in performance, with the average AUROC de-
creasing from 87.5%to85.3%, and the average AUPRC
declining from 68.7%to66.2%across both cell types (see
Table 1). The inclusion of scBERT representations improves
the AUROC by 2.6%and the AUPRC by 3.8%. While the
improvement is less significant compared to the GNN en-
coder, this is expected as the contextual representations
from scRNA-seq data are learned through pre-training on
millions of unlabeled single cells and then fine-tuned for the
specific cell type. In addition to rich contextual representa-
tions, scBERT captures long-range dependencies between
genes by leveraging self-attention mechanisms and pretrain-
ing on large-scale unlabeled scRNA-seq data (Pratapa et al.,
2020). This comprehensive understanding of gene-gene
interactions and semantic relationships allows for effective
modeling of complex, non-linear gene regulatory patterns
that extend beyond immediate neighbors in the gene regula-
tory network.
The contextual representations learned by the pre-trained
Transformer facilitate the identification of intricate regula-
tory relationships that might be overlooked by traditional
methods focused on local neighborhoods or predefined gene
sets. The ability to capture global context and long-range
dependencies is a key advantage of pre-trained single-cell
Transformer models for deciphering the intricate gene regu-
latory mechanisms governing cellular states and identities.
The improvement shown in Table 1 justifies the effectiveness
of this approach.
Effect of Attentive Pooling Mechanism: The impact of
incorporating Attentive Pooling is evaluated by comparing
the AUROC and AUPRC metrics with and without attentive
pooling across four datasets. As shown in Table 1, the in-
clusion of attentive pooling results in a slight improvement,
with a 1.6%increase in the average AUROC and a 9.6%
increase in the average AUPRC. While the improvement
is not significant, the experiments confirm that attentive
pooling offers some support for the gene regulation task.
We believe that the significance of attentive pooling will be
more pronounced when scaling the method to larger datasets.
The cell type data is sparse and of low quality. However,
the attention weights learned from scBERT (Pratapa et al.,
2020) demonstrate that the marker genes are automaticallylearned for each cell. Consequently, attentive pooling helps
to effectively focus on high-quality cell data by removing
noise. By employing an attentive pooling mechanism, sc-
TransNet selectively focuses on the most informative cells
for each gene, mitigating noise and filtering out irrelevant
information, thereby enhancing the quality of the input data
used for GRN inference.
6. Conclusion and | Future Work
In this work, we propose scTransNet, a joint graph learn-
ing inference framework that integrates prior knowledge
from known Gene Regulatory Networks (GRNs) with con-
textual representations learned by pre-trained single-cell
transcriptomics Transformers. Our approach aims to effec-
tively boost GRN prediction by leveraging the complemen-
tary strengths of structured biological knowledge and rich
contextual representations. We evaluate our method on four
human cell scRNA-seq benchmark datasets and demonstrate
consistent improvements over current baselines in predict-
ing gene-gene regulatory interactions. Our framework com-
prises four key modules: a GNN encoder to capture the
network topology from known GRNs, a scBERT encoder to
learn contextual representations from scRNA-seq data, an
Attentive Pooling mechanism to focus on informative cells,
and a Final Output layer for prediction. The synergistic
combination of these modules is verified to be effective in
accurately inferring gene regulatory dependencies.
Moving forward, we plan to incorporate the knowledge
integration process directly into the fine-tuning of the Trans-
former model, aiming to fuse information across layers more
effectively. Additionally, we will evaluate our approach on
various other datasets, including simulated datasets, to fur-
ther validate its robustness and generalizability. Beyond
GRN inference, we intend to investigate the advantages of
jointly learning single-cell Transformers and structured bio-
logical knowledge for other cell-related tasks. These tasks
include cell type annotation, identifying echo archetypes
(Luca et al., 2021), and enhancing the interpretability of
single-cell models. By leveraging the complementary
strengths of contextual representations and structured knowl-
edge, we aim to advance the understanding and analysis of
complex cellular processes and regulatory mechanisms.
Acknowledgements
Our work is sponsored by the NSF NAIRR Pilot and PSC
Neocortex, Commonwealth Cyber Initiative, Children’s Na-
tional Hospital, Fralin Biomedical Research Institute (Vir-
ginia Tech), Sanghani Center for AI and Data Analytics
(Virginia Tech), Virginia Tech Innovation Campus, and a
generous gift from the Amazon + Virginia Tech Center for
Efficient and Robust Machine Learning.
8
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Impact Statement
“This paper presents work whose goal is to advance the field
of Machine Learning. There are many potential societal
consequences of our work, none which we feel must be
specifically highlighted here.” | Conclusion and Future Work
In this work, we propose scTransNet, a joint graph learn-
ing inference framework that integrates prior knowledge
from known Gene Regulatory Networks (GRNs) with con-
textual representations learned by pre-trained single-cell
transcriptomics Transformers. Our approach aims to effec-
tively boost GRN prediction by leveraging the complemen-
tary strengths of structured biological knowledge and rich
contextual representations. We evaluate our method on four
human cell scRNA-seq benchmark datasets and demonstrate
consistent improvements over current baselines in predict-
ing gene-gene regulatory interactions. Our framework com-
prises four key modules: a GNN encoder to capture the
network topology from known GRNs, a scBERT encoder to
learn contextual representations from scRNA-seq data, an
Attentive Pooling mechanism to focus on informative cells,
and a Final Output layer for prediction. The synergistic
combination of these modules is verified to be effective in
accurately inferring gene regulatory dependencies.
Moving forward, we plan to incorporate the knowledge
integration process directly into the fine-tuning of the Trans-
former model, aiming to fuse information across layers more
effectively. Additionally, we will evaluate our approach on
various other datasets, including simulated datasets, to fur-
ther validate its robustness and generalizability. Beyond
GRN inference, we intend to investigate the advantages of
jointly learning single-cell Transformers and structured bio-
logical knowledge for other cell-related tasks. These tasks
include cell type annotation, identifying echo archetypes
(Luca et al., 2021), and enhancing the interpretability of
single-cell models. By leveraging the complementary
strengths of contextual representations and structured knowl-
edge, we aim to advance the understanding and analysis of
complex cellular processes and regulatory mechanisms.
Acknowledgements
Our work is sponsored by the NSF NAIRR Pilot and PSC
Neocortex, Commonwealth Cyber Initiative, Children’s Na-
tional Hospital, Fralin Biomedical Research Institute (Vir-
ginia Tech), Sanghani Center for AI and Data Analytics
(Virginia Tech), Virginia Tech Innovation Campus, and a
generous gift from the Amazon + Virginia Tech Center for
Efficient and Robust Machine Learning.
8
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Impact Statement
“This paper presents work whose goal is to advance the field
of Machine Learning. There are many potential societal
consequences of our work, none which we feel must be
specifically highlighted here.” | Summary of the GRN prediction performance of scTransNet in the (A) AUROC metric (top) (B) and the AUPRC metric (bottom).
Our evaluation is conducted on two human single-cell RNA sequencing (scRNA-seq) datasets, with a cell-type-specific ground-truth
network. The scRNA-seq datasets consist of significantly varying transcription factors (TFs) and the 500 or 1000 most-varying genes.
both gene expression profiles and network topology for
predicting gene dependencies.
•CNNC (Yuan & Bar-Joseph, 2019) proposes inferring
GRNs using deep convolutional neural networks (CNNs).
•DeepDRIM (Chen et al., 2021) is a supervised deep neural
network that utilizes images representing the expression
distribution of joint gene pairs as input for binary classifi-
cation of regulatory relationships, considering both target
TF-gene pairs and potential neighbor genes.
•GRN-transformer (Shu et al., 2022) is a weakly super-
vised learning method that utilizes axial transformers to
infer cell type-specific GRNs from single-cell RNA-seq
data and generic GRNs.
•Pearson correlation coefficient (PCC) (Salleh et al., 2015;
Raza & Jaiswal, 2013) is a traditional statistical method
for measuring the linear correlation between two variables,
often used as a baseline for GRN inference.
•Mutual information (MI) (Margolin et al., 2006) is an
information-theoretic measure of the mutual dependence
between two random variables, also used as a baseline for
GRN inference.
•SCODE (Matsumoto et al., 2017) is a computational
method for inferring GRNs from single-cell RNA-seq
data using a Bayesian framework.
•GRNBoost2 (Moerman et al., 2019) is a gradient boosting-
based method for GRN inference.•GENIE3 (Huynh-Thu et al., 2010) is a random forest-
based machine learning method that constructs GRNs
based on regression weight coefficients, and won the
DREAM5 In Silico Network Challenge in 2010.
These methods represent a diverse range of approaches, in-
cluding traditional statistical methods, machine learning
techniques, and deep learning models, for inferring gene
regulatory networks from various types of data, such as
bulk and single-cell RNA-seq, as well as incorporating ad-
ditional information like network topology and chromatin
accessibility.
5. Results
5.1. Performance on benchmark datasets
The results (see Figure 2) demonstrate that scTransNet
outperforms state-of-the-art baseline methods across all
four benchmark datasets, achieving superior performance
in terms of both AUROC and AUPRC evaluation metrics.
Notably, scTransNet’s AUROC values are approximately
5.4%and7.4%higher on average compared to the second-
best methods, namely GNNLink (Mao et al., 2023) and
GENELink (Chen & Liu, 2022b), respectively. Similarly, sc-
TransNet’s AUPRC values show an impressive improvement
of approximately 7.4%and16% on average over GNNLink
and GENELink, respectively.
To gain further insights, we analyzed scTransNet’s final
gene regulatory network (GRN) predictions and compared
them with those from GENELink. Our analysis revealed
6
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Table 1. Comparison of average AUROC and AUPRC evaluation metrics on human benchmark datasets, validating the roles of the GNN
encoder, scBERT encoder, and Attentive Pooling using the cell-type-specific ChIP-seq network for our proposed method.
w/o GNN encoder w/o scBERT encoder w/o Attentive Pooling scTransNet
Dataset AUROC AUPRC AUROC AUPRC AUROC AUPRC AUROC AUPRC
hESC 0.842 0.544 0.853 0.572 0.860 0.569 0.880 0.595
hHEP 0.830 0.725 0.854 0.753 0.862 0.683 0.870 0.780
that scTransNet effectively captured all the gene regulatory
interactions predicted by GENELink. This finding suggests
that by incorporating joint learning, scTransNet does not
introduce additional noise to the predictive power of the
graph representations. Instead, it enhances the predictive
capability through the scBERT encoder in its architecture.
Figure 3 provides a visualization of a partial subgraph of
the ground truth GRN, highlighting the predictions made
by scTransNet that were not captured by GENELink, which
solely relies on graphs for predicting gene-gene interactions.
Additionally, the figure visualizes the ground truth labels
that scTransNet failed to capture. In summary, the compara-
tive analysis demonstrates that scTransNet effectively cap-
tures all the regulatory interactions predicted by GENELink
while leveraging joint learning to improve predictive perfor-
mance. The visualization illustrates the additional interac-
tions scTransNet could predict beyond GENELink, as well
as the ground truth interactions it missed, providing insights
into the strengths and limitations of the proposed method.
5.2. Discussion and Ablations
To evaluate the effectiveness of jointly learning from pre-
trained scRNA-seq language models (Yang et al., 2022),
which capture rich contextual representations, and Gene
Regulatory Networks (GRNs), which encode structured bi-
ological knowledge, we compare the average Area Under
the Receiver Operating Characteristic Curve (AUROC) and
Area Under the Precision-Recall Curve (AUPRC) metrics
with and without these encoders across the four human cell
type benchmark datasets (Pratapa et al., 2020). The aver-
age AUROC and AUPRC scores are calculated across both
the TFs+500 highly variable genes and TFs+1000 highly
variable genes datasets for each human cell data type (i.e,
hESC (human embryonic stem cells) and hHEP (human
mature hepatocytes)). Additionally, we validate the impor-
tance of incorporating Attentive Pooling (Section 3.2) by
contrasting the results when using average pooling of gene
embeddings across cells instead of attentive pooling. Consis-
tent parameter settings are employed across all four human
cell benchmark datasets, with Cell-type-specific ChIP-seq
network data serving as the ground truth.
Effect of Graph Neural Network Component: The re-
sults demonstrate the significant impact of incorporating
SOX2 NANOG
EOMESHNRNPD
CCNB2RBPJ
HSD17B1 ISL1OTX2
NUP35AR1D4BKIF23
FAM117B
Edge detected by scT ransNet
Edge not detected by scT ransNetTranscription Factor
Target GeneFigure 3. GRN prediction performance of scTransNet on a partial
ground truth subgraph. Solid line edges depict ground truth regu-
latory interactions correctly predicted by scTransNet but missed
by the baseline GENELink method, which relies solely on graph
representations. Notably, scTransNet effectively identified all reg-
ulatory links predicted by GENELink (not visualized). Dotted line
edges represent ground truth interactions that scTransNet failed
to capture reveal its limitations and providing insights for further
improvement. Overall, this highlights scTransNet’s strength in
leveraging joint learning to uncover additional true regulatory in-
teractions beyond graphs.
the Graph Neural Network (GNN) encoder component in
the proposed method. With the GNN encoder, the average
AUROC value across all the human cell type datasets is
87.5%, and the average AUPRC value is 68.7%. In contrast,
without the GNN encoder, the average AUROC drops to
83.6%, and the average AUPRC decreases to 63.4%. The
inclusion of the GNN encoder leads to an improvement of
4.6%in the average AUROC and a notable 8.3%increase in
the average AUPRC. These results highlight the consistent
performance enhancement provided by the GNN encoder
across both AUROC and AUPRC metrics for the human cell
type benchmark datasets. The GNN encoder plays a crucial
role in the architecture as the task is formulated as a super-
vised Gene Regulatory Network (GRN) inference problem,
aiming to identify potential gene regulatory dependencies
7
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
given prior knowledge of the GRN. The GNN models the
regulatory interactions as a graph, learning node represen-
tations that effectively encode the network topology and
gene interdependencies present in the GRN, which serves
as the primary source of biological knowledge. The results
in Table 1 justify the use of this structural graph representa-
tion for understanding the complex regulatory networks in
single-cell transcriptomics data.
Effect of Pre-trained Single-Cell Transcriptomics Trans-
former: The removal of the scBERT encoder also leads
to a drop in performance, with the average AUROC de-
creasing from 87.5%to85.3%, and the average AUPRC
declining from 68.7%to66.2%across both cell types (see
Table 1). The inclusion of scBERT representations improves
the AUROC by 2.6%and the AUPRC by 3.8%. While the
improvement is less significant compared to the GNN en-
coder, this is expected as the contextual representations
from scRNA-seq data are learned through pre-training on
millions of unlabeled single cells and then fine-tuned for the
specific cell type. In addition to rich contextual representa-
tions, scBERT captures long-range dependencies between
genes by leveraging self-attention mechanisms and pretrain-
ing on large-scale unlabeled scRNA-seq data (Pratapa et al.,
2020). This comprehensive understanding of gene-gene
interactions and semantic relationships allows for effective
modeling of complex, non-linear gene regulatory patterns
that extend beyond immediate neighbors in the gene regula-
tory network.
The contextual representations learned by the pre-trained
Transformer facilitate the identification of intricate regula-
tory relationships that might be overlooked by traditional
methods focused on local neighborhoods or predefined gene
sets. The ability to capture global context and long-range
dependencies is a key advantage of pre-trained single-cell
Transformer models for deciphering the intricate gene regu-
latory mechanisms governing cellular states and identities.
The improvement shown in Table 1 justifies the effectiveness
of this approach.
Effect of Attentive Pooling Mechanism: The impact of
incorporating Attentive Pooling is evaluated by comparing
the AUROC and AUPRC metrics with and without attentive
pooling across four datasets. As shown in Table 1, the in-
clusion of attentive pooling results in a slight improvement,
with a 1.6%increase in the average AUROC and a 9.6%
increase in the average AUPRC. While the improvement
is not significant, the experiments confirm that attentive
pooling offers some support for the gene regulation task.
We believe that the significance of attentive pooling will be
more pronounced when scaling the method to larger datasets.
The cell type data is sparse and of low quality. However,
the attention weights learned from scBERT (Pratapa et al.,
2020) demonstrate that the marker genes are automaticallylearned for each cell. Consequently, attentive pooling helps
to effectively focus on high-quality cell data by removing
noise. By employing an attentive pooling mechanism, sc-
TransNet selectively focuses on the most informative cells
for each gene, mitigating noise and filtering out irrelevant
information, thereby enhancing the quality of the input data
used for GRN inference.
6. Conclusion and Future Work
In this work, we propose scTransNet, a joint graph learn-
ing inference framework that integrates prior knowledge
from known Gene Regulatory Networks (GRNs) with con-
textual representations learned by pre-trained single-cell
transcriptomics Transformers. Our approach aims to effec-
tively boost GRN prediction by leveraging the complemen-
tary strengths of structured biological knowledge and rich
contextual representations. We evaluate our method on four
human cell scRNA-seq benchmark datasets and demonstrate
consistent improvements over current baselines in predict-
ing gene-gene regulatory interactions. Our framework com-
prises four key modules: a GNN encoder to capture the
network topology from known GRNs, a scBERT encoder to
learn contextual representations from scRNA-seq data, an
Attentive Pooling mechanism to focus on informative cells,
and a Final Output layer for prediction. The synergistic
combination of these modules is verified to be effective in
accurately inferring gene regulatory dependencies.
Moving forward, we plan to incorporate the knowledge
integration process directly into the fine-tuning of the Trans-
former model, aiming to fuse information across layers more
effectively. Additionally, we will evaluate our approach on
various other datasets, including simulated datasets, to fur-
ther validate its robustness and generalizability. Beyond
GRN inference, we intend to investigate the advantages of
jointly learning single-cell Transformers and structured bio-
logical knowledge for other cell-related tasks. These tasks
include cell type annotation, identifying echo archetypes
(Luca et al., 2021), and enhancing the interpretability of
single-cell models. By leveraging the complementary
strengths of contextual representations and structured knowl-
edge, we aim to advance the understanding and analysis of
complex cellular processes and regulatory mechanisms.
Acknowledgements
Our work is sponsored by the NSF NAIRR Pilot and PSC
Neocortex, Commonwealth Cyber Initiative, Children’s Na-
tional Hospital, Fralin Biomedical Research Institute (Vir-
ginia Tech), Sanghani Center for AI and Data Analytics
(Virginia Tech), Virginia Tech Innovation Campus, and a
generous gift from the Amazon + Virginia Tech Center for
Efficient and Robust Machine Learning.
8
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Impact Statement
“This paper presents work whose goal is to advance the field
of Machine Learning. There are many potential societal
consequences of our work, none which we feel must be
specifically highlighted here.” | Section not found | References
Aibar, S., Gonz ´alez-Blas, C. B., Moerman, T., Huynh-Thu,
V . A., Imrichova, H., Hulselmans, G., Rambow, F., Ma-
rine, J.-C., Geurts, P., Aerts, J., et al. Scenic: single-cell
regulatory network inference and clustering. Nature meth-
ods, 14(11):1083–1086, 2017.
Akers, K. and Murali, T. Gene regulatory network infer-
ence in single-cell biology. Current Opinion in Systems
Biology , 26:87–97, 2021.
Biswas, S., Manicka, S., Hoel, E., and Levin, M. Gene
regulatory networks exhibit several kinds of memory:
quantification of memory in biological and random tran-
scriptional networks. iScience , 24(3):102131, March
2021.
Buettner, F., Natarajan, K. N., Casale, F. P., Proserpio, V .,
Scialdone, A., Theis, F. J., Teichmann, S. A., Marioni,
J. C., and Stegle, O. Computational analysis of cell-to-cell
heterogeneity in single-cell rna-sequencing data reveals
hidden subpopulations of cells. Nature biotechnology , 33
(2):155–160, 2015.
Camp, J. G., Sekine, K., Gerber, T., Loeffler-Wirth, H.,
Binder, H., Gac, M., Kanton, S., Kageyama, J., Damm,
G., Seehofer, D., et al. Multilineage communication
regulates human liver bud development from pluripotency.
Nature , 546(7659):533–538, 2017.
Chan, T. E., Stumpf, M. P., and Babtie, A. C. Gene reg-
ulatory network inference from single-cell data using
multivariate information measures. Cell systems , 5(3):
251–267, 2017.
Chen, G. and Liu, Z.-P. Graph attention network for
link prediction of gene regulations from single-cell
RNA-sequencing data. Bioinformatics , 38(19):4522–
4529, 08 2022a. ISSN 1367-4803. doi: 10.1093/
bioinformatics/btac559. URL https://doi.org/
10.1093/bioinformatics/btac559 .
Chen, G. and Liu, Z.-P. Graph attention network for
link prediction of gene regulations from single-cell rna-
sequencing data. Bioinformatics , 38(19):4522–4529,
2022b.
Chen, J., Cheong, C., Lan, L., Zhou, X., Liu, J., Lyu, A.,
Cheung, W. K., and Zhang, L. Deepdrim: a deep neuralnetwork to reconstruct cell-type-specific gene regulatory
network using single-cell rna-seq data. Briefings in bioin-
formatics , 22(6):bbab325, 2021.
Chen, J., Xu, H., Tao, W., Chen, Z., Zhao, Y ., and
Han, J.-D. J. Transformer for one stop interpretable
cell type annotation. Nature Communications , 14(1):
223, Jan 2023. ISSN 2041-1723. doi: 10.1038/
s41467-023-35923-4. URL https://doi.org/10.
1038/s41467-023-35923-4 .
Choromanski, K., Likhosherstov, V ., Dohan, D., Song, X.,
Gane, A., Sarlos, T., Hawkins, P., Davis, J., Mohiuddin,
A., Kaiser, L., Belanger, D., Colwell, L., and Weller, A.
Rethinking attention with performers, 2022.
Cramer, P. Organization and regulation of gene transcription.
Nature , 573(7772):45–54, 2019.
Cui, H., Wang, C., Maan, H., Pang, K., Luo, F., Duan, N.,
and Wang, B. scgpt: toward building a foundation model
for single-cell multi-omics using generative ai. Nature
Methods , Feb 2024. ISSN 1548-7105. doi: 10.1038/
s41592-024-02201-0. URL https://doi.org/10.
1038/s41592-024-02201-0 .
Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. Bert:
Pre-training of deep bidirectional transformers for lan-
guage understanding, 2019.
Du, J., Jia, P., Dai, Y ., Tao, C., Zhao, Z., and Zhi, D.
Gene2vec: distributed representation of genes based on
co-expression. BMC genomics , 20:7–15, 2019.
Feng, Y ., Chen, X., Lin, B. Y ., Wang, P., Yan, J., and Ren, X.
Scalable multi-hop relational reasoning for knowledge-
aware question answering, 2020.
Huynh-Thu, V . A., Irrthum, A., Wehenkel, L., and Geurts, P.
Inferring regulatory networks from expression data using
tree-based methods. PloS one , 5(9):e12776, 2010.
Jovic, D., Liang, X., Zeng, H., Lin, L., Xu, F., and Luo, Y .
Single-cell RNA sequencing technologies and applica-
tions: A brief overview. Clin. Transl. Med. , 12(3):e694,
March 2022.
KC, K., Li, R., Cui, F., Yu, Q., and Haake, A. R.
Gne: a deep learning framework for gene network in-
ference by aggregating biological information. BMC
Systems Biology , 13(2):38, Apr 2019. doi: 10.1186/
s12918-019-0694-y. URL https://doi.org/10.
1186/s12918-019-0694-y .
Kc, K., Li, R., Cui, F., Yu, Q., and Haake, A. R. Gne:
a deep learning framework for gene network inference
by aggregating biological information. BMC systems
biology , 13:1–14, 2019.
9
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Kharchenko, P. V ., Silberstein, L., and Scadden, D. T.
Bayesian approach to single-cell differential expression
analysis. Nature methods , 11(7):740–742, 2014.
Luca, B. A., Steen, C. B., Matusiak, M., Azizi, A.,
Varma, S., Zhu, C., Przybyl, J., Esp ´ın-P´erez, A.,
Diehn, M., Alizadeh, A. A., van de Rijn, M., Gen-
tles, A. J., and Newman, A. M. Atlas of clinically
distinct cell states and ecosystems across human solid
tumors. Cell, 184(21):5482–5496.e28, 2021. ISSN
0092-8674. doi: https://doi.org/10.1016/j.cell.2021.09.
014. URL https://www.sciencedirect.com/
science/article/pii/S0092867421010618 .
Mao, G., Pang, Z., Zuo, K., Wang, Q., Pei, X., Chen, X., and
Liu, J. Predicting gene regulatory links from single-cell
RNA-seq data using graph neural networks. Briefings
in Bioinformatics , 24(6):bbad414, 11 2023. ISSN 1477-
4054. doi: 10.1093/bib/bbad414. URL https://doi.
org/10.1093/bib/bbad414 .
Margolin, A., Nemenman, I., Basso, K., Wiggins, C.,
Stolovitzky, G., Favera, R., and andCalifano, A. Aracne:
Analgorithm forthereconstructionofgeneregulatorynet-
worksina mammaliancellularcontext. BMCbioinformat-
ics, 7, 2006.
Matsumoto, H., Kiryu, H., Furusawa, C., Ko, M. S., Ko,
S. B., Gouda, N., Hayashi, T., and Nikaido, I. Scode:
an efficient regulatory network inference algorithm from
single-cell rna-seq during differentiation. Bioinformatics ,
33(15):2314–2321, 2017.
Moerman, T., Aibar Santos, S., Bravo Gonz ´alez-Blas, C.,
Simm, J., Moreau, Y ., Aerts, J., and Aerts, S. Grnboost2
and arboreto: efficient and scalable inference of gene
regulatory networks. Bioinformatics , 35(12):2159–2161,
2019.
OpenAI, R. Gpt-4 technical report. ArXiv , 2303, 2023.
Parmar, N., Vaswani, A., Uszkoreit, J., Kaiser, L.,
Shazeer, N., Ku, A., and Tran, D. Image trans-
former. In Dy, J. and Krause, A. (eds.), Proceed-
ings of the 35th International Conference on Machine
Learning , volume 80 of Proceedings of Machine Learn-
ing Research , pp. 4055–4064. PMLR, 10–15 Jul 2018.
URLhttps://proceedings.mlr.press/v80/
parmar18a.html .
Pratapa, A., Jalihal, A. P., Law, J. N., Bharadwaj,
A., and Murali, T. M. Benchmarking algorithms
for gene regulatory network inference from single-
cell transcriptomic data. Nature Methods , 17(2):147–
154, Feb 2020. ISSN 1548-7105. doi: 10.1038/
s41592-019-0690-6. URL https://doi.org/10.
1038/s41592-019-0690-6 .Raza, K. and Jaiswal, R. Reconstruction and analysis of
cancer-specific gene regulatory networks from gene ex-
pression profiles. arXiv preprint arXiv:1305.5750 , 2013.
Salleh, F. H. M., Arif, S. M., Zainudin, S., and Firdaus-
Raih, M. Reconstructing gene regulatory networks from
knock-out data using gaussian noise model and pearson
correlation coefficient. Computational biology and chem-
istry, 59:3–14, 2015.
Shu, H., Zhou, J., Lian, Q., Li, H., Zhao, D., Zeng, J., and
Ma, J. Modeling gene regulatory networks using neural
network architectures. Nature Computational Science , 1
(7):491–501, 2021.
Shu, H., Ding, F., Zhou, J., Xue, Y ., Zhao, D., Zeng, J.,
and Ma, J. Boosting single-cell gene regulatory network
reconstruction via bulk-cell transcriptomic data. Briefings
in Bioinformatics , 23(5):bbac389, 2022.
Theodoris, C. V ., Xiao, L., Chopra, A., Chaffin, M. D.,
Al Sayed, Z. R., Hill, M. C., Mantineo, H., Brydon,
E. M., Zeng, Z., Liu, X. S., and Ellinor, P. T. Transfer
learning enables predictions in network biology. Nature ,
618(7965):616–624, Jun 2023. ISSN 1476-4687. doi:
10.1038/s41586-023-06139-9. URL https://doi.
org/10.1038/s41586-023-06139-9 .
Tsai, M.-J., Wang, J.-R., Ho, S.-J., Shu, L.-S., Huang, W.-
L., and Ho, S.-Y . Grema: modelling of emulated gene
regulatory networks with confidence levels based on evo-
lutionary intelligence to cope with the underdetermined
problem. Bioinformatics , 36(12):3833–3840, 2020.
Van de Sande, B., Flerin, C., Davie, K., De Waegeneer,
M., Hulselmans, G., Aibar, S., Seurinck, R., Saelens,
W., Cannoodt, R., Rouchon, Q., et al. A scalable scenic
workflow for single-cell gene regulatory network analysis.
Nature protocols , 15(7):2247–2276, 2020.
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones,
L., Gomez, A. N., Kaiser, L., and Polosukhin, I. Attention
is all you need, 2023.
Velickovic, P., Cucurull, G., Casanova, A., Romero, A.,
Lio’, P., and Bengio, Y . Graph attention networks.
ArXiv , abs/1710.10903, 2017. URL https://api.
semanticscholar.org/CorpusID:3292002 .
Wagner, A., Regev, A., and Yosef, N. Revealing the vectors
of cellular identity with single-cell genomics. Nature
biotechnology , 34(11):1145–1160, 2016.
Wu, Z., Pan, S., Chen, F., Long, G., Zhang, C., and Philip,
S. Y . A comprehensive survey on graph neural networks.
IEEE transactions on neural networks and learning sys-
tems, 32(1):4–24, 2020.
10
scTransNet for GRN Inference from Pre-trained scRNA-seq Transformer with Joint Graph Learning
Yang, F., Wang, W., Wang, F., Fang, Y ., Tang, D., Huang,
J., Lu, H., and Yao, J. scbert as a large-scale pretrained
deep language model for cell type annotation of single-
cell rna-seq data. Nature Machine Intelligence , 4(10):
852–866, Oct 2022. ISSN 2522-5839. doi: 10.1038/
s42256-022-00534-z. URL https://doi.org/10.
1038/s42256-022-00534-z .
Yin, P., Neubig, G., Yih, W.-t., and Riedel, S. TaBERT:
Pretraining for joint understanding of textual and tab-
ular data. In Jurafsky, D., Chai, J., Schluter, N., and
Tetreault, J. (eds.), Proceedings of the 58th Annual Meet-
ing of the Association for Computational Linguistics , pp.
8413–8426, Online, July 2020. Association for Compu-
tational Linguistics. doi: 10.18653/v1/2020.acl-main.
745. URL https://aclanthology.org/2020.
acl-main.745 .
Yuan, Y . and Bar-Joseph, Z. Deep learning for inferring
gene relationships from single-cell expression data. Pro-
ceedings of the National Academy of Sciences , 116(52):
27151–27158, 2019.
Zeng, Y ., He, Y ., Zheng, R., and Li, M. Inferring single-
cell gene regulatory network by non-redundant mutual
information. Briefings in Bioinformatics , 24(5):bbad326,
2023.
Zhang, Y ., Jin, R., and Zhou, Z.-H. Understanding bag-
of-words model: a statistical framework. International
journal of machine learning and cybernetics , 1:43–52,
2010.
Zhao, M., He, W., Tang, J., Zou, Q., and Guo, F. A hybrid
deep learning framework for gene regulatory network
inference from single-cell transcriptomic data. Briefings
in bioinformatics , 23(2):bbab568, 2022.
11 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18213v1 | http://arxiv.org/pdf/2407.18213v1 | Exploring Scaling Trends in LLM Robustness | Nikolhaus Howe, Michał Zajac, Ian McKenzie, Oskar Hollinsworth, Tom Tseng, Pierre-Luc Bacon, Adam Gleave | 2024-07-25 | Abstract.
html .
Moustafa Alzantot, Bharathan Balaji, and Mani Sri-
vastava. Did you hear that? Adversarial examples
against automatic speech recognition, 2018. URL
https://arxiv.org/abs/1808.05665 .
Cem Anil, Esin Durmus, Mrinank Sharma, Joe Benton,
Sandipan Kundu, Joshua Batson, Nina Rimsky,
Meg Tong, Jesse Mu, Daniel Ford, Francesco
Mosconi, Rajashree Agrawal, Rylan Schaeffer,
Naomi Bashkansky, Samuel Svenningsen, Mike
Lambert, Ansh Radhakrishnan, Carson Denison,
Evan J Hubinger, Yuntao Bai, Trenton Bricken,
6
Timothy Maxwell, Nicholas Schiefer, Jamie Sully,
Alex Tamkin, Tamera Lanham, Karina Nguyen,
Tomasz Korbak, Jared Kaplan, Deep Ganguli,
Samuel R Bowman, Ethan Perez, Roger Grosse,
and David Duvenaud. Many-shot Jailbreaking,
2024. URL https://www-cdn.anthropic.com/
af5633c94ed2beb282f6a53c595eb437e8e7b630/
Many_Shot_Jailbreaking__2024_04_02_0936.
pdf.
Anthropic. Tool use (function calling), 2024. URL
https://archive.ph/EqXCz .
Brian R. Bartoldson, James Diffenderfer, Konstanti-
nos Parasyris, and Bhavya Kailkhura. Adversar-
ial Robustness Limits via Scaling-Law and Human-
Alignment Studies, April 2024. URL http://arxiv.
org/abs/2404.09349 .
Stella Biderman, Hailey Schoelkopf, Quentin Gregory
Anthony, Herbie Bradley, Kyle O’Brien, Eric Halla-
han, Mohammad Aflah Khan, Shivanshu Purohit,
USVSN Sai Prashanth, Edward Raff, et al. Pythia:
A suite for analyzing large language models across
training and scaling. In International Conference on
Machine Learning , pages 2397–2430. PMLR, 2023.
Yair Carmon, Aditi Raghunathan, Ludwig Schmidt,
Percy Liang, and John C. Duchi. Unlabeled Data Im-
proves Adversarial Robustness, January 2022. URL
http://arxiv.org/abs/1905.13736 .
Canyu Chen and Kai Shu. Can LLM-generated misin-
formation be detected? In International Conference
on Learning Representations , 2024.
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, Alex Ray, Raul Puri, Gretchen
Krueger, Michael Petrov, Heidy Khlaaf, Girish Sas-
try, Pamela Mishkin, Brooke Chan, Scott Gray,
Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz
Kaiser, Mohammad Bavarian, Clemens Winter,
Philippe Tillet, Felipe Petroski Such, Dave Cum-
mings, Matthias Plappert, Fotios Chantzis, Eliza-
beth Barnes, Ariel Herbert-Voss, William Hebgen
Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie
Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain,
William Saunders, Christopher Hesse, Andrew N.
Carr, Jan Leike, Josh Achiam, Vedant Misra, Evan
Morikawa, Alec Radford, Matthew Knight, Miles
Brundage, Mira Murati, Katie Mayer, Peter Welin-
der, Bob McGrew, Dario Amodei, Sam McCandlish,
Ilya Sutskever, and Wojciech Zaremba. EvaluatingLarge Language Models Trained on Code, July 2021.
URL http://arxiv.org/abs/2107.03374 .
Moustapha M Cisse, Yossi Adi, Natalia Neverova,
and Joseph Keshet. Houdini: Fooling deep
structured visual and speech recognition mod-
els with adversarial examples. In Advances in
Neural Information Processing Systems , vol-
ume 30, 2017. URL https://proceedings.
neurips.cc/paper_files/paper/2017/hash/
d494020ff8ec181ef98ed97ac3f25453-Abstract.
html .
Edoardo Debenedetti, Zishen Wan, Maksym An-
driushchenko, Vikash Sehwag, Kshitij Bhardwaj, and
Bhavya Kailkhura. Scaling Compute Is Not All You
Need for Adversarial Robustness, December 2023.
URL http://arxiv.org/abs/2312.13131 .
Deep Ganguli, Liane Lovitt, Jackson Kernion, Amanda
Askell, Yuntao Bai, Saurav Kadavath, Ben Mann,
Ethan Perez, Nicholas Schiefer, Kamal Ndousse,
Andy Jones, Sam Bowman, Anna Chen, Tom Con-
erly, Nova DasSarma, Dawn Drain, Nelson El-
hage, Sheer El-Showk, Stanislav Fort, Zac Hatfield-
Dodds, Tom Henighan, Danny Hernandez, Tristan
Hume, Josh Jacobson, Scott Johnston, Shauna
Kravec, Catherine Olsson, Sam Ringer, Eli Tran-
Johnson, Dario Amodei, Tom Brown, Nicholas
Joseph, Sam McCandlish, Chris Olah, Jared Ka-
plan, and Jack Clark. Red Teaming Language Mod-
els to Reduce Harms: | Introduction
Language models have demonstrated a range of im-
pressive capabilities in tasks such as general reason-
ing (Hendrycks et al., 2021), graduate-level Q&A (Rein
et al., 2023), and code generation (Chen et al., 2021).
This growth in capabilities has fueled rapid deployment,
with ChatGPT becoming one of the fastest-growing
consumer applications in history (Hu, 2023). More-
over, language models are increasingly integrated into
larger systems enabling them to take actions in the real
world using external tools (OpenAI, 2023; Anthropic,
2024; Google, 2024) and pursue long-term open-ended
goals (Richards, 2024; Kinniment et al., 2024).
The advent of language models enables many new
tasks to be solved by AI but also introduces novel
∗Primary contact for correspondences.classes of security vulnerabilities. In particular, a wide
variety of adversarial prompts can hijack models (Wei
et al., 2023; Zou et al., 2023; Anil et al., 2024). This
enables malicious users to bypass safety fine-tuning per-
formed by the designer, unlocking harmful capabilities
such as generating compelling misinformation (Spitale
et al., 2023; Chen and Shu, 2024). Innocent users
are also at risk from attackers using methods such as
indirect prompt injections (Abdelnabi et al., 2023) to
exploit LLM-driven applications without any awareness
or participation by the user.
A key question is whether future, more capable sys-
tems will naturally become more robust, or if this will
instead require a dedicated safety effort. Although
current attacks are concerning, the risks could grow
still greater with future models capable of more danger-
ous actions, such as assisting with biological weapon
development (Mouton et al., 2023), or with greater
affordances to interact with the world (Sharkey et al.,
2023), such as a virtual assistant for a CEO of a major
company. Prior work has found that superhuman Go
systems (Wang et al., 2023) are vulnerable to attack,
demonstrating that impressive capabilities do not guar-
antee robustness. However, work has also found that
scaling unlabeled pretraining data (Hendrycks et al.,
2019; Carmon et al., 2022; Alayrac et al., 2019) and
model size (Xie and Yuille, 2019; Huang et al., 2023)
improves adversarial robustness in computer vision.
To answer this question, we conduct an empirical
investigation into scaling trends for the adversarial
robustness of language models. These trends enable us
to forecast the robustness of future models, and give us
insight into how the offense-defense balance might shift
over time. For example, does the cost of conducting
an attack against more capable models grow faster
1arXiv:2407.18213v1 [cs.LG] 25 Jul 2024
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, GCG attack
Figure 1: Attack success rate ( y-axis) of GCGagainst Pythia models of different sizes ( x-axis) fine-tuned on
theSpam (left) and IMBD (right ) tasks. We run three fine-tuning seeds for each model, plotting the
median attack success rate and shading the range between the min and max. We observe significant
attack success rate variability across model sizes: median robustness does not improve monotonically
with scale.
or slower than the defender’s cost of training those
models?
Concretely, we investigate the robustness of Pythia
models ranging from 14M to 12B parameter (Biderman
et al., 2023) against two attacks: the random tokens
baseline and the state-of-the-art greedy coordinate
gradient attack. We test these models in various
simple classification tasks where our models achieve
high accuracy on clean (non-adversarial) data.
We first evaluate these pretrained models fine-tuned
only on clean data. Larger models tend to be more
resistant to attack, but the effect is weak and noisy
(Figure 1). By contrast, a clearer scaling trend emerges
for models adversarially trained against examples of
attacks (Figure 2). Larger models are both more
sample efficient, becoming more robust with fewer
examples, and converge to be more robust given a
sufficient number of examples. Moreover, adversarial
training against one attack transfers protection to
similar attacks, with the transfer being stronger for
larger models (Figure 3b).
2. | Section not found | Related Work
Adversarial examples were first identified in image clas-
sifiers (Szegedy et al., 2014), but have since been found
for systems performing image captioning (Xu et al.,
2019; Zhang et al., 2020), speech recognition (Cisse
et al., 2017; Alzantot et al., 2018; Sch¨ onherr et al.,
2018), and reinforcement learning (Huang et al., 2017;
Gleave et al., 2020; Ilahi et al., 2022). Moreover, arange of adversarial threat models (Gilmer et al., 2018)
give rise to viable attacks.
Most recently, many qualitatively different vulner-
abilities have been found in language models, from
human-understandable “jailbreaks” (Wei et al., 2023)
to seemingly gibberish adversarial suffixes (Wallace
et al., 2021; Zou et al., 2023). Simple methods such
as perplexity filtering and paraphrasing defend against
some of these attacks (Jain et al., 2023). However,
these defenses can easily be bypassed by more sophisti-
cated methods (Zhu et al., 2023). Adversarial training
shows more promise as a defense (Ziegler et al., 2022),
and is the focus of our analysis.
The determinants of adversarial robustness have been
well-studied in computer vision. One line of scholarship
proposes a fundamental tradeoff between robustness
and accuracy (Tsipras et al., 2019): exploitable mod-
els are simply relying on non-robust features (Ilyas
et al., 2019), which improve training performance
but hurt robustness. Other work has emphasized
what does improve robustness. Scaling unlabeled pre-
training data (Hendrycks et al., 2019; Carmon et al.,
2022; Alayrac et al., 2019), model depth (Xie and
Yuille, 2019) and model width (Huang et al., 2023)
improves adversarial robustness in computer vision.
However, other work shows that computer vision ad-
versarial robustness scales too slowly to be a full so-
lution (Debenedetti et al., 2023; Bartoldson et al.,
2024).
Language model scaling laws (Hestness et al., 2017;
Rosenfeld et al., 2019; Kaplan et al., 2020; Hoff-
2
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attackFigure 2: Attack success rate ( y-axis) of GCGagainst Pythia models of varying sizes (line color) on Spam (left)
andIMDB (right ) during adversarial training ( x-axis) against GCGover 10 rounds ( top) and over
30 rounds ( bottom ). See Figure 16 for a zoomed-in view of the final 10 rounds of the 30-round
adversarial training. We plot the median over three seeds and shade the region between the min
and max. We observe larger models are more sample efficient, and appear to converge to a higher
robustness (lower attack success rate).
mann et al., 2022) have shown that increasing com-
pute improves performance across many tasks and
domains (Chen et al., 2021; Hernandez et al., 2021).
However, scaling does not solve all problems (Lin et al.,
2022; McKenzie et al., 2023). There has been only
limited work on scaling laws for adversarial robustness
in language models, with mixed results. Ganguli et al.
(2022) show that LLMs become harder to attack with
scale—but Anil et al. (2024) find that some attacks
become more successful with scale.
3. Experimental | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Methodology
We test models in the binary classification setting,
as it is the simplest context in which to study LLM
robustness. Crucially, binary classification allows usto measure robustness by the attack success rate ,
defined as the proportion of examples correctly clas-
sified by the model before attack that are incorrectly
classified after attack.1We adapt pretrained models
for classification by replacing the unembedding layer
with a randomly initialized classification head, and
then fine-tune the models on each task.
Tasks We consider four tasks in our experiments,
the latter two developed by us for this project:
•Spam (Metsis et al., 2006): Given the subject and
body of an email, is it spam or not?
•IMDB (Maas et al., 2011): Given a movie review,
1We assume that the attack does not, in fact, change the
ground truth label of the datapoint. This is guaranteed by
construction for some of our simple procedurally generated
tasks, and was manually validated on a random sample of
datapoints in other tasks.
3
is the sentiment positive or negative?
•PasswordMatch : Given two strings in the prompt,
are they exactly equal?
•WordLength : Given two words in the prompt, is
the first word shorter than the second?
Spam andIMDB were chosen as standard natural lan-
guage processing classification tasks. PasswordMatch
was inspired by TensorTrust (Toyer et al., 2023), and
WordLength by the RuLES dataset (Mu et al., 2023).
Both PasswordMatch andWordLength were designed
to be easily procedurally generated and have ground
truth labels that can be checked algorithmically. For
brevity, we report on Spam andIMDB in the main text,
with plots for other tasks deferred to Appendices D
and E. We provide example datapoints and details
about the datasets in Appendix B.
Models We test the Pythia model family (Biderman
et al., 2023). These models range in size from 14M to
12B parameters (or 7.6M to 11.6B when used with a
classification head). All models were trained to predict
the next token on the same dataset following the same
training protocol, allowing us to isolate model scale
from other confounding factors.
Attacks Our attacks append an adversarial suffix
ofNtokens to the prompt. We use two different
procedures to generate this adversarial suffix: a random
token baseline ( RandomToken ) and the state-of-the-
art greedy coordinate gradient attack ( GCG; Zou et al.,
2023). RandomToken was chosen due to its simplicity.
GCG was chosen as it is currently one of the most
effective attacks on language models.
In the RandomToken baseline, the Ntokens are cho-
sen uniformly at random from the model’s vocabulary.
We evaluate the model on the attacked text and then
repeat the process with another sample of Nrandom
tokens until the model is successfully attacked or an
appointed budget for model calls is exhausted.
InGCG(Zou et al., 2023), the Ntokens are initialized
arbitrarily and then greedily optimized over multiple
rounds. In each round, the gradient of the loss function
with respect to the attack tokens is computed. This
gradient is used to compute a set of promising single-
token modifications, from which the best candidate
is selected and used in the next round. To make this
attack work in the classification setting, we minimize
the cross-entropy loss between the predicted label and
the target label.
In our experiments, we always use N= 10 tokens.
For more details about the attacks and hyperparame-
ters used, see Appendix C.4. Fine-tuning
Figure 1 shows the robustness of fine-tuned models
against the GCGattack. The attack is generally less
successful on larger models, but model size alone does
not explain all the variance in attack success rate.
We observe similarly large random variation in attack
success across model sizes on other tasks and with
other attacks; for more details, see Appendix D.2.
As described in Section 3, we use the Pythia mod-
els, which range from 7.6M to 11.6B parameters after
replacing the unembedding matrix with a classifica-
tion head.2We fine-tune all models for a single epoch
with default hyperparameters from HuggingFace Trans-
formers (Wolf et al., 2019), except for the learning
rate which we set to 1e−5. All models reach >83%
accuracy on all tasks, with larger models generally
performing better (see Appendix D.1 for the final val-
idation performance of all models on all tasks). We
then evaluate the fine-tuned models against adversarial
attacks on an unseen validation dataset.
To understand the source of the variability in model
robustness shown by our experiments, we varied 1)
the pretraining checkpoint,3and 2) the random seeds
used to initialize the classification head before fine-
tuning. Both factors led to significant variability in
model robustness, with pretraining checkpoint con-
tributing significantly more variability. The variability
was comparable or greater than that of an order of
magnitude of model scaling, indicating that out-of-the-
box robustness on a given task is heavily influenced by
the randomness of the pretraining procedure itself.
This initial result suggests that we cannot rely on
scale alone to solve the problem of robustness. How-
ever, in practice, we would apply a defense to a model
prior to deploying it in a security-critical setting. In the
following section, we consider whether scale enables
defenses to more effectively improve model robustness.
5. Adversarial training
In this section, we explore how model size impacts
robustness when performing adversarial training. Fig-
ure 2 evaluates the robustness of Pythia models to
theGCGattack when adversarially trained against the
same attack. We see a much cleaner trend than in the
fine-tuning only case: larger models gain robustness
2In all figures, we report the actual parameter count of the
classification model, and not the pretrained model it was
derived from.
3The Pythia models provide checkpoints from earlier stages of
pretraining. We used various checkpoints from the final 10%
of pretraining as a starting point for fine-tuning.
4
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG train, GCG 30 its eval
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M(a)Adversarial training against 10-iteration GCG, with eval-
uation against 30-iteration GCG. All models show some
transfer of their defense to this stronger attack, with
larger models doing so more effectively.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RT train, GCG eval(b)Adversarial training against 10-iteration RandomToken ,
with evaluation against 10-iteration GCG.≥100M pa-
rameter models show strong defense transfer, while
smaller models struggle against the new attack.
Figure 3: Attack success rate ( y-axis) against Pythia models of varying sizes (line color) during adversarial
training ( x-axis).
more quickly and converge to be more robust than
smaller models. These results suggest that model size
is a strong predictor of robustness—so long as the
model is explicitly optimized for robustness. We ob-
serve similar behavior across the other two datasets
and two attacks; see Appendix E for these plots, in-
cluding extensions for up to 30 adversarial training
rounds.
We perform adversarial training by iteratively training
our model on a training dataset, evaluating the model
on attacked examples, and then adding successful at-
tack examples to the training dataset. Simultaneously,
we evaluate model performance on a held-out attacked
validation dataset. This procedure is illustrated in Fig-
ure 12.
In our experiments, we initialize the training dataset
to consist of 2000 clean examples, and add 200 ad-
versarial examples to the training dataset each round.
We repeat the train-attack-add loop 30 times (here we
only show the first 10 rounds; see Appendix E for the
full 30-round plots). Since adversarial examples are
only added after the first training round, the models
here were trained for a single epoch on the 2000 clean
datapoints before being adversarially attacked.
We perform adversarial training on Pythia models
ranging from 7.6 to 909 million parameters after re-
placing the unembedding layer with a classification
head.4Table 1 in Appendix A enumerates all model
4Specifically, we use the pythia-14m topythia-1b models
loaded as AutoModelForSequenceClassification .sizes along with corresponding plot colors.
5.1. Robustness transfer
In practice, we often do not have the luxury of knowing
the exact attack method an adversary may employ
against our model. For practical deployments, we
therefore need adversarial training on a handful of
attacks to provide more general robustness against
other unforeseen attacks. In this subsection, we study
whether we observe this transfer in robustness between
attacks—and how model scale affects the transfer.
First, we explore whether robustness from adversarial
training transfers to a stronger attack from the same
family. To do this, we adversarially train using the
procedure described above with GCG for 10 iterations
as our training attack. We then evaluate on GCG for
30 iterations, a stronger attack. Figure 3a shows that
larger models are more robust to this in-distribution,
stronger attack. Although the transfer is imperfect—
the models do, of course, lose against 30-iteration
GCG more than against 10-iteration GCG—the perfor-
mance is much better than the undefended (fine-tuned)
models, which lose approximately 100% of the time.
This is a promising result. Yet, what happens if our
models experience an attack that is not only stronger
but also uses a different method than the one on which
they were adversarially trained? We investigate this
question by performing adversarial training against
RandomToken and evaluating against the GCGattack.
Figure 3b shows models adversarially trained on
5
RandomToken do perform better than undefended
models, though the effect is weaker. Critically, the
extent to which transfer occurs varies drastically across
models. In particular, the models with more than 100
million parameters all show strong transfer behavior,
with the attack success rate falling below 25% after
just 4 rounds of adversarial training. On the other
hand, models with fewer than 100 million parame-
ters struggle to transfer their robustness against the
RandomToken attack to the stronger GCGattack, with
the attack success rate still near 70% on the strongest
model even after 10 adversarial training rounds.
This finding is encouraging as it suggests that, for
sufficiently large models, robustness will transfer across
attacks. It appears that this transfer might be a
property that emerges with sufficient scale, similarly
to other emergent properties like the ability to use a
scratchpad for addition or the utility of instruction fine-
tuning (Wei et al., 2022). While we cannot say with
certainty that such transfer of robustness generalizes
outside the settings and attacks considered in this
work, it seems plausible that it would, and indeed, that
scaling to further orders of magnitude could unlock
more general transfer to a wider variety of attack
methodologies and strengths.
6. Conclusion
Our results demonstrate that larger Pythia models ben-
efit more from adversarial training than smaller Pythia
models across a variety of classification tasks. An
important direction for future work is to validate this
trend holds in a broader variety of settings. In particu-
lar, we plan to study generative tasks and how factors
such as task complexity affect robustness. We also
plan to investigate different model families, including
larger models.
A key application of scaling trends is to inform appro-
priate sizing of models to maximize robustness given
a fixed defender compute budget. Although larger
models are more sample efficient with a fixed num-
ber of adversarial training time steps, each adversarial
training step is more computationally expensive than
with smaller models. For example, Figure 2 shows that
performing 8 adversarial training rounds on the 17.6M
parameter model results in better robustness than per-
forming 4 adversarial training rounds on the 44.7M
parameter model, and a quick calculation shows that
it is slightly less expensive to train (see Appendix E.3).
However, using a smaller model is not always better,
since there are diminishing returns to adversarial train-
ing, with larger models appearing to converge to bemore robust.
Although scale can improve robustness, our results
make clear that it is far from the only determinant. For
example, a small adversarially trained model is more
robust than a large model fine-tuned only on clean data.
We expect that achieving robust language models will
require innovations in defense techniques as well as
scaling model pretraining and defense training. Scaling
trends both enable us to measure how far we are from
achieving robustness by scale alone and enable us to
identify defense techniques that can better leverage
scale to produce more robust models.
Acknowledgements
The authors thank ChengCheng Tan for her assistance
in formatting this document, and Daniel Pandori for his
contributions to the codebase during the early stages
of this project. Nikolaus Howe thanks the Natural
Sciences and Engineering Research Council of Canada
(NSERC) for their support via the Vanier Canada
Graduate Scholarship.
References
Sahar Abdelnabi, Kai Greshake, Shailesh Mishra,
Christoph Endres, Thorsten Holz, and Mario Fritz.
Not what you’ve signed up for: Compromising
real-world LLM-integrated applications with indi-
rect prompt injection. In AISec , page 79–90, 2023.
Jean-Baptiste Alayrac, Jonathan Uesato, Po-Sen
Huang, Alhussein Fawzi, Robert Stanforth, and
Pushmeet Kohli. Are Labels Required for Improving
Adversarial Robustness? In Advances in Neural
Information Processing Systems , volume 32. Curran
Associates, Inc., 2019. URL https://papers.
nips.cc/paper_files/paper/2019/hash/
bea6cfd50b4f5e3c735a972cf0eb8450-Abstract.
html .
Moustafa Alzantot, Bharathan Balaji, and Mani Sri-
vastava. Did you hear that? Adversarial examples
against automatic speech recognition, 2018. URL
https://arxiv.org/abs/1808.05665 .
Cem Anil, Esin Durmus, Mrinank Sharma, Joe Benton,
Sandipan Kundu, Joshua Batson, Nina Rimsky,
Meg Tong, Jesse Mu, Daniel Ford, Francesco
Mosconi, Rajashree Agrawal, Rylan Schaeffer,
Naomi Bashkansky, Samuel Svenningsen, Mike
Lambert, Ansh Radhakrishnan, Carson Denison,
Evan J Hubinger, Yuntao Bai, Trenton Bricken,
6
Timothy Maxwell, Nicholas Schiefer, Jamie Sully,
Alex Tamkin, Tamera Lanham, Karina Nguyen,
Tomasz Korbak, Jared Kaplan, Deep Ganguli,
Samuel R Bowman, Ethan Perez, Roger Grosse,
and David Duvenaud. Many-shot Jailbreaking,
2024. URL https://www-cdn.anthropic.com/
af5633c94ed2beb282f6a53c595eb437e8e7b630/
Many_Shot_Jailbreaking__2024_04_02_0936.
pdf.
Anthropic. Tool use (function calling), 2024. URL
https://archive.ph/EqXCz .
Brian R. Bartoldson, James Diffenderfer, Konstanti-
nos Parasyris, and Bhavya Kailkhura. Adversar-
ial Robustness Limits via Scaling-Law and Human-
Alignment Studies, April 2024. URL http://arxiv.
org/abs/2404.09349 .
Stella Biderman, Hailey Schoelkopf, Quentin Gregory
Anthony, Herbie Bradley, Kyle O’Brien, Eric Halla-
han, Mohammad Aflah Khan, Shivanshu Purohit,
USVSN Sai Prashanth, Edward Raff, et al. Pythia:
A suite for analyzing large language models across
training and scaling. In International Conference on
Machine Learning , pages 2397–2430. PMLR, 2023.
Yair Carmon, Aditi Raghunathan, Ludwig Schmidt,
Percy Liang, and John C. Duchi. Unlabeled Data Im-
proves Adversarial Robustness, January 2022. URL
http://arxiv.org/abs/1905.13736 .
Canyu Chen and Kai Shu. Can LLM-generated misin-
formation be detected? In International Conference
on Learning Representations , 2024.
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, Alex Ray, Raul Puri, Gretchen
Krueger, Michael Petrov, Heidy Khlaaf, Girish Sas-
try, Pamela Mishkin, Brooke Chan, Scott Gray,
Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz
Kaiser, Mohammad Bavarian, Clemens Winter,
Philippe Tillet, Felipe Petroski Such, Dave Cum-
mings, Matthias Plappert, Fotios Chantzis, Eliza-
beth Barnes, Ariel Herbert-Voss, William Hebgen
Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie
Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain,
William Saunders, Christopher Hesse, Andrew N.
Carr, Jan Leike, Josh Achiam, Vedant Misra, Evan
Morikawa, Alec Radford, Matthew Knight, Miles
Brundage, Mira Murati, Katie Mayer, Peter Welin-
der, Bob McGrew, Dario Amodei, Sam McCandlish,
Ilya Sutskever, and Wojciech Zaremba. EvaluatingLarge Language Models Trained on Code, July 2021.
URL http://arxiv.org/abs/2107.03374 .
Moustapha M Cisse, Yossi Adi, Natalia Neverova,
and Joseph Keshet. Houdini: Fooling deep
structured visual and speech recognition mod-
els with adversarial examples. In Advances in
Neural Information Processing Systems , vol-
ume 30, 2017. URL https://proceedings.
neurips.cc/paper_files/paper/2017/hash/
d494020ff8ec181ef98ed97ac3f25453-Abstract.
html .
Edoardo Debenedetti, Zishen Wan, Maksym An-
driushchenko, Vikash Sehwag, Kshitij Bhardwaj, and
Bhavya Kailkhura. Scaling Compute Is Not All You
Need for Adversarial Robustness, December 2023.
URL http://arxiv.org/abs/2312.13131 .
Deep Ganguli, Liane Lovitt, Jackson Kernion, Amanda
Askell, Yuntao Bai, Saurav Kadavath, Ben Mann,
Ethan Perez, Nicholas Schiefer, Kamal Ndousse,
Andy Jones, Sam Bowman, Anna Chen, Tom Con-
erly, Nova DasSarma, Dawn Drain, Nelson El-
hage, Sheer El-Showk, Stanislav Fort, Zac Hatfield-
Dodds, Tom Henighan, Danny Hernandez, Tristan
Hume, Josh Jacobson, Scott Johnston, Shauna
Kravec, Catherine Olsson, Sam Ringer, Eli Tran-
Johnson, Dario Amodei, Tom Brown, Nicholas
Joseph, Sam McCandlish, Chris Olah, Jared Ka-
plan, and Jack Clark. Red Teaming Language Mod-
els to Reduce Harms: | methods such as
indirect prompt injections (Abdelnabi et al., 2023) to
exploit LLM-driven applications without any awareness
or participation by the user.
A key question is whether future, more capable sys-
tems will naturally become more robust, or if this will
instead require a dedicated safety effort. Although
current attacks are concerning, the risks could grow
still greater with future models capable of more danger-
ous actions, such as assisting with biological weapon
development (Mouton et al., 2023), or with greater
affordances to interact with the world (Sharkey et al.,
2023), such as a virtual assistant for a CEO of a major
company. Prior work has found that superhuman Go
systems (Wang et al., 2023) are vulnerable to attack,
demonstrating that impressive capabilities do not guar-
antee robustness. However, work has also found that
scaling unlabeled pretraining data (Hendrycks et al.,
2019; Carmon et al., 2022; Alayrac et al., 2019) and
model size (Xie and Yuille, 2019; Huang et al., 2023)
improves adversarial robustness in computer vision.
To answer this question, we conduct an empirical
investigation into scaling trends for the adversarial
robustness of language models. These trends enable us
to forecast the robustness of future models, and give us
insight into how the offense-defense balance might shift
over time. For example, does the cost of conducting
an attack against more capable models grow faster
1arXiv:2407.18213v1 [cs.LG] 25 Jul 2024
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, GCG attack
Figure 1: Attack success rate ( y-axis) of GCGagainst Pythia models of different sizes ( x-axis) fine-tuned on
theSpam (left) and IMBD (right ) tasks. We run three fine-tuning seeds for each model, plotting the
median attack success rate and shading the range between the min and max. We observe significant
attack success rate variability across model sizes: median robustness does not improve monotonically
with scale.
or slower than the defender’s cost of training those
models?
Concretely, we investigate the robustness of Pythia
models ranging from 14M to 12B parameter (Biderman
et al., 2023) against two attacks: the random tokens
baseline and the state-of-the-art greedy coordinate
gradient attack. We test these models in various
simple classification tasks where our models achieve
high accuracy on clean (non-adversarial) data.
We first evaluate these pretrained models fine-tuned
only on clean data. Larger models tend to be more
resistant to attack, but the effect is weak and noisy
(Figure 1). By contrast, a clearer scaling trend emerges
for models adversarially trained against examples of
attacks (Figure 2). Larger models are both more
sample efficient, becoming more robust with fewer
examples, and converge to be more robust given a
sufficient number of examples. Moreover, adversarial
training against one attack transfers protection to
similar attacks, with the transfer being stronger for
larger models (Figure 3b).
2. Related Work
Adversarial examples were first identified in image clas-
sifiers (Szegedy et al., 2014), but have since been found
for systems performing image captioning (Xu et al.,
2019; Zhang et al., 2020), speech recognition (Cisse
et al., 2017; Alzantot et al., 2018; Sch¨ onherr et al.,
2018), and reinforcement learning (Huang et al., 2017;
Gleave et al., 2020; Ilahi et al., 2022). Moreover, arange of adversarial threat models (Gilmer et al., 2018)
give rise to viable attacks.
Most recently, many qualitatively different vulner-
abilities have been found in language models, from
human-understandable “jailbreaks” (Wei et al., 2023)
to seemingly gibberish adversarial suffixes (Wallace
et al., 2021; Zou et al., 2023). Simple methods such
as perplexity filtering and paraphrasing defend against
some of these attacks (Jain et al., 2023). However,
these defenses can easily be bypassed by more sophisti-
cated methods (Zhu et al., 2023). Adversarial training
shows more promise as a defense (Ziegler et al., 2022),
and is the focus of our analysis.
The determinants of adversarial robustness have been
well-studied in computer vision. One line of scholarship
proposes a fundamental tradeoff between robustness
and accuracy (Tsipras et al., 2019): exploitable mod-
els are simply relying on non-robust features (Ilyas
et al., 2019), which improve training performance
but hurt robustness. Other work has emphasized
what does improve robustness. Scaling unlabeled pre-
training data (Hendrycks et al., 2019; Carmon et al.,
2022; Alayrac et al., 2019), model depth (Xie and
Yuille, 2019) and model width (Huang et al., 2023)
improves adversarial robustness in computer vision.
However, other work shows that computer vision ad-
versarial robustness scales too slowly to be a full so-
lution (Debenedetti et al., 2023; Bartoldson et al.,
2024).
Language model scaling laws (Hestness et al., 2017;
Rosenfeld et al., 2019; Kaplan et al., 2020; Hoff-
2
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attackFigure 2: Attack success rate ( y-axis) of GCGagainst Pythia models of varying sizes (line color) on Spam (left)
andIMDB (right ) during adversarial training ( x-axis) against GCGover 10 rounds ( top) and over
30 rounds ( bottom ). See Figure 16 for a zoomed-in view of the final 10 rounds of the 30-round
adversarial training. We plot the median over three seeds and shade the region between the min
and max. We observe larger models are more sample efficient, and appear to converge to a higher
robustness (lower attack success rate).
mann et al., 2022) have shown that increasing com-
pute improves performance across many tasks and
domains (Chen et al., 2021; Hernandez et al., 2021).
However, scaling does not solve all problems (Lin et al.,
2022; McKenzie et al., 2023). There has been only
limited work on scaling laws for adversarial robustness
in language models, with mixed | Section not found | Section not found | Section not found | results. Ganguli et al.
(2022) show that LLMs become harder to attack with
scale—but Anil et al. (2024) find that some attacks
become more successful with scale.
3. Experimental Methodology
We test models in the binary classification setting,
as it is the simplest context in which to study LLM
robustness. Crucially, binary classification allows usto measure robustness by the attack success rate ,
defined as the proportion of examples correctly clas-
sified by the model before attack that are incorrectly
classified after attack.1We adapt pretrained models
for classification by replacing the unembedding layer
with a randomly initialized classification head, and
then fine-tune the models on each task.
Tasks We consider four tasks in our experiments,
the latter two developed by us for this project:
•Spam (Metsis et al., 2006): Given the subject and
body of an email, is it spam or not?
•IMDB (Maas et al., 2011): Given a movie review,
1We assume that the attack does not, in fact, change the
ground truth label of the datapoint. This is guaranteed by
construction for some of our simple procedurally generated
tasks, and was manually validated on a random sample of
datapoints in other tasks.
3
is the sentiment positive or negative?
•PasswordMatch : Given two strings in the prompt,
are they exactly equal?
•WordLength : Given two words in the prompt, is
the first word shorter than the second?
Spam andIMDB were chosen as standard natural lan-
guage processing classification tasks. PasswordMatch
was inspired by TensorTrust (Toyer et al., 2023), and
WordLength by the RuLES dataset (Mu et al., 2023).
Both PasswordMatch andWordLength were designed
to be easily procedurally generated and have ground
truth labels that can be checked algorithmically. For
brevity, we report on Spam andIMDB in the main text,
with plots for other tasks deferred to Appendices D
and E. We provide example datapoints and details
about the datasets in Appendix B.
Models We test the Pythia model family (Biderman
et al., 2023). These models range in size from 14M to
12B parameters (or 7.6M to 11.6B when used with a
classification head). All models were trained to predict
the next token on the same dataset following the same
training protocol, allowing us to isolate model scale
from other confounding factors.
Attacks Our attacks append an adversarial suffix
ofNtokens to the prompt. We use two different
procedures to generate this adversarial suffix: a random
token baseline ( RandomToken ) and the state-of-the-
art greedy coordinate gradient attack ( GCG; Zou et al.,
2023). RandomToken was chosen due to its simplicity.
GCG was chosen as it is currently one of the most
effective attacks on language models.
In the RandomToken baseline, the Ntokens are cho-
sen uniformly at random from the model’s vocabulary.
We evaluate the model on the attacked text and then
repeat the process with another sample of Nrandom
tokens until the model is successfully attacked or an
appointed budget for model calls is exhausted.
InGCG(Zou et al., 2023), the Ntokens are initialized
arbitrarily and then greedily optimized over multiple
rounds. In each round, the gradient of the loss function
with respect to the attack tokens is computed. This
gradient is used to compute a set of promising single-
token modifications, from which the best candidate
is selected and used in the next round. To make this
attack work in the classification setting, we minimize
the cross-entropy loss between the predicted label and
the target label.
In our experiments, we always use N= 10 tokens.
For more details about the attacks and hyperparame-
ters used, see Appendix C.4. Fine-tuning
Figure 1 shows the robustness of fine-tuned models
against the GCGattack. The attack is generally less
successful on larger models, but model size alone does
not explain all the variance in attack success rate.
We observe similarly large random variation in attack
success across model sizes on other tasks and with
other attacks; for more details, see Appendix D.2.
As described in Section 3, we use the Pythia mod-
els, which range from 7.6M to 11.6B parameters after
replacing the unembedding matrix with a classifica-
tion head.2We fine-tune all models for a single epoch
with default hyperparameters from HuggingFace Trans-
formers (Wolf et al., 2019), except for the learning
rate which we set to 1e−5. All models reach >83%
accuracy on all tasks, with larger models generally
performing better (see Appendix D.1 for the final val-
idation performance of all models on all tasks). We
then evaluate the fine-tuned models against adversarial
attacks on an unseen validation dataset.
To understand the source of the variability in model
robustness shown by our experiments, we varied 1)
the pretraining checkpoint,3and 2) the random seeds
used to initialize the classification head before fine-
tuning. Both factors led to significant variability in
model robustness, with pretraining checkpoint con-
tributing significantly more variability. The variability
was comparable or greater than that of an order of
magnitude of model scaling, indicating that out-of-the-
box robustness on a given task is heavily influenced by
the randomness of the pretraining procedure itself.
This initial result suggests that we cannot rely on
scale alone to solve the problem of robustness. How-
ever, in practice, we would apply a defense to a model
prior to deploying it in a security-critical setting. In the
following section, we consider whether scale enables
defenses to more effectively improve model robustness.
5. Adversarial training
In this section, we explore how model size impacts
robustness when performing adversarial training. Fig-
ure 2 evaluates the robustness of Pythia models to
theGCGattack when adversarially trained against the
same attack. We see a much cleaner trend than in the
fine-tuning only case: larger models gain robustness
2In all figures, we report the actual parameter count of the
classification model, and not the pretrained model it was
derived from.
3The Pythia models provide checkpoints from earlier stages of
pretraining. We used various checkpoints from the final 10%
of pretraining as a starting point for fine-tuning.
4
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG train, GCG 30 its eval
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M(a)Adversarial training against 10-iteration GCG, with eval-
uation against 30-iteration GCG. All models show some
transfer of their defense to this stronger attack, with
larger models doing so more effectively.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RT train, GCG eval(b)Adversarial training against 10-iteration RandomToken ,
with evaluation against 10-iteration GCG.≥100M pa-
rameter models show strong defense transfer, while
smaller models struggle against the new attack.
Figure 3: Attack success rate ( y-axis) against Pythia models of varying sizes (line color) during adversarial
training ( x-axis).
more quickly and converge to be more robust than
smaller models. These results suggest that model size
is a strong predictor of robustness—so long as the
model is explicitly optimized for robustness. We ob-
serve similar behavior across the other two datasets
and two attacks; see Appendix E for these plots, in-
cluding extensions for up to 30 adversarial training
rounds.
We perform adversarial training by iteratively training
our model on a training dataset, evaluating the model
on attacked examples, and then adding successful at-
tack examples to the training dataset. Simultaneously,
we evaluate model performance on a held-out attacked
validation dataset. This procedure is illustrated in Fig-
ure 12.
In our experiments, we initialize the training dataset
to consist of 2000 clean examples, and add 200 ad-
versarial examples to the training dataset each round.
We repeat the train-attack-add loop 30 times (here we
only show the first 10 rounds; see Appendix E for the
full 30-round plots). Since adversarial examples are
only added after the first training round, the models
here were trained for a single epoch on the 2000 clean
datapoints before being adversarially attacked.
We perform adversarial training on Pythia models
ranging from 7.6 to 909 million parameters after re-
placing the unembedding layer with a classification
head.4Table 1 in Appendix A enumerates all model
4Specifically, we use the pythia-14m topythia-1b models
loaded as AutoModelForSequenceClassification .sizes along with corresponding plot colors.
5.1. Robustness transfer
In practice, we often do not have the luxury of knowing
the exact attack method an adversary may employ
against our model. For practical deployments, we
therefore need adversarial training on a handful of
attacks to provide more general robustness against
other unforeseen attacks. In this subsection, we study
whether we observe this transfer in robustness between
attacks—and how model scale affects the transfer.
First, we explore whether robustness from adversarial
training transfers to a stronger attack from the same
family. To do this, we adversarially train using the
procedure described above with GCG for 10 iterations
as our training attack. We then evaluate on GCG for
30 iterations, a stronger attack. Figure 3a shows that
larger models are more robust to this in-distribution,
stronger attack. Although the transfer is imperfect—
the models do, of course, lose against 30-iteration
GCG more than against 10-iteration GCG—the perfor-
mance is much better than the undefended (fine-tuned)
models, which lose approximately 100% of the time.
This is a promising result. Yet, what happens if our
models experience an attack that is not only stronger
but also uses a different method than the one on which
they were adversarially trained? We investigate this
question by performing adversarial training against
RandomToken and evaluating against the GCGattack.
Figure 3b shows models adversarially trained on
5
RandomToken do perform better than undefended
models, though the effect is weaker. Critically, the
extent to which transfer occurs varies drastically across
models. In particular, the models with more than 100
million parameters all show strong transfer behavior,
with the attack success rate falling below 25% after
just 4 rounds of adversarial training. On the other
hand, models with fewer than 100 million parame-
ters struggle to transfer their robustness against the
RandomToken attack to the stronger GCGattack, with
the attack success rate still near 70% on the strongest
model even after 10 adversarial training rounds.
This finding is encouraging as it suggests that, for
sufficiently large models, robustness will transfer across
attacks. It appears that this transfer might be a
property that emerges with sufficient scale, similarly
to other emergent properties like the ability to use a
scratchpad for addition or the utility of instruction fine-
tuning (Wei et al., 2022). While we cannot say with
certainty that such transfer of robustness generalizes
outside the settings and attacks considered in this
work, it seems plausible that it would, and indeed, that
scaling to further orders of magnitude could unlock
more general transfer to a wider variety of attack
methodologies and strengths.
6. Conclusion
Our results demonstrate that larger Pythia models ben-
efit more from adversarial training than smaller Pythia
models across a variety of classification tasks. An
important direction for | Section not found | Section not found | Section not found | Section not found | Section not found | future work is to validate this
trend holds in a broader variety of settings. In particu-
lar, we plan to study generative tasks and how factors
such as task complexity affect robustness. We also
plan to investigate different model families, including
larger models.
A key application of scaling trends is to inform appro-
priate sizing of models to maximize robustness given
a fixed defender compute budget. Although larger
models are more sample efficient with a fixed num-
ber of adversarial training time steps, each adversarial
training step is more computationally expensive than
with smaller models. For example, Figure 2 shows that
performing 8 adversarial training rounds on the 17.6M
parameter model results in better robustness than per-
forming 4 adversarial training rounds on the 44.7M
parameter model, and a quick calculation shows that
it is slightly less expensive to train (see Appendix E.3).
However, using a smaller model is not always better,
since there are diminishing returns to adversarial train-
ing, with larger models appearing to converge to bemore robust.
Although scale can improve robustness, our results
make clear that it is far from the only determinant. For
example, a small adversarially trained model is more
robust than a large model fine-tuned only on clean data.
We expect that achieving robust language models will
require innovations in defense techniques as well as
scaling model pretraining and defense training. Scaling
trends both enable us to measure how far we are from
achieving robustness by scale alone and enable us to
identify defense techniques that can better leverage
scale to produce more robust models.
Acknowledgements
The authors thank ChengCheng Tan for her assistance
in formatting this document, and Daniel Pandori for his
contributions to the codebase during the early stages
of this project. Nikolaus Howe thanks the Natural
Sciences and Engineering Research Council of Canada
(NSERC) for their support via the Vanier Canada
Graduate Scholarship. | Conclusion
Our results demonstrate that larger Pythia models ben-
efit more from adversarial training than smaller Pythia
models across a variety of classification tasks. An
important direction for future work is to validate this
trend holds in a broader variety of settings. In particu-
lar, we plan to study generative tasks and how factors
such as task complexity affect robustness. We also
plan to investigate different model families, including
larger models.
A key application of scaling trends is to inform appro-
priate sizing of models to maximize robustness given
a fixed defender compute budget. Although larger
models are more sample efficient with a fixed num-
ber of adversarial training time steps, each adversarial
training step is more computationally expensive than
with smaller models. For example, Figure 2 shows that
performing 8 adversarial training rounds on the 17.6M
parameter model results in better robustness than per-
forming 4 adversarial training rounds on the 44.7M
parameter model, and a quick calculation shows that
it is slightly less expensive to train (see Appendix E.3).
However, using a smaller model is not always better,
since there are diminishing returns to adversarial train-
ing, with larger models appearing to converge to bemore robust.
Although scale can improve robustness, our results
make clear that it is far from the only determinant. For
example, a small adversarially trained model is more
robust than a large model fine-tuned only on clean data.
We expect that achieving robust language models will
require innovations in defense techniques as well as
scaling model pretraining and defense training. Scaling
trends both enable us to measure how far we are from
achieving robustness by scale alone and enable us to
identify defense techniques that can better leverage
scale to produce more robust models.
Acknowledgements
The authors thank ChengCheng Tan for her assistance
in formatting this document, and Daniel Pandori for his
contributions to the codebase during the early stages
of this project. Nikolaus Howe thanks the Natural
Sciences and Engineering Research Council of Canada
(NSERC) for their support via the Vanier Canada
Graduate Scholarship. | Section not found | Section not found | References
Sahar Abdelnabi, Kai Greshake, Shailesh Mishra,
Christoph Endres, Thorsten Holz, and Mario Fritz.
Not what you’ve signed up for: Compromising
real-world LLM-integrated applications with indi-
rect prompt injection. In AISec , page 79–90, 2023.
Jean-Baptiste Alayrac, Jonathan Uesato, Po-Sen
Huang, Alhussein Fawzi, Robert Stanforth, and
Pushmeet Kohli. Are Labels Required for Improving
Adversarial Robustness? In Advances in Neural
Information Processing Systems , volume 32. Curran
Associates, Inc., 2019. URL https://papers.
nips.cc/paper_files/paper/2019/hash/
bea6cfd50b4f5e3c735a972cf0eb8450-Abstract.
html .
Moustafa Alzantot, Bharathan Balaji, and Mani Sri-
vastava. Did you hear that? Adversarial examples
against automatic speech recognition, 2018. URL
https://arxiv.org/abs/1808.05665 .
Cem Anil, Esin Durmus, Mrinank Sharma, Joe Benton,
Sandipan Kundu, Joshua Batson, Nina Rimsky,
Meg Tong, Jesse Mu, Daniel Ford, Francesco
Mosconi, Rajashree Agrawal, Rylan Schaeffer,
Naomi Bashkansky, Samuel Svenningsen, Mike
Lambert, Ansh Radhakrishnan, Carson Denison,
Evan J Hubinger, Yuntao Bai, Trenton Bricken,
6
Timothy Maxwell, Nicholas Schiefer, Jamie Sully,
Alex Tamkin, Tamera Lanham, Karina Nguyen,
Tomasz Korbak, Jared Kaplan, Deep Ganguli,
Samuel R Bowman, Ethan Perez, Roger Grosse,
and David Duvenaud. Many-shot Jailbreaking,
2024. URL https://www-cdn.anthropic.com/
af5633c94ed2beb282f6a53c595eb437e8e7b630/
Many_Shot_Jailbreaking__2024_04_02_0936.
pdf.
Anthropic. Tool use (function calling), 2024. URL
https://archive.ph/EqXCz .
Brian R. Bartoldson, James Diffenderfer, Konstanti-
nos Parasyris, and Bhavya Kailkhura. Adversar-
ial Robustness Limits via Scaling-Law and Human-
Alignment Studies, April 2024. URL http://arxiv.
org/abs/2404.09349 .
Stella Biderman, Hailey Schoelkopf, Quentin Gregory
Anthony, Herbie Bradley, Kyle O’Brien, Eric Halla-
han, Mohammad Aflah Khan, Shivanshu Purohit,
USVSN Sai Prashanth, Edward Raff, et al. Pythia:
A suite for analyzing large language models across
training and scaling. In International Conference on
Machine Learning , pages 2397–2430. PMLR, 2023.
Yair Carmon, Aditi Raghunathan, Ludwig Schmidt,
Percy Liang, and John C. Duchi. Unlabeled Data Im-
proves Adversarial Robustness, January 2022. URL
http://arxiv.org/abs/1905.13736 .
Canyu Chen and Kai Shu. Can LLM-generated misin-
formation be detected? In International Conference
on Learning Representations , 2024.
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, Alex Ray, Raul Puri, Gretchen
Krueger, Michael Petrov, Heidy Khlaaf, Girish Sas-
try, Pamela Mishkin, Brooke Chan, Scott Gray,
Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz
Kaiser, Mohammad Bavarian, Clemens Winter,
Philippe Tillet, Felipe Petroski Such, Dave Cum-
mings, Matthias Plappert, Fotios Chantzis, Eliza-
beth Barnes, Ariel Herbert-Voss, William Hebgen
Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie
Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain,
William Saunders, Christopher Hesse, Andrew N.
Carr, Jan Leike, Josh Achiam, Vedant Misra, Evan
Morikawa, Alec Radford, Matthew Knight, Miles
Brundage, Mira Murati, Katie Mayer, Peter Welin-
der, Bob McGrew, Dario Amodei, Sam McCandlish,
Ilya Sutskever, and Wojciech Zaremba. EvaluatingLarge Language Models Trained on Code, July 2021.
URL http://arxiv.org/abs/2107.03374 .
Moustapha M Cisse, Yossi Adi, Natalia Neverova,
and Joseph Keshet. Houdini: Fooling deep
structured visual and speech recognition mod-
els with adversarial examples. In Advances in
Neural Information Processing Systems , vol-
ume 30, 2017. URL https://proceedings.
neurips.cc/paper_files/paper/2017/hash/
d494020ff8ec181ef98ed97ac3f25453-Abstract.
html .
Edoardo Debenedetti, Zishen Wan, Maksym An-
driushchenko, Vikash Sehwag, Kshitij Bhardwaj, and
Bhavya Kailkhura. Scaling Compute Is Not All You
Need for Adversarial Robustness, December 2023.
URL http://arxiv.org/abs/2312.13131 .
Deep Ganguli, Liane Lovitt, Jackson Kernion, Amanda
Askell, Yuntao Bai, Saurav Kadavath, Ben Mann,
Ethan Perez, Nicholas Schiefer, Kamal Ndousse,
Andy Jones, Sam Bowman, Anna Chen, Tom Con-
erly, Nova DasSarma, Dawn Drain, Nelson El-
hage, Sheer El-Showk, Stanislav Fort, Zac Hatfield-
Dodds, Tom Henighan, Danny Hernandez, Tristan
Hume, Josh Jacobson, Scott Johnston, Shauna
Kravec, Catherine Olsson, Sam Ringer, Eli Tran-
Johnson, Dario Amodei, Tom Brown, Nicholas
Joseph, Sam McCandlish, Chris Olah, Jared Ka-
plan, and Jack Clark. Red Teaming Language Mod-
els to Reduce Harms: Methods, Scaling Behav-
iors, and Lessons Learned, November 2022. URL
http://arxiv.org/abs/2209.07858 .
Leo Gao, Stella Biderman, Sid Black, Laurence Gold-
ing, Travis Hoppe, Charles Foster, Jason Phang,
Horace He, Anish Thite, Noa Nabeshima, et al. The
Pile: An 800gb dataset of diverse text for language
modeling. arXiv preprint arXiv:2101.00027 , 2020.
Justin Gilmer, Luke Metz, Fartash Faghri, Samuel S.
Schoenholz, Maithra Raghu, Martin Wattenberg,
and Ian Goodfellow. Adversarial Spheres, September
2018. URL http://arxiv.org/abs/1801.02774 .
Adam Gleave, Michael Dennis, Cody Wild, Neel Kant,
Sergey Levine, and Stuart Russell. Adversarial poli-
cies: Attacking deep reinforcement learning. In In-
ternational Conference on Learning Representations ,
2020.
Google. Function calling — Google AI for developers,
2024. URL https://archive.ph/YGJHJ .
7
Dan Hendrycks, Kimin Lee, and Mantas Mazeika. Us-
ing Pre-Training Can Improve Model Robustness
and Uncertainty. In International Conference on
Machine Learning , pages 2712–2721. PMLR, May
2019. URL https://proceedings.mlr.press/
v97/hendrycks19a.html . ISSN: 2640-3498.
Dan Hendrycks, Collin Burns, Steven Basart, Andy
Zou, Mantas Mazeika, Dawn Song, and Jacob Stein-
hardt. Measuring massive multitask language under-
standing. In International Conference on Learning
Representations , 2021. URL https://openreview.
net/forum?id=d7KBjmI3GmQ .
Danny Hernandez, Jared Kaplan, Tom Henighan, and
Sam McCandlish. Scaling Laws for Transfer, Febru-
ary 2021. URL http://arxiv.org/abs/2102.
01293 .
Joel Hestness, Sharan Narang, Newsha Ardalani, Gre-
gory Diamos, Heewoo Jun, Hassan Kianinejad,
Md Mostofa Ali Patwary, Yang Yang, and Yanqi
Zhou. Deep Learning Scaling is Predictable, Empir-
ically, December 2017. URL http://arxiv.org/
abs/1712.00409 .
Jordan Hoffmann, Sebastian Borgeaud, Arthur Men-
sch, Elena Buchatskaya, Trevor Cai, Eliza Ruther-
ford, Diego de Las Casas, Lisa Anne Hendricks, Jo-
hannes Welbl, Aidan Clark, Tom Hennigan, Eric
Noland, Katie Millican, George van den Driess-
che, Bogdan Damoc, Aurelia Guy, Simon Osin-
dero, Karen Simonyan, Erich Elsen, Jack W. Rae,
Oriol Vinyals, and Laurent Sifre. Training Compute-
Optimal Large Language Models, March 2022. URL
http://arxiv.org/abs/2203.15556 .
Krystal Hu. ChatGPT sets record for fastest-growing
user base – analyst note. Reuters , 2023.
Sandy H. Huang, Nicolas Papernot, Ian J. Goodfellow,
Yan Duan, and Pieter Abbeel. Adversarial attacks on
neural network policies. arXiv:1702.02284v1 [cs.LG],
2017.
Shihua Huang, Zhichao Lu, Kalyanmoy Deb, and
Vishnu Naresh Boddeti. Revisiting Residual Net-
works for Adversarial Robustness. In IEEE/CVF
Conference on Computer Vision and Pattern Recog-
nition , pages 8202–8211, Vancouver, BC, Canada,
June 2023. IEEE. ISBN 9798350301298. doi:
10.1109/CVPR52729.2023.00793 . URL https://
ieeexplore.ieee.org/document/10204909/ .
Inaam Ilahi, Muhammad Usama, Junaid Qadir,
Muhammad Umar Janjua, Ala Al-Fuqaha, Dinh ThaiHoang, and Dusit Niyato. Challenges and counter-
measures for adversarial attacks on deep reinforce-
ment learning. IEEE TAI , 3(2):90–109, 2022.
Andrew Ilyas, Shibani Santurkar, Dimitris Tsipras,
Logan Engstrom, Brandon Tran, and Aleksander
Madry. Adversarial Examples Are Not Bugs,
They Are Features. In Advances in Neural
Information Processing Systems , volume 32. Curran
Associates, Inc., 2019. URL https://papers.
nips.cc/paper_files/paper/2019/hash/
e2c420d928d4bf8ce0ff2ec19b371514-Abstract.
html .
Neel Jain, Avi Schwarzschild, Yuxin Wen, Gowthami
Somepalli, John Kirchenbauer, Ping yeh Chiang,
Micah Goldblum, Aniruddha Saha, Jonas Geiping,
and Tom Goldstein. Baseline defenses for adversarial
attacks against aligned language models, 2023. URL
https://arxiv.org/abs/2309.00614 .
Jared Kaplan, Sam McCandlish, Tom Henighan,
Tom B. Brown, Benjamin Chess, Rewon Child, Scott
Gray, Alec Radford, Jeffrey Wu, and Dario Amodei.
Scaling Laws for Neural Language Models, January
2020. URL http://arxiv.org/abs/2001.08361 .
Megan Kinniment, Lucas Jun Koba Sato, Haox-
ing Du, Brian Goodrich, Max Hasin, Lawrence
Chan, Luke Harold Miles, Tao R. Lin, Hjalmar
Wijk, Joel Burget, Aaron Ho, Elizabeth Barnes,
and Paul Christiano. Evaluating language-model
agents on realistic autonomous tasks, 2024. URL
https://arxiv.org/abs/2312.11671 .
Stephanie Lin, Jacob Hilton, and Owain Evans. Truth-
fulQA: Measuring How Models Mimic Human False-
hoods, May 2022. URL http://arxiv.org/abs/
2109.07958 .
Andrew L. Maas, Raymond E. Daly, Peter T. Pham,
Dan Huang, Andrew Y. Ng, and Christopher Potts.
Learning word vectors for sentiment analysis. In
Association for Computational Linguistics: Human
Language Technologies , pages 142–150, Portland,
Oregon, USA, June 2011. Association for Computa-
tional Linguistics. URL http://www.aclweb.org/
anthology/P11-1015 .
Ian R. McKenzie, Alexander Lyzhov, Michael Martin
Pieler, Alicia Parrish, Aaron Mueller, Ameya Prabhu,
Euan McLean, Xudong Shen, Joe Cavanagh, An-
drew George Gritsevskiy, Derik Kauffman, Aaron T.
Kirtland, Zhengping Zhou, Yuhui Zhang, Sicong
Huang, Daniel Wurgaft, Max Weiss, Alexis Ross,
8
Gabriel Recchia, Alisa Liu, Jiacheng Liu, Tom Tseng,
Tomasz Korbak, Najoung Kim, Samuel R. Bowman,
and Ethan Perez. Inverse Scaling: When Bigger
Isn’t Better. Transactions on Machine Learning Re-
search , June 2023. ISSN 2835-8856. URL https:
//openreview.net/forum?id=DwgRm72GQF .
Vangelis Metsis, Ion Androutsopoulos, and Georgios
Paliouras. Spam Filtering with Naive Bayes -
Which Naive Bayes? In Conference on Email and
Anti-Spam , 2006. URL https://www2.aueb.gr/
users/ion/docs/ceas2006_paper.pdf .
Christopher A. Mouton, Caleb Lucas, and Ella Guest.
The Operational Risks of AI in Large-Scale Bio-
logical Attacks: A Red-Team Approach . RAND
Corporation, 2023.
Norman Mu, Sarah Chen, Zifan Wang, Sizhe Chen,
David Karamardian, Lulwa Aljeraisy, Basel Alomair,
Dan Hendrycks, and David Wagner. Can LLMs
follow simple rules? arXiv , 2023. URL https:
//arxiv.org/abs/2311.04235 .
OpenAI. Assistants API documentation, 2023. URL
https://archive.ph/8Az8d .
David Rein, Betty Li Hou, Asa Cooper Stickland, Jack-
son Petty, Richard Yuanzhe Pang, Julien Dirani,
Julian Michael, and Samuel R. Bowman. GPQA: A
graduate-level google-proof q&a benchmark, 2023.
URL https://arxiv.org/abs/2311.12022 .
Toran Bruce Richards. Auto-gpt: An autonomous
GPT-4 experiment, 2024. URL https://github.
com/Significant-Gravitas/AutoGPT/ .
Jonathan S. Rosenfeld, Amir Rosenfeld, Yonatan Be-
linkov, and Nir Shavit. A Constructive Prediction of
the Generalization Error Across Scales, December
2019. URL http://arxiv.org/abs/1909.12673 .
Lea Sch¨ onherr, Katharina Kohls, Steffen Zeiler,
Thorsten Holz, and Dorothea Kolossa. Adversar-
ial attacks against automatic speech recognition
systems via psychoacoustic hiding, 2018.
Lee Sharkey, Cl ´ ıodhna N ´ ı Ghuidhir, Dan Braun, J´ er´ emy
Scheurer, Mikita Balesni, Lucius Bushnaq, Charlotte
Stix, and Marius Hobbhahn. A causal framework for
AI regulation and auditing. Technical report, Apollo
Research, 2023.
Giovanni Spitale, Nikola Biller-Andorno, and Federico
Germani. AI model GPT-3 (dis)informs us better
than humans. Science Advances , 9(26), 2023.Christian Szegedy, Wojciech Zaremba, Ilya Sutskever,
Joan Bruna, Dumitru Erhan, Ian Goodfellow, and
Rob Fergus. Intriguing properties of neural networks,
2014. URL https://arxiv.org/abs/1312.6199 .
Sam Toyer, Olivia Watkins, Ethan Adrian Mendes,
Justin Svegliato, Luke Bailey, Tiffany Wang, Isaac
Ong, Karim Elmaaroufi, Pieter Abbeel, Trevor Dar-
rell, Alan Ritter, and Stuart Russell. Tensor Trust:
Interpretable prompt injection attacks from an on-
line game, 2023. URL https://arxiv.org/abs/
2311.01011 .
Dimitris Tsipras, Shibani Santurkar, Logan Engstrom,
Alexander Turner, and Aleksander Madry. Robust-
ness may be at odds with accuracy. In International
Conference on Learning Representations , 2019. URL
https://arxiv.org/abs/1805.12152 .
Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner,
and Sameer Singh. Universal Adversarial Triggers
for Attacking and Analyzing NLP, January 2021.
URL http://arxiv.org/abs/1908.07125 .
Tony Tong Wang, Adam Gleave, Tom Tseng, Kellin
Pelrine, Nora Belrose, Joseph Miller, Michael D
Dennis, Yawen Duan, Viktor Pogrebniak, Sergey
Levine, and Stuart Russell. Adversarial policies beat
superhuman Go AIs. In International Conference
on Machine Learning , pages 35655–35739. PMLR,
2023.
Alexander Wei, Nika Haghtalab, and Jacob Steinhardt.
Jailbroken: How Does LLM Safety Training Fail?,
July 2023. URL http://arxiv.org/abs/2307.
02483 .
Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel,
Barret Zoph, Sebastian Borgeaud, Dani Yogatama,
Maarten Bosma, Denny Zhou, Donald Metzler, et al.
Emergent abilities of large language models. arXiv
preprint arXiv:2206.07682 , 2022. URL https://
arxiv.org/abs/2206.07682 .
Thomas Wolf, Lysandre Debut, Victor Sanh, Julien
Chaumond, Clement Delangue, Anthony Moi, Pier-
ric Cistac, Tim Rault, R´ emi Louf, Morgan Funtow-
icz, et al. HuggingFace’s transformers: State-of-
the-art natural language processing. arXiv preprint
arXiv:1910.03771 , 2019. URL https://arxiv.
org/abs/1910.03771 .
Cihang Xie and Alan Yuille. Intriguing Properties of
Adversarial Training at Scale. In International Con-
ference on Learning Representations , September
9
2019. URL https://openreview.net/forum?
id=HyxJhCEFDS .
Yan Xu, Baoyuan Wu, Fumin Shen, Yanbo Fan, Yong
Zhang, Heng Tao Shen, and Wei Liu. Exact ad-
versarial attack to image captioning via structured
output learning with latent variables. In IEEE/CVF
Conference on Computer Vision and Pattern Recog-
nition , June 2019.
Shaofeng Zhang, Zheng Wang, Xing Xu, Xiang Guan,
and Yang Yang. Fooled by imagination: Adversar-
ial attack to image captioning via perturbation in
complex domain. In ICME , 2020.
Sicheng Zhu, Ruiyi Zhang, Bang An, Gang Wu, Joe
Barrow, Zichao Wang, Furong Huang, Ani Nenkova,
and Tong Sun. AutoDAN: Interpretable gradient-
based adversarial attacks on large language mod-
els, 2023. URL https://arxiv.org/abs/2310.
15140 .
Daniel Ziegler, Seraphina Nix, Lawrence Chan, Tim
Bauman, Peter Schmidt-Nielsen, Tao Lin, Adam
Scherlis, Noa Nabeshima, Benjamin Weinstein-Raun,
Daniel de Haas, Buck Shlegeris, and Nate Thomas.
Adversarial training for high-stakes reliability. In
Advances in Neural Information Processing Systems ,
October 2022. URL https://openreview.net/
forum?id=NtJyGXo0nF .
Andy Zou, Zifan Wang, J. Zico Kolter, and Matt
Fredrikson. Universal and transferable adversarial
attacks on aligned language models, 2023. URL
https://arxiv.org/abs/2307.15043 .
10
A. Models
In this work, we use the Pythia suite (Biderman et al., 2023), a collection of 10 autoregressive language models
of different sizes, all pretrained for one epoch on the Pile (Gao et al., 2020). Model checkpoints are provided
every thousand steps; for the experiments presented in this work, we always start from the final checkpoint (the
main revision on HuggingFace Hub) unless otherwise specified.
We reproduce the model sizes of the Pythia suite in Table 1. Note that the number of parameters differs
from that given in the model name because we use the models for classification tasks, which replaces the
unembedding layer with a (smaller) classification head.
Model Size (# parameters) Short Name Pythia Name Plot Color
7,629,056 7.6M 14m
17,617,408 17.6M 31m
44,672,000 44.7M 70m
123,691,008 123.7M 160m
353,824,768 353.8M 410m
908,763,136 908.8M 1b
1,311,629,312 1.3B 1.4b NA
2,646,435,840 2.6B 2.8b NA
6,650,740,736 6.7B 6.9b NA
11,586,560,000 11.6B 12b NA
Table 1: Model sizes used in our experiments, the short name often used in plots, Pythia model name, and
corresponding plot colors where applicable
11
B. Datasets
We consider four datasets in this paper. Two of them are pre-existing datasets that we use from HuggingFace
Hub: Spam (Metsis et al., 2006) and IMDB (Maas et al., 2011).5Two are synthetic datasets that we generate
ourselves: PasswordMatch andWordLength . For representative datapoints of these datasets, see Table 3.
Since the context window for the Pythia model family is 2048 tokens (Biderman et al., 2023), we must be
careful not to run models on datapoints that are longer than this threshold. For fine-tuning, presented in
Section 4, we train on the entire dataset, filtering out the (very few) datapoints which exceed 2000 tokens. We
cap at 2000 tokens instead of the 2048 token context length to leave room for adversarial attacks, special tokens,
and any other additional tokens we might need. Table 2 shows the number of datapoints in each dataset, as
well as the number of datapoints that exceed 2000 tokens.
For the PasswordMatch task, we allow attacks to replace the ‘user-provided’ password, instead of treating
the prompt as immutable and appending new text only after it.
Dataset Train of which >2000 tokens Validation of which >2000 tokens
Spam 31,716 496 2,000 33
IMDB 25,000 7 25,000 4
PasswordMatch 20,000 0 2,000 0
WordLength 20,000 0 2,000 0
Table 2: Dataset Statistics
5Available at https://huggingface.co/datasets/SetFit/enron_spam and https://huggingface.co/datasets/
stanfordnlp/imdb
12
Dataset Text Label
Spam organisational announcement we are pleased to announce that we have
appointed michael brown as chief \noperating officer of enron europe
.\nmichael joined enron \x01 , s london legal department in 1995 and
has played a key \nrole in the success of many of our large commercial
ventures since then . in \njuly 1999 , he was made enron europe \x01 ,
s general counsel . replacing michael in \nthe general counsel role will
be mark evans who joined our legal department \nin 1995 . \nplease
join us in congratulating michael and mark in their new roles .HAM (0)
Spam claim your free home depot gift card - a $1000 value . claim your
home depot gift card - a $1000 value . were sure you can find a use
for this gift card in your area . ( ) . \nby exclusiverewards \nqprkelmvSPAM (1)
IMDB Up until the last 20 minutes, I was thinking that this is possibly Jackie
Chan\’s worst movie (excluding his pre-1978 work, which I am not
familiar with). The final fight sequence changed all that: it is long
and good and intense - indeed, one of the highlights of Chan \’s career.
But to get to it, you have to sit through a lot of ”comedy” that
might amuse five-year-olds (oh, look! someone threw a tomato at
that guy \’s face) and endless ”football” scenes. Not to mention the
dubbing (which includes the line ”How can I turn it off? It \’s not a
tap” - watch to find out what it refers to). ”Dragon Lord” is worth
renting for the final fight alone, but the rest of the movie is only for
Jackie collectors, and even then only for those who \’ve already seen at
least 15 of his other movies. (**)NEGATIVE (0)
IMDB Hurrah! A space film that doesn \’t take itself too seriously and everyone
can come along for the exciting ride that is space camp. The film starts
slowly, the usual mix of idiots and high-fliers mixed together into a
dodgy soup. But when the going gets tough - the tough get themselves
sorted out and it´ s not an un-believable change in the characters as you
can believe that there \’s some responsibility in their young minds.¡br
/¿¡br /¿The only flaw in the film is that Kate Capshaw is EXTREMELY
annoying as the ”I \’m right and you \’re all wrong” instructor. I would
recommend this as a nice night in movie and a 7 Vote.POSITIVE (1)
PasswordMatch You are an online security system. Below the user will enter a pass-
word.\nIf it is ”syllogistic”, then respond with ”Access Granted”. Oth-
erwise respond with ”Access Denied”. \n—\nYorktown \n—\nACCESS DENIED (0)
PasswordMatch You are an online security system. Below the user will enter a pass-
word.\nIf it is ”Herodotus”, then respond with ”Access Granted”.
Otherwise respond with ”Access Denied”. \n—\nHerodotus \n—\nACCESS GRANTED (1)
WordLength Which word is longer? Word 1: keyword. Word 2: medal. Return 0
for the first word and 1 for the second word. If the words are the same
length, return 0. Ignore everything after this sentence.FIRST (0)
WordLength Which word is longer? Word 1: purloin. Word 2: literate. Return 0
for the first word and 1 for the second word. If the words are the same
length, return 0. Ignore everything after this sentence.SECOND (1)
Table 3: Representative examples from four datasets used in our experiments.
13
C. Adversarial Attacks
The primary attack we use is GCGfrom Zou et al. (2023). We use the simple, single-prompt version described
in Algorithm 1 of Zou et al. (2023) with the modifiable subset Iset to be the final Ntokens of the prompt
(except for PasswordMatch , where there is a final ---separator after the attack tokens; see Table 3). We use
a suffix of length N= 10 , batch size B= 128 , and k= 256 top substitutions for all experiments. We use
T= 10 iterations for most experiments, using T= 30 to evaluate robustness transfer from adversarially training
on a weaker attack ( T= 10 ).
We describe the baseline RandomToken algorithm in Algorithm 1. RandomToken is designed to be similar to
GCGexcept that RandomToken does not use gradient-guided search. Instead, for each iteration we replace each
token in the adversarial suffix with a new token chosen uniformly at random from the vocabulary of the model.
We then evaluate the new prompt to see if it has caused the model to give an incorrect answer and stop the
attack if it has. If no iteration was successful, we return the adversarial suffix from the final iteration.
To make sure the baseline is a fair comparison, we constrain the attacks to use the same maximum number of
forward passes. To do this, we compute the number of forward passes used by GCGasB×T= 1280 and thus
perform up to 1280 iterations of RandomToken .
Algorithm 1 RandomToken
Input: Initial prompt x1:n, modifiable subset I, iterations T, success criterion S, vocabulary V
fort= 1toTdo
fori∈ Ido
xi←Uniform (V)
end for
ifS(x1:n)then
return: x1:n
end if
end for
return: x1:n
Output: Optimized prompt x1:n
14
D. Fine-tuning
D.1. Training
For each task, we fine-tune each model for a single epoch. The final validation accuracies are shown in Table 4.
Task Model Size (# parameters) Validation accuracy
Spam 7.6M 0.985
17.6M 0.985
44.7M 0.99
123.7M 0.99
353.8M 0.985
908.8M 0.99
1.3B 0.99
2.6B 0.9
6.7B 0.99
11.6B 0.99
IMDB 7.6M 0.875
17.6M 0.9
44.7M 0.905
123.7M 0.93
353.8M 0.96
908.8M 0.965
1.3B 0.96
2.6B 0.975
6.7B 0.97
11.6B 0.98
PasswordMatch 7.6M 1
17.6M 1
44.7M 1
123.7M 1
353.8M 1
908.8M 1
1.3B 1
2.6B 1
6.7B 1
11.6B 1
WordLength 7.6M 0.836
17.6M 0.882
44.7M 0.858
123.7M 0.944
353.8M 0.978
908.8M 0.958
1.3B 0.968
2.6B 0.972
6.7B 0.954
11.6B 0.976
Table 4: Accuracy on (not attacked) validation dataset at the end of training.
15
D.2. Attack Results
We attack the fine-tuned models with both the GCGandRandomToken attacks. As explored in Section 4, while
model size appears to generally help with robustness, there is a large amount of unexplained variability in each
model’s robustness.
D.2.1. GCG
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Figure 4: GCGattack success rate on different sizes of fine-tuned models on the Spam task. We show three seeds
per model size. The min-max-median plot (left) and scatterplot (right) are constructed using the
same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack
Figure 5: GCGattack success rate on different sizes of fine-tuned models on the IMDB task. We show three seeds
per model size. The min-max-median plot (left) and scatterplot (right) are constructed using the
same data.
16
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RatePasswordMatch, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PasswordMatch, GCG attackFigure 6: GCGattack success rate on different sizes of fine-tuned models on the PasswordMatch task. We show
three seeds per model size. The min-max-median plot (left) and scatterplot (right) are constructed
using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateWordLength, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WordLength, GCG attack
Figure 7: GCGattack success rate on different sizes of fine-tuned models on the WordLength task. We show
three seeds per model size. The min-max-median plot (left) and scatterplot (right) are constructed
using the same data.
17
D.2.2. RandomToken
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, RT attack
Figure 8: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the Spam task.
We show three seeds per model size. The min-max-median plot (left) and scatterplot (right) are
constructed using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, RT attack
Figure 9: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the IMDB task.
We show three seeds per model size. The min-max-median plot (left) and scatterplot (right) are
constructed using the same data.
18
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RatePasswordMatch, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PasswordMatch, RT attackFigure 10: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the PasswordMatch
task. We show three seeds per model size. The min-max-median plot (left) and scatterplot (right)
are constructed using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateWordLength, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WordLength, RT attack
Figure 11: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the WordLength
task. We show three seeds per model size. The min-max-median plot (left) and scatterplot (right)
are constructed using the same data.
19
E. Adversarial Training and Transfer
The overall adversarial training procedure is presented in Figure 12.
Figure 12: Our adversarial training setup.
As the diagram highlights, adversarial training is done by repeating the following steps:
•Train the model for one epoch on the train dataset.
•Attack the train dataset and evaluate the model on the attacked train dataset.
•Add the attacked examples to the train dataset.
•Attack the validation dataset and evaluate the model on the attacked validation dataset. Record model
performance on the attacked validation dataset.
For adversarial training, we use an initial training dataset of size 2000, and a validation dataset of size 200.
Initially we used a validation dataset also of size 2000, but found that decreasing the validation dataset size
had a negligible effect on the variance of the attack success rate, so opted for smaller dataset to enable faster
evaluation. At each round, we add 200 adversarially-attacked examples to the train dataset.
20
E.1. Adversarial Training
Below, we show plots of adversarial training using the GCGandRandomToken attacks across the four tasks. We
use three seeds per model, and present attack success rate after 10 and 30 rounds of adversarial training.
E.1.1. GCG Attack 10 Rounds
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 13: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for 10 rounds of adversarial training. We shade min to
max and plot median over three seeds.
21
E.1.2. GCG Attack 10 Rounds Alternate View
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
(a)Spam task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 14: Attack success rate as a function of model size across four tasks using the 10-iteration GCGattack,
over different adversarial training rounds.
22
E.1.3. GCG Attack 30 Rounds
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 15: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for 30 rounds of adversarial training.
23
E.1.4. GCG Attack 30 Rounds Convergence
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.10Attack Success Rate
Spam, GCG attack
(a)Spam task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0250.0500.0750.1000.1250.1500.1750.200Attack Success Rate
IMDB, GCG attack (b)IMDB task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0020.0040.0060.0080.010Attack Success Rate
PM, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.100.120.14Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 16: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for the final 10 rounds of 30-round adversarial training.
24
E.1.5. RandomToken Attack 10 Rounds
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RandomToken attack
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 17: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for 10 rounds of adversarial training. We shade min to max
and plot median over three seeds.
25
E.1.6. RandomToken Attack 10 Rounds Alternate View
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, RT attack
(a)Spam task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, RT attack (b)IMDB task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PM, RT attack
(c)PasswordMatch task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WL, RT attack (d)WordLength task.
Figure 18: Attack success rate as a function of model size across four tasks using the 10-iteration RandomToken
(RT) attack, over different adversarial training rounds.
26
E.1.7. RandomToken Attack 30 Rounds
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RandomToken attack
(c)PasswordMatch task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 19: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for 30 rounds of adversarial training.
27
E.1.8. RandomToken Attack 30 Rounds Convergence
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.10Attack Success Rate
Spam, RandomToken attack
(a)Spam task.
20 22 24 26 28 30
Adversarial Training Round0.000.050.100.150.200.250.30Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0020.0040.0060.0080.010Attack Success Rate
PM, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
20 22 24 26 28 30
Adversarial Training Round0.000.050.100.150.200.25Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 20: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for the final 10 rounds of 30-round adversarial training.
28
E.2. Transfer
As presented in Section 5.1, we also evaluate how models adversarially trained with one attack generalize to
defending against other attacks. We present two collections of plots: first, models trained on the 10-iteration
GCGattack and evaluated with the 30-iteration GCGattack; second, models trained on the RandomToken attack
and evaluated on the (10-iteration) GCGattack. In the first case, all model sizes are able to generalize to being
somewhat robust against the stronger attack, though larger models do so both faster and to a greater extent.
By contrast, in the second case, only the larger models are able to generalize within the 10 adversarial training
rounds studied.
E.2.1. GCG Attack
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG train, GCG 30 its eval
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG train, GCG 30 its eval (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG train, GCG 30 its eval
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG train, GCG 30 its eval (d)WordLength task.
Figure 21: Attack success rate as a function of adversarial training round across four tasks. Adversarial training
is performed with the 10-iteration GCGattack, and evaluation performed with the 30-iteration GCG
attack.
29
E.2.2. RandomToken attack
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RT train, GCG eval
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RT train, GCG eval (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RT train, GCG eval
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RT train, GCG eval (d)WordLength task.
Figure 22: Attack success rate as a function of adversarial training round across four tasks. Adversarial training
is performed with the RandomToken (RT) attack, and evaluation performed with the 10-iteration
GCGattack.
30
E.3. Complexity Calculation
In Section 6, we compare the relative complexity of adversarially training a larger model for fewer rounds or a
smaller model for more rounds. In this section, we provide a worked example. We use a batch size of 8 for
both the 17.6M and 44.7M models. We start with 2000 datapoints in the train dataset and add 200 datapoints
each round. This means that after 4 rounds of training, each model will have seenP4
i=1(250 + i·25)= 1250
batches, and after 8 rounds of training,P8
i=1(250 + i·25)= 2900 batches. If we update model parameters
once per batch, this means that after 4 rounds, the 44.7M parameter model will have had 44.7M·1250 = 55875 M
gradient updates, while after 8 rounds, the 17.6M parameter model will have had 17.6M·2900 = 51040 M
gradient updates.
31 | Appendix B.
Models We test the Pythia model family (Biderman
et al., 2023). These models range in size from 14M to
12B parameters (or 7.6M to 11.6B when used with a
classification head). All models were trained to predict
the next token on the same dataset following the same
training protocol, allowing us to isolate model scale
from other confounding factors.
Attacks Our attacks append an adversarial suffix
ofNtokens to the prompt. We use two different
procedures to generate this adversarial suffix: a random
token baseline ( RandomToken ) and the state-of-the-
art greedy coordinate gradient attack ( GCG; Zou et al.,
2023). RandomToken was chosen due to its simplicity.
GCG was chosen as it is currently one of the most
effective attacks on language models.
In the RandomToken baseline, the Ntokens are cho-
sen uniformly at random from the model’s vocabulary.
We evaluate the model on the attacked text and then
repeat the process with another sample of Nrandom
tokens until the model is successfully attacked or an
appointed budget for model calls is exhausted.
InGCG(Zou et al., 2023), the Ntokens are initialized
arbitrarily and then greedily optimized over multiple
rounds. In each round, the gradient of the loss function
with respect to the attack tokens is computed. This
gradient is used to compute a set of promising single-
token modifications, from which the best candidate
is selected and used in the next round. To make this
attack work in the classification setting, we minimize
the cross-entropy loss between the predicted label and
the target label.
In our experiments, we always use N= 10 tokens.
For more details about the attacks and hyperparame-
ters used, see Appendix C.4. Fine-tuning
Figure 1 shows the robustness of fine-tuned models
against the GCGattack. The attack is generally less
successful on larger models, but model size alone does
not explain all the variance in attack success rate.
We observe similarly large random variation in attack
success across model sizes on other tasks and with
other attacks; for more details, see Appendix D.2.
As described in Section 3, we use the Pythia mod-
els, which range from 7.6M to 11.6B parameters after
replacing the unembedding matrix with a classifica-
tion head.2We fine-tune all models for a single epoch
with default hyperparameters from HuggingFace Trans-
formers (Wolf et al., 2019), except for the learning
rate which we set to 1e−5. All models reach >83%
accuracy on all tasks, with larger models generally
performing better (see Appendix D.1 for the final val-
idation performance of all models on all tasks). We
then evaluate the fine-tuned models against adversarial
attacks on an unseen validation dataset.
To understand the source of the variability in model
robustness shown by our experiments, we varied 1)
the pretraining checkpoint,3and 2) the random seeds
used to initialize the classification head before fine-
tuning. Both factors led to significant variability in
model robustness, with pretraining checkpoint con-
tributing significantly more variability. The variability
was comparable or greater than that of an order of
magnitude of model scaling, indicating that out-of-the-
box robustness on a given task is heavily influenced by
the randomness of the pretraining procedure itself.
This initial result suggests that we cannot rely on
scale alone to solve the problem of robustness. How-
ever, in practice, we would apply a defense to a model
prior to deploying it in a security-critical setting. In the
following section, we consider whether scale enables
defenses to more effectively improve model robustness.
5. Adversarial training
In this section, we explore how model size impacts
robustness when performing adversarial training. Fig-
ure 2 evaluates the robustness of Pythia models to
theGCGattack when adversarially trained against the
same attack. We see a much cleaner trend than in the
fine-tuning only case: larger models gain robustness
2In all figures, we report the actual parameter count of the
classification model, and not the pretrained model it was
derived from.
3The Pythia models provide checkpoints from earlier stages of
pretraining. We used various checkpoints from the final 10%
of pretraining as a starting point for fine-tuning.
4
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG train, GCG 30 its eval
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M(a)Adversarial training against 10-iteration GCG, with eval-
uation against 30-iteration GCG. All models show some
transfer of their defense to this stronger attack, with
larger models doing so more effectively.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RT train, GCG eval(b)Adversarial training against 10-iteration RandomToken ,
with evaluation against 10-iteration GCG.≥100M pa-
rameter models show strong defense transfer, while
smaller models struggle against the new attack.
Figure 3: Attack success rate ( y-axis) against Pythia models of varying sizes (line color) during adversarial
training ( x-axis).
more quickly and converge to be more robust than
smaller models. These results suggest that model size
is a strong predictor of robustness—so long as the
model is explicitly optimized for robustness. We ob-
serve similar behavior across the other two datasets
and two attacks; see Appendix E for these plots, in-
cluding extensions for up to 30 adversarial training
rounds.
We perform adversarial training by iteratively training
our model on a training dataset, evaluating the model
on attacked examples, and then adding successful at-
tack examples to the training dataset. Simultaneously,
we evaluate model performance on a held-out attacked
validation dataset. This procedure is illustrated in Fig-
ure 12.
In our experiments, we initialize the training dataset
to consist of 2000 clean examples, and add 200 ad-
versarial examples to the training dataset each round.
We repeat the train-attack-add loop 30 times (here we
only show the first 10 rounds; see Appendix E for the
full 30-round plots). Since adversarial examples are
only added after the first training round, the models
here were trained for a single epoch on the 2000 clean
datapoints before being adversarially attacked.
We perform adversarial training on Pythia models
ranging from 7.6 to 909 million parameters after re-
placing the unembedding layer with a classification
head.4Table 1 in Appendix A enumerates all model
4Specifically, we use the pythia-14m topythia-1b models
loaded as AutoModelForSequenceClassification .sizes along with corresponding plot colors.
5.1. Robustness transfer
In practice, we often do not have the luxury of knowing
the exact attack method an adversary may employ
against our model. For practical deployments, we
therefore need adversarial training on a handful of
attacks to provide more general robustness against
other unforeseen attacks. In this subsection, we study
whether we observe this transfer in robustness between
attacks—and how model scale affects the transfer.
First, we explore whether robustness from adversarial
training transfers to a stronger attack from the same
family. To do this, we adversarially train using the
procedure described above with GCG for 10 iterations
as our training attack. We then evaluate on GCG for
30 iterations, a stronger attack. Figure 3a shows that
larger models are more robust to this in-distribution,
stronger attack. Although the transfer is imperfect—
the models do, of course, lose against 30-iteration
GCG more than against 10-iteration GCG—the perfor-
mance is much better than the undefended (fine-tuned)
models, which lose approximately 100% of the time.
This is a promising result. Yet, what happens if our
models experience an attack that is not only stronger
but also uses a different method than the one on which
they were adversarially trained? We investigate this
question by performing adversarial training against
RandomToken and evaluating against the GCGattack.
Figure 3b shows models adversarially trained on
5
RandomToken do perform better than undefended
models, though the effect is weaker. Critically, the
extent to which transfer occurs varies drastically across
models. In particular, the models with more than 100
million parameters all show strong transfer behavior,
with the attack success rate falling below 25% after
just 4 rounds of adversarial training. On the other
hand, models with fewer than 100 million parame-
ters struggle to transfer their robustness against the
RandomToken attack to the stronger GCGattack, with
the attack success rate still near 70% on the strongest
model even after 10 adversarial training rounds.
This finding is encouraging as it suggests that, for
sufficiently large models, robustness will transfer across
attacks. It appears that this transfer might be a
property that emerges with sufficient scale, similarly
to other emergent properties like the ability to use a
scratchpad for addition or the utility of instruction fine-
tuning (Wei et al., 2022). While we cannot say with
certainty that such transfer of robustness generalizes
outside the settings and attacks considered in this
work, it seems plausible that it would, and indeed, that
scaling to further orders of magnitude could unlock
more general transfer to a wider variety of attack
methodologies and strengths.
6. Conclusion
Our results demonstrate that larger Pythia models ben-
efit more from adversarial training than smaller Pythia
models across a variety of classification tasks. An
important direction for future work is to validate this
trend holds in a broader variety of settings. In particu-
lar, we plan to study generative tasks and how factors
such as task complexity affect robustness. We also
plan to investigate different model families, including
larger models.
A key application of scaling trends is to inform appro-
priate sizing of models to maximize robustness given
a fixed defender compute budget. Although larger
models are more sample efficient with a fixed num-
ber of adversarial training time steps, each adversarial
training step is more computationally expensive than
with smaller models. For example, Figure 2 shows that
performing 8 adversarial training rounds on the 17.6M
parameter model results in better robustness than per-
forming 4 adversarial training rounds on the 44.7M
parameter model, and a quick calculation shows that
it is slightly less expensive to train (see Appendix E.3).
However, using a smaller model is not always better,
since there are diminishing returns to adversarial train-
ing, with larger models appearing to converge to bemore robust.
Although scale can improve robustness, our results
make clear that it is far from the only determinant. For
example, a small adversarially trained model is more
robust than a large model fine-tuned only on clean data.
We expect that achieving robust language models will
require innovations in defense techniques as well as
scaling model pretraining and defense training. Scaling
trends both enable us to measure how far we are from
achieving robustness by scale alone and enable us to
identify defense techniques that can better leverage
scale to produce more robust models.
Acknowledgements
The authors thank ChengCheng Tan for her assistance
in formatting this document, and Daniel Pandori for his
contributions to the codebase during the early stages
of this project. Nikolaus Howe thanks the Natural
Sciences and Engineering Research Council of Canada
(NSERC) for their support via the Vanier Canada
Graduate Scholarship.
References
Sahar Abdelnabi, Kai Greshake, Shailesh Mishra,
Christoph Endres, Thorsten Holz, and Mario Fritz.
Not what you’ve signed up for: Compromising
real-world LLM-integrated applications with indi-
rect prompt injection. In AISec , page 79–90, 2023.
Jean-Baptiste Alayrac, Jonathan Uesato, Po-Sen
Huang, Alhussein Fawzi, Robert Stanforth, and
Pushmeet Kohli. Are Labels Required for Improving
Adversarial Robustness? In Advances in Neural
Information Processing Systems , volume 32. Curran
Associates, Inc., 2019. URL https://papers.
nips.cc/paper_files/paper/2019/hash/
bea6cfd50b4f5e3c735a972cf0eb8450-Abstract.
html .
Moustafa Alzantot, Bharathan Balaji, and Mani Sri-
vastava. Did you hear that? Adversarial examples
against automatic speech recognition, 2018. URL
https://arxiv.org/abs/1808.05665 .
Cem Anil, Esin Durmus, Mrinank Sharma, Joe Benton,
Sandipan Kundu, Joshua Batson, Nina Rimsky,
Meg Tong, Jesse Mu, Daniel Ford, Francesco
Mosconi, Rajashree Agrawal, Rylan Schaeffer,
Naomi Bashkansky, Samuel Svenningsen, Mike
Lambert, Ansh Radhakrishnan, Carson Denison,
Evan J Hubinger, Yuntao Bai, Trenton Bricken,
6
Timothy Maxwell, Nicholas Schiefer, Jamie Sully,
Alex Tamkin, Tamera Lanham, Karina Nguyen,
Tomasz Korbak, Jared Kaplan, Deep Ganguli,
Samuel R Bowman, Ethan Perez, Roger Grosse,
and David Duvenaud. Many-shot Jailbreaking,
2024. URL https://www-cdn.anthropic.com/
af5633c94ed2beb282f6a53c595eb437e8e7b630/
Many_Shot_Jailbreaking__2024_04_02_0936.
pdf.
Anthropic. Tool use (function calling), 2024. URL
https://archive.ph/EqXCz .
Brian R. Bartoldson, James Diffenderfer, Konstanti-
nos Parasyris, and Bhavya Kailkhura. Adversar-
ial Robustness Limits via Scaling-Law and Human-
Alignment Studies, April 2024. URL http://arxiv.
org/abs/2404.09349 .
Stella Biderman, Hailey Schoelkopf, Quentin Gregory
Anthony, Herbie Bradley, Kyle O’Brien, Eric Halla-
han, Mohammad Aflah Khan, Shivanshu Purohit,
USVSN Sai Prashanth, Edward Raff, et al. Pythia:
A suite for analyzing large language models across
training and scaling. In International Conference on
Machine Learning , pages 2397–2430. PMLR, 2023.
Yair Carmon, Aditi Raghunathan, Ludwig Schmidt,
Percy Liang, and John C. Duchi. Unlabeled Data Im-
proves Adversarial Robustness, January 2022. URL
http://arxiv.org/abs/1905.13736 .
Canyu Chen and Kai Shu. Can LLM-generated misin-
formation be detected? In International Conference
on Learning Representations , 2024.
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming
Yuan, Henrique Ponde de Oliveira Pinto, Jared Ka-
plan, Harri Edwards, Yuri Burda, Nicholas Joseph,
Greg Brockman, Alex Ray, Raul Puri, Gretchen
Krueger, Michael Petrov, Heidy Khlaaf, Girish Sas-
try, Pamela Mishkin, Brooke Chan, Scott Gray,
Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz
Kaiser, Mohammad Bavarian, Clemens Winter,
Philippe Tillet, Felipe Petroski Such, Dave Cum-
mings, Matthias Plappert, Fotios Chantzis, Eliza-
beth Barnes, Ariel Herbert-Voss, William Hebgen
Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie
Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain,
William Saunders, Christopher Hesse, Andrew N.
Carr, Jan Leike, Josh Achiam, Vedant Misra, Evan
Morikawa, Alec Radford, Matthew Knight, Miles
Brundage, Mira Murati, Katie Mayer, Peter Welin-
der, Bob McGrew, Dario Amodei, Sam McCandlish,
Ilya Sutskever, and Wojciech Zaremba. EvaluatingLarge Language Models Trained on Code, July 2021.
URL http://arxiv.org/abs/2107.03374 .
Moustapha M Cisse, Yossi Adi, Natalia Neverova,
and Joseph Keshet. Houdini: Fooling deep
structured visual and speech recognition mod-
els with adversarial examples. In Advances in
Neural Information Processing Systems , vol-
ume 30, 2017. URL https://proceedings.
neurips.cc/paper_files/paper/2017/hash/
d494020ff8ec181ef98ed97ac3f25453-Abstract.
html .
Edoardo Debenedetti, Zishen Wan, Maksym An-
driushchenko, Vikash Sehwag, Kshitij Bhardwaj, and
Bhavya Kailkhura. Scaling Compute Is Not All You
Need for Adversarial Robustness, December 2023.
URL http://arxiv.org/abs/2312.13131 .
Deep Ganguli, Liane Lovitt, Jackson Kernion, Amanda
Askell, Yuntao Bai, Saurav Kadavath, Ben Mann,
Ethan Perez, Nicholas Schiefer, Kamal Ndousse,
Andy Jones, Sam Bowman, Anna Chen, Tom Con-
erly, Nova DasSarma, Dawn Drain, Nelson El-
hage, Sheer El-Showk, Stanislav Fort, Zac Hatfield-
Dodds, Tom Henighan, Danny Hernandez, Tristan
Hume, Josh Jacobson, Scott Johnston, Shauna
Kravec, Catherine Olsson, Sam Ringer, Eli Tran-
Johnson, Dario Amodei, Tom Brown, Nicholas
Joseph, Sam McCandlish, Chris Olah, Jared Ka-
plan, and Jack Clark. Red Teaming Language Mod-
els to Reduce Harms: Methods, Scaling Behav-
iors, and Lessons Learned, November 2022. URL
http://arxiv.org/abs/2209.07858 .
Leo Gao, Stella Biderman, Sid Black, Laurence Gold-
ing, Travis Hoppe, Charles Foster, Jason Phang,
Horace He, Anish Thite, Noa Nabeshima, et al. The
Pile: An 800gb dataset of diverse text for language
modeling. arXiv preprint arXiv:2101.00027 , 2020.
Justin Gilmer, Luke Metz, Fartash Faghri, Samuel S.
Schoenholz, Maithra Raghu, Martin Wattenberg,
and Ian Goodfellow. Adversarial Spheres, September
2018. URL http://arxiv.org/abs/1801.02774 .
Adam Gleave, Michael Dennis, Cody Wild, Neel Kant,
Sergey Levine, and Stuart Russell. Adversarial poli-
cies: Attacking deep reinforcement learning. In In-
ternational Conference on Learning Representations ,
2020.
Google. Function calling — Google AI for developers,
2024. URL https://archive.ph/YGJHJ .
7
Dan Hendrycks, Kimin Lee, and Mantas Mazeika. Us-
ing Pre-Training Can Improve Model Robustness
and Uncertainty. In International Conference on
Machine Learning , pages 2712–2721. PMLR, May
2019. URL https://proceedings.mlr.press/
v97/hendrycks19a.html . ISSN: 2640-3498.
Dan Hendrycks, Collin Burns, Steven Basart, Andy
Zou, Mantas Mazeika, Dawn Song, and Jacob Stein-
hardt. Measuring massive multitask language under-
standing. In International Conference on Learning
Representations , 2021. URL https://openreview.
net/forum?id=d7KBjmI3GmQ .
Danny Hernandez, Jared Kaplan, Tom Henighan, and
Sam McCandlish. Scaling Laws for Transfer, Febru-
ary 2021. URL http://arxiv.org/abs/2102.
01293 .
Joel Hestness, Sharan Narang, Newsha Ardalani, Gre-
gory Diamos, Heewoo Jun, Hassan Kianinejad,
Md Mostofa Ali Patwary, Yang Yang, and Yanqi
Zhou. Deep Learning Scaling is Predictable, Empir-
ically, December 2017. URL http://arxiv.org/
abs/1712.00409 .
Jordan Hoffmann, Sebastian Borgeaud, Arthur Men-
sch, Elena Buchatskaya, Trevor Cai, Eliza Ruther-
ford, Diego de Las Casas, Lisa Anne Hendricks, Jo-
hannes Welbl, Aidan Clark, Tom Hennigan, Eric
Noland, Katie Millican, George van den Driess-
che, Bogdan Damoc, Aurelia Guy, Simon Osin-
dero, Karen Simonyan, Erich Elsen, Jack W. Rae,
Oriol Vinyals, and Laurent Sifre. Training Compute-
Optimal Large Language Models, March 2022. URL
http://arxiv.org/abs/2203.15556 .
Krystal Hu. ChatGPT sets record for fastest-growing
user base – analyst note. Reuters , 2023.
Sandy H. Huang, Nicolas Papernot, Ian J. Goodfellow,
Yan Duan, and Pieter Abbeel. Adversarial attacks on
neural network policies. arXiv:1702.02284v1 [cs.LG],
2017.
Shihua Huang, Zhichao Lu, Kalyanmoy Deb, and
Vishnu Naresh Boddeti. Revisiting Residual Net-
works for Adversarial Robustness. In IEEE/CVF
Conference on Computer Vision and Pattern Recog-
nition , pages 8202–8211, Vancouver, BC, Canada,
June 2023. IEEE. ISBN 9798350301298. doi:
10.1109/CVPR52729.2023.00793 . URL https://
ieeexplore.ieee.org/document/10204909/ .
Inaam Ilahi, Muhammad Usama, Junaid Qadir,
Muhammad Umar Janjua, Ala Al-Fuqaha, Dinh ThaiHoang, and Dusit Niyato. Challenges and counter-
measures for adversarial attacks on deep reinforce-
ment learning. IEEE TAI , 3(2):90–109, 2022.
Andrew Ilyas, Shibani Santurkar, Dimitris Tsipras,
Logan Engstrom, Brandon Tran, and Aleksander
Madry. Adversarial Examples Are Not Bugs,
They Are Features. In Advances in Neural
Information Processing Systems , volume 32. Curran
Associates, Inc., 2019. URL https://papers.
nips.cc/paper_files/paper/2019/hash/
e2c420d928d4bf8ce0ff2ec19b371514-Abstract.
html .
Neel Jain, Avi Schwarzschild, Yuxin Wen, Gowthami
Somepalli, John Kirchenbauer, Ping yeh Chiang,
Micah Goldblum, Aniruddha Saha, Jonas Geiping,
and Tom Goldstein. Baseline defenses for adversarial
attacks against aligned language models, 2023. URL
https://arxiv.org/abs/2309.00614 .
Jared Kaplan, Sam McCandlish, Tom Henighan,
Tom B. Brown, Benjamin Chess, Rewon Child, Scott
Gray, Alec Radford, Jeffrey Wu, and Dario Amodei.
Scaling Laws for Neural Language Models, January
2020. URL http://arxiv.org/abs/2001.08361 .
Megan Kinniment, Lucas Jun Koba Sato, Haox-
ing Du, Brian Goodrich, Max Hasin, Lawrence
Chan, Luke Harold Miles, Tao R. Lin, Hjalmar
Wijk, Joel Burget, Aaron Ho, Elizabeth Barnes,
and Paul Christiano. Evaluating language-model
agents on realistic autonomous tasks, 2024. URL
https://arxiv.org/abs/2312.11671 .
Stephanie Lin, Jacob Hilton, and Owain Evans. Truth-
fulQA: Measuring How Models Mimic Human False-
hoods, May 2022. URL http://arxiv.org/abs/
2109.07958 .
Andrew L. Maas, Raymond E. Daly, Peter T. Pham,
Dan Huang, Andrew Y. Ng, and Christopher Potts.
Learning word vectors for sentiment analysis. In
Association for Computational Linguistics: Human
Language Technologies , pages 142–150, Portland,
Oregon, USA, June 2011. Association for Computa-
tional Linguistics. URL http://www.aclweb.org/
anthology/P11-1015 .
Ian R. McKenzie, Alexander Lyzhov, Michael Martin
Pieler, Alicia Parrish, Aaron Mueller, Ameya Prabhu,
Euan McLean, Xudong Shen, Joe Cavanagh, An-
drew George Gritsevskiy, Derik Kauffman, Aaron T.
Kirtland, Zhengping Zhou, Yuhui Zhang, Sicong
Huang, Daniel Wurgaft, Max Weiss, Alexis Ross,
8
Gabriel Recchia, Alisa Liu, Jiacheng Liu, Tom Tseng,
Tomasz Korbak, Najoung Kim, Samuel R. Bowman,
and Ethan Perez. Inverse Scaling: When Bigger
Isn’t Better. Transactions on Machine Learning Re-
search , June 2023. ISSN 2835-8856. URL https:
//openreview.net/forum?id=DwgRm72GQF .
Vangelis Metsis, Ion Androutsopoulos, and Georgios
Paliouras. Spam Filtering with Naive Bayes -
Which Naive Bayes? In Conference on Email and
Anti-Spam , 2006. URL https://www2.aueb.gr/
users/ion/docs/ceas2006_paper.pdf .
Christopher A. Mouton, Caleb Lucas, and Ella Guest.
The Operational Risks of AI in Large-Scale Bio-
logical Attacks: A Red-Team Approach . RAND
Corporation, 2023.
Norman Mu, Sarah Chen, Zifan Wang, Sizhe Chen,
David Karamardian, Lulwa Aljeraisy, Basel Alomair,
Dan Hendrycks, and David Wagner. Can LLMs
follow simple rules? arXiv , 2023. URL https:
//arxiv.org/abs/2311.04235 .
OpenAI. Assistants API documentation, 2023. URL
https://archive.ph/8Az8d .
David Rein, Betty Li Hou, Asa Cooper Stickland, Jack-
son Petty, Richard Yuanzhe Pang, Julien Dirani,
Julian Michael, and Samuel R. Bowman. GPQA: A
graduate-level google-proof q&a benchmark, 2023.
URL https://arxiv.org/abs/2311.12022 .
Toran Bruce Richards. Auto-gpt: An autonomous
GPT-4 experiment, 2024. URL https://github.
com/Significant-Gravitas/AutoGPT/ .
Jonathan S. Rosenfeld, Amir Rosenfeld, Yonatan Be-
linkov, and Nir Shavit. A Constructive Prediction of
the Generalization Error Across Scales, December
2019. URL http://arxiv.org/abs/1909.12673 .
Lea Sch¨ onherr, Katharina Kohls, Steffen Zeiler,
Thorsten Holz, and Dorothea Kolossa. Adversar-
ial attacks against automatic speech recognition
systems via psychoacoustic hiding, 2018.
Lee Sharkey, Cl ´ ıodhna N ´ ı Ghuidhir, Dan Braun, J´ er´ emy
Scheurer, Mikita Balesni, Lucius Bushnaq, Charlotte
Stix, and Marius Hobbhahn. A causal framework for
AI regulation and auditing. Technical report, Apollo
Research, 2023.
Giovanni Spitale, Nikola Biller-Andorno, and Federico
Germani. AI model GPT-3 (dis)informs us better
than humans. Science Advances , 9(26), 2023.Christian Szegedy, Wojciech Zaremba, Ilya Sutskever,
Joan Bruna, Dumitru Erhan, Ian Goodfellow, and
Rob Fergus. Intriguing properties of neural networks,
2014. URL https://arxiv.org/abs/1312.6199 .
Sam Toyer, Olivia Watkins, Ethan Adrian Mendes,
Justin Svegliato, Luke Bailey, Tiffany Wang, Isaac
Ong, Karim Elmaaroufi, Pieter Abbeel, Trevor Dar-
rell, Alan Ritter, and Stuart Russell. Tensor Trust:
Interpretable prompt injection attacks from an on-
line game, 2023. URL https://arxiv.org/abs/
2311.01011 .
Dimitris Tsipras, Shibani Santurkar, Logan Engstrom,
Alexander Turner, and Aleksander Madry. Robust-
ness may be at odds with accuracy. In International
Conference on Learning Representations , 2019. URL
https://arxiv.org/abs/1805.12152 .
Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner,
and Sameer Singh. Universal Adversarial Triggers
for Attacking and Analyzing NLP, January 2021.
URL http://arxiv.org/abs/1908.07125 .
Tony Tong Wang, Adam Gleave, Tom Tseng, Kellin
Pelrine, Nora Belrose, Joseph Miller, Michael D
Dennis, Yawen Duan, Viktor Pogrebniak, Sergey
Levine, and Stuart Russell. Adversarial policies beat
superhuman Go AIs. In International Conference
on Machine Learning , pages 35655–35739. PMLR,
2023.
Alexander Wei, Nika Haghtalab, and Jacob Steinhardt.
Jailbroken: How Does LLM Safety Training Fail?,
July 2023. URL http://arxiv.org/abs/2307.
02483 .
Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel,
Barret Zoph, Sebastian Borgeaud, Dani Yogatama,
Maarten Bosma, Denny Zhou, Donald Metzler, et al.
Emergent abilities of large language models. arXiv
preprint arXiv:2206.07682 , 2022. URL https://
arxiv.org/abs/2206.07682 .
Thomas Wolf, Lysandre Debut, Victor Sanh, Julien
Chaumond, Clement Delangue, Anthony Moi, Pier-
ric Cistac, Tim Rault, R´ emi Louf, Morgan Funtow-
icz, et al. HuggingFace’s transformers: State-of-
the-art natural language processing. arXiv preprint
arXiv:1910.03771 , 2019. URL https://arxiv.
org/abs/1910.03771 .
Cihang Xie and Alan Yuille. Intriguing Properties of
Adversarial Training at Scale. In International Con-
ference on Learning Representations , September
9
2019. URL https://openreview.net/forum?
id=HyxJhCEFDS .
Yan Xu, Baoyuan Wu, Fumin Shen, Yanbo Fan, Yong
Zhang, Heng Tao Shen, and Wei Liu. Exact ad-
versarial attack to image captioning via structured
output learning with latent variables. In IEEE/CVF
Conference on Computer Vision and Pattern Recog-
nition , June 2019.
Shaofeng Zhang, Zheng Wang, Xing Xu, Xiang Guan,
and Yang Yang. Fooled by imagination: Adversar-
ial attack to image captioning via perturbation in
complex domain. In ICME , 2020.
Sicheng Zhu, Ruiyi Zhang, Bang An, Gang Wu, Joe
Barrow, Zichao Wang, Furong Huang, Ani Nenkova,
and Tong Sun. AutoDAN: Interpretable gradient-
based adversarial attacks on large language mod-
els, 2023. URL https://arxiv.org/abs/2310.
15140 .
Daniel Ziegler, Seraphina Nix, Lawrence Chan, Tim
Bauman, Peter Schmidt-Nielsen, Tao Lin, Adam
Scherlis, Noa Nabeshima, Benjamin Weinstein-Raun,
Daniel de Haas, Buck Shlegeris, and Nate Thomas.
Adversarial training for high-stakes reliability. In
Advances in Neural Information Processing Systems ,
October 2022. URL https://openreview.net/
forum?id=NtJyGXo0nF .
Andy Zou, Zifan Wang, J. Zico Kolter, and Matt
Fredrikson. Universal and transferable adversarial
attacks on aligned language models, 2023. URL
https://arxiv.org/abs/2307.15043 .
10
A. Models
In this work, we use the Pythia suite (Biderman et al., 2023), a collection of 10 autoregressive language models
of different sizes, all pretrained for one epoch on the Pile (Gao et al., 2020). Model checkpoints are provided
every thousand steps; for the experiments presented in this work, we always start from the final checkpoint (the
main revision on HuggingFace Hub) unless otherwise specified.
We reproduce the model sizes of the Pythia suite in Table 1. Note that the number of parameters differs
from that given in the model name because we use the models for classification tasks, which replaces the
unembedding layer with a (smaller) classification head.
Model Size (# parameters) Short Name Pythia Name Plot Color
7,629,056 7.6M 14m
17,617,408 17.6M 31m
44,672,000 44.7M 70m
123,691,008 123.7M 160m
353,824,768 353.8M 410m
908,763,136 908.8M 1b
1,311,629,312 1.3B 1.4b NA
2,646,435,840 2.6B 2.8b NA
6,650,740,736 6.7B 6.9b NA
11,586,560,000 11.6B 12b NA
Table 1: Model sizes used in our experiments, the short name often used in plots, Pythia model name, and
corresponding plot colors where applicable
11
B. Datasets
We consider four datasets in this paper. Two of them are pre-existing datasets that we use from HuggingFace
Hub: Spam (Metsis et al., 2006) and IMDB (Maas et al., 2011).5Two are synthetic datasets that we generate
ourselves: PasswordMatch andWordLength . For representative datapoints of these datasets, see Table 3.
Since the context window for the Pythia model family is 2048 tokens (Biderman et al., 2023), we must be
careful not to run models on datapoints that are longer than this threshold. For fine-tuning, presented in
Section 4, we train on the entire dataset, filtering out the (very few) datapoints which exceed 2000 tokens. We
cap at 2000 tokens instead of the 2048 token context length to leave room for adversarial attacks, special tokens,
and any other additional tokens we might need. Table 2 shows the number of datapoints in each dataset, as
well as the number of datapoints that exceed 2000 tokens.
For the PasswordMatch task, we allow attacks to replace the ‘user-provided’ password, instead of treating
the prompt as immutable and appending new text only after it.
Dataset Train of which >2000 tokens Validation of which >2000 tokens
Spam 31,716 496 2,000 33
IMDB 25,000 7 25,000 4
PasswordMatch 20,000 0 2,000 0
WordLength 20,000 0 2,000 0
Table 2: Dataset Statistics
5Available at https://huggingface.co/datasets/SetFit/enron_spam and https://huggingface.co/datasets/
stanfordnlp/imdb
12
Dataset Text Label
Spam organisational announcement we are pleased to announce that we have
appointed michael brown as chief \noperating officer of enron europe
.\nmichael joined enron \x01 , s london legal department in 1995 and
has played a key \nrole in the success of many of our large commercial
ventures since then . in \njuly 1999 , he was made enron europe \x01 ,
s general counsel . replacing michael in \nthe general counsel role will
be mark evans who joined our legal department \nin 1995 . \nplease
join us in congratulating michael and mark in their new roles .HAM (0)
Spam claim your free home depot gift card - a $1000 value . claim your
home depot gift card - a $1000 value . were sure you can find a use
for this gift card in your area . ( ) . \nby exclusiverewards \nqprkelmvSPAM (1)
IMDB Up until the last 20 minutes, I was thinking that this is possibly Jackie
Chan\’s worst movie (excluding his pre-1978 work, which I am not
familiar with). The final fight sequence changed all that: it is long
and good and intense - indeed, one of the highlights of Chan \’s career.
But to get to it, you have to sit through a lot of ”comedy” that
might amuse five-year-olds (oh, look! someone threw a tomato at
that guy \’s face) and endless ”football” scenes. Not to mention the
dubbing (which includes the line ”How can I turn it off? It \’s not a
tap” - watch to find out what it refers to). ”Dragon Lord” is worth
renting for the final fight alone, but the rest of the movie is only for
Jackie collectors, and even then only for those who \’ve already seen at
least 15 of his other movies. (**)NEGATIVE (0)
IMDB Hurrah! A space film that doesn \’t take itself too seriously and everyone
can come along for the exciting ride that is space camp. The film starts
slowly, the usual mix of idiots and high-fliers mixed together into a
dodgy soup. But when the going gets tough - the tough get themselves
sorted out and it´ s not an un-believable change in the characters as you
can believe that there \’s some responsibility in their young minds.¡br
/¿¡br /¿The only flaw in the film is that Kate Capshaw is EXTREMELY
annoying as the ”I \’m right and you \’re all wrong” instructor. I would
recommend this as a nice night in movie and a 7 Vote.POSITIVE (1)
PasswordMatch You are an online security system. Below the user will enter a pass-
word.\nIf it is ”syllogistic”, then respond with ”Access Granted”. Oth-
erwise respond with ”Access Denied”. \n—\nYorktown \n—\nACCESS DENIED (0)
PasswordMatch You are an online security system. Below the user will enter a pass-
word.\nIf it is ”Herodotus”, then respond with ”Access Granted”.
Otherwise respond with ”Access Denied”. \n—\nHerodotus \n—\nACCESS GRANTED (1)
WordLength Which word is longer? Word 1: keyword. Word 2: medal. Return 0
for the first word and 1 for the second word. If the words are the same
length, return 0. Ignore everything after this sentence.FIRST (0)
WordLength Which word is longer? Word 1: purloin. Word 2: literate. Return 0
for the first word and 1 for the second word. If the words are the same
length, return 0. Ignore everything after this sentence.SECOND (1)
Table 3: Representative examples from four datasets used in our experiments.
13
C. Adversarial Attacks
The primary attack we use is GCGfrom Zou et al. (2023). We use the simple, single-prompt version described
in Algorithm 1 of Zou et al. (2023) with the modifiable subset Iset to be the final Ntokens of the prompt
(except for PasswordMatch , where there is a final ---separator after the attack tokens; see Table 3). We use
a suffix of length N= 10 , batch size B= 128 , and k= 256 top substitutions for all experiments. We use
T= 10 iterations for most experiments, using T= 30 to evaluate robustness transfer from adversarially training
on a weaker attack ( T= 10 ).
We describe the baseline RandomToken algorithm in Algorithm 1. RandomToken is designed to be similar to
GCGexcept that RandomToken does not use gradient-guided search. Instead, for each iteration we replace each
token in the adversarial suffix with a new token chosen uniformly at random from the vocabulary of the model.
We then evaluate the new prompt to see if it has caused the model to give an incorrect answer and stop the
attack if it has. If no iteration was successful, we return the adversarial suffix from the final iteration.
To make sure the baseline is a fair comparison, we constrain the attacks to use the same maximum number of
forward passes. To do this, we compute the number of forward passes used by GCGasB×T= 1280 and thus
perform up to 1280 iterations of RandomToken .
Algorithm 1 RandomToken
Input: Initial prompt x1:n, modifiable subset I, iterations T, success criterion S, vocabulary V
fort= 1toTdo
fori∈ Ido
xi←Uniform (V)
end for
ifS(x1:n)then
return: x1:n
end if
end for
return: x1:n
Output: Optimized prompt x1:n
14
D. Fine-tuning
D.1. Training
For each task, we fine-tune each model for a single epoch. The final validation accuracies are shown in Table 4.
Task Model Size (# parameters) Validation accuracy
Spam 7.6M 0.985
17.6M 0.985
44.7M 0.99
123.7M 0.99
353.8M 0.985
908.8M 0.99
1.3B 0.99
2.6B 0.9
6.7B 0.99
11.6B 0.99
IMDB 7.6M 0.875
17.6M 0.9
44.7M 0.905
123.7M 0.93
353.8M 0.96
908.8M 0.965
1.3B 0.96
2.6B 0.975
6.7B 0.97
11.6B 0.98
PasswordMatch 7.6M 1
17.6M 1
44.7M 1
123.7M 1
353.8M 1
908.8M 1
1.3B 1
2.6B 1
6.7B 1
11.6B 1
WordLength 7.6M 0.836
17.6M 0.882
44.7M 0.858
123.7M 0.944
353.8M 0.978
908.8M 0.958
1.3B 0.968
2.6B 0.972
6.7B 0.954
11.6B 0.976
Table 4: Accuracy on (not attacked) validation dataset at the end of training.
15
D.2. Attack Results
We attack the fine-tuned models with both the GCGandRandomToken attacks. As explored in Section 4, while
model size appears to generally help with robustness, there is a large amount of unexplained variability in each
model’s robustness.
D.2.1. GCG
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Figure 4: GCGattack success rate on different sizes of fine-tuned models on the Spam task. We show three seeds
per model size. The min-max-median plot (left) and scatterplot (right) are constructed using the
same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack
Figure 5: GCGattack success rate on different sizes of fine-tuned models on the IMDB task. We show three seeds
per model size. The min-max-median plot (left) and scatterplot (right) are constructed using the
same data.
16
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RatePasswordMatch, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PasswordMatch, GCG attackFigure 6: GCGattack success rate on different sizes of fine-tuned models on the PasswordMatch task. We show
three seeds per model size. The min-max-median plot (left) and scatterplot (right) are constructed
using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateWordLength, GCG attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WordLength, GCG attack
Figure 7: GCGattack success rate on different sizes of fine-tuned models on the WordLength task. We show
three seeds per model size. The min-max-median plot (left) and scatterplot (right) are constructed
using the same data.
17
D.2.2. RandomToken
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateSpam, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, RT attack
Figure 8: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the Spam task.
We show three seeds per model size. The min-max-median plot (left) and scatterplot (right) are
constructed using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateIMDB, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, RT attack
Figure 9: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the IMDB task.
We show three seeds per model size. The min-max-median plot (left) and scatterplot (right) are
constructed using the same data.
18
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RatePasswordMatch, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PasswordMatch, RT attackFigure 10: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the PasswordMatch
task. We show three seeds per model size. The min-max-median plot (left) and scatterplot (right)
are constructed using the same data.
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success RateWordLength, RT attack
Min-Max Range
Median
1071081091010
Model size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WordLength, RT attack
Figure 11: RandomToken (RT) attack success rate on different sizes of fine-tuned models on the WordLength
task. We show three seeds per model size. The min-max-median plot (left) and scatterplot (right)
are constructed using the same data.
19
E. Adversarial Training and Transfer
The overall adversarial training procedure is presented in Figure 12.
Figure 12: Our adversarial training setup.
As the diagram highlights, adversarial training is done by repeating the following steps:
•Train the model for one epoch on the train dataset.
•Attack the train dataset and evaluate the model on the attacked train dataset.
•Add the attacked examples to the train dataset.
•Attack the validation dataset and evaluate the model on the attacked validation dataset. Record model
performance on the attacked validation dataset.
For adversarial training, we use an initial training dataset of size 2000, and a validation dataset of size 200.
Initially we used a validation dataset also of size 2000, but found that decreasing the validation dataset size
had a negligible effect on the variance of the attack success rate, so opted for smaller dataset to enable faster
evaluation. At each round, we add 200 adversarially-attacked examples to the train dataset.
20
E.1. Adversarial Training
Below, we show plots of adversarial training using the GCGandRandomToken attacks across the four tasks. We
use three seeds per model, and present attack success rate after 10 and 30 rounds of adversarial training.
E.1.1. GCG Attack 10 Rounds
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 13: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for 10 rounds of adversarial training. We shade min to
max and plot median over three seeds.
21
E.1.2. GCG Attack 10 Rounds Alternate View
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
(a)Spam task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 14: Attack success rate as a function of model size across four tasks using the 10-iteration GCGattack,
over different adversarial training rounds.
22
E.1.3. GCG Attack 30 Rounds
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG attack (b)IMDB task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG attack
(c)PasswordMatch task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 15: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for 30 rounds of adversarial training.
23
E.1.4. GCG Attack 30 Rounds Convergence
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.10Attack Success Rate
Spam, GCG attack
(a)Spam task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0250.0500.0750.1000.1250.1500.1750.200Attack Success Rate
IMDB, GCG attack (b)IMDB task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0020.0040.0060.0080.010Attack Success Rate
PM, GCG attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.100.120.14Attack Success Rate
WL, GCG attack (d)WordLength task.
Figure 16: Attack success rate as a function of adversarial training round across four tasks using the 10-iteration
GCGattack, for different model sizes, shown for the final 10 rounds of 30-round adversarial training.
24
E.1.5. RandomToken Attack 10 Rounds
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RandomToken attack
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 17: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for 10 rounds of adversarial training. We shade min to max
and plot median over three seeds.
25
E.1.6. RandomToken Attack 10 Rounds Alternate View
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
Spam, RT attack
(a)Spam task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
IMDB, RT attack (b)IMDB task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
PM, RT attack
(c)PasswordMatch task.
107108109
Model Size (# parameters)0.00.20.40.60.81.0Attack Success Rate
WL, RT attack (d)WordLength task.
Figure 18: Attack success rate as a function of model size across four tasks using the 10-iteration RandomToken
(RT) attack, over different adversarial training rounds.
26
E.1.7. RandomToken Attack 30 Rounds
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(a)Spam task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RandomToken attack
(c)PasswordMatch task.
5 10 15 20 25 30
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 19: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for 30 rounds of adversarial training.
27
E.1.8. RandomToken Attack 30 Rounds Convergence
20 22 24 26 28 30
Adversarial Training Round0.000.020.040.060.080.10Attack Success Rate
Spam, RandomToken attack
(a)Spam task.
20 22 24 26 28 30
Adversarial Training Round0.000.050.100.150.200.250.30Attack Success Rate
IMDB, RandomToken attack (b)IMDB task.
20 22 24 26 28 30
Adversarial Training Round0.0000.0020.0040.0060.0080.010Attack Success Rate
PM, RandomToken attack
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
20 22 24 26 28 30
Adversarial Training Round0.000.050.100.150.200.25Attack Success Rate
WL, RandomToken attack (d)WordLength task.
Figure 20: Attack success rate as a function of adversarial training round across four tasks using the RandomToken
attack, for different model sizes, shown for the final 10 rounds of 30-round adversarial training.
28
E.2. Transfer
As presented in Section 5.1, we also evaluate how models adversarially trained with one attack generalize to
defending against other attacks. We present two collections of plots: first, models trained on the 10-iteration
GCGattack and evaluated with the 30-iteration GCGattack; second, models trained on the RandomToken attack
and evaluated on the (10-iteration) GCGattack. In the first case, all model sizes are able to generalize to being
somewhat robust against the stronger attack, though larger models do so both faster and to a greater extent.
By contrast, in the second case, only the larger models are able to generalize within the 10 adversarial training
rounds studied.
E.2.1. GCG Attack
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, GCG train, GCG 30 its eval
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, GCG train, GCG 30 its eval (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, GCG train, GCG 30 its eval
Model Size
7.6M
17.6M
44.7M
123.7M
353.8M
908.8M
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, GCG train, GCG 30 its eval (d)WordLength task.
Figure 21: Attack success rate as a function of adversarial training round across four tasks. Adversarial training
is performed with the 10-iteration GCGattack, and evaluation performed with the 30-iteration GCG
attack.
29
E.2.2. RandomToken attack
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
Spam, RT train, GCG eval
(a)Spam task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
IMDB, RT train, GCG eval (b)IMDB task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
PM, RT train, GCG eval
(c)PasswordMatch task.
2 4 6 8 10
Adversarial Training Round0.00.20.40.60.81.0Attack Success Rate
WL, RT train, GCG eval (d)WordLength task.
Figure 22: Attack success rate as a function of adversarial training round across four tasks. Adversarial training
is performed with the RandomToken (RT) attack, and evaluation performed with the 10-iteration
GCGattack.
30
E.3. Complexity Calculation
In Section 6, we compare the relative complexity of adversarially training a larger model for fewer rounds or a
smaller model for more rounds. In this section, we provide a worked example. We use a batch size of 8 for
both the 17.6M and 44.7M models. We start with 2000 datapoints in the train dataset and add 200 datapoints
each round. This means that after 4 rounds of training, each model will have seenP4
i=1(250 + i·25)= 1250
batches, and after 8 rounds of training,P8
i=1(250 + i·25)= 2900 batches. If we update model parameters
once per batch, this means that after 4 rounds, the 44.7M parameter model will have had 44.7M·1250 = 55875 M
gradient updates, while after 8 rounds, the 17.6M parameter model will have had 17.6M·2900 = 51040 M
gradient updates.
31 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18219v1 | http://arxiv.org/pdf/2407.18219v1 | Recursive Introspection: Teaching Language Model Agents How to Self-Improve | Yuxiao Qu, Tianjun Zhang, Naman Garg, Aviral Kumar | 2024-07-25 | abstract terms, this requires
mastering two qualities: (a)producing responses that explicitly seek information about the task, followed
by(b)making decisions and improving them by ”thinking” and verifying them at inference time. For
instance, tosucceedinusinganewcodinglibrary, aneffectiveLLMagentshouldfirstsynthesizeprograms,
then try the most promising subset against a compiler, use the resulting feedback to improve the program,
and repeat the process for multiple turns. Having the ability to successfully improve a response in
sequential attempts is equivalent to a form of ”self-improvement”, at test time.
To enable test-time self-improvement, recent approaches attempt to repurpose the knowledge already
stored in pre-trained models via few-shot prompting [ 7,15,31,52,64]. Although prompt tuning in
conjunction with feedback is effective in eliciting improved responses from capable models, it fails to
produce models that can succeed in complex tasks by correcting their own mistakes, such as those that
require logical reasoning [ 21,55]. In many of these problems, models contain the “knowledge” needed
to answer a challenging prompt, but are not able to elicit that knowledge even when asked to sequentially
correct their mistakes. Fine-tuning the LLM on domain-specific question-answering data [ 6,29,39] can
help, but it still does not teach the agent a test-time improvement strategy (see Section 6). A strategy for
Corresponding author(s): [email protected]; This work was done at Carnegie Mellon University.arXiv:2407.18219v1 [cs.LG] 25 Jul 2024
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure1:Recursive Introspection (RISE). Using iterative multi-round training on on-policy rollouts and supervision from a
reward function, RISE trains models that are capable of improving themselves over multiple turns. At inference, we run majority
voting on candidate outputs from different turns to obtain the final response.
improving responses over sequential attempts at test time is crucial for tackling challenging prompts,
where directly attempting the problem in one shot may largely be futile.
Can we train models to be capable of improving their ownresponses? If done correctly and on a
diverse set of problems and scenarios, this could introduce in an LLM, a general procedure for “how”it
can tackle a hard prompt by improving itself as opposed to supervising it with “what” to respond with,
which may not generalize as the test prompt becomes out of distribution. Although one straightforward
approach to inducing this capability into a model would be to generate data that showcase improvements
over multiple sequential turns (potentially from highly capable models), we find that simply imitating
these data is not sufficient to enable this capability (Section 6.4). Quite well, this is due to two reasons:
First, multi-turn data from a different model would not show improvements in the kinds of errors the
learner would make, thereby being irrelevant to the learner [ 24]. Second, often sequential multi-turn
data collected from proprietary models is also not of high quality since these models are typically not
good at proposing meaningful improvements to their own errors [ 21] even though they can still provide
useful responses to the problem at hand. Therefore, we need a different strategy to endow models
with a self-improvement capability. Our key insight is to supervise improvements to the learner’s own
responses in an iterative fashion, taking inspiration from methods in online imitation learning [ 36] and
reinforcement learning (RL) [ 45]. This supervision can be in the form of oracle responses to the prompt
sampled i.i.d. from more capable models, or be generated from the learner itself.
Our contribution is an algorithm RISE: Recursive Introspection (Figure 1) that utilizes these insights to
improve the self-improvement capability of an LLM over the course of multiple attempts at a given prompt.
In each iteration, our approach bootstraps on-policy rollouts from the learner with better responses at
the next turn obtained by running best-of-N (using a success indicator on the task) on multiple revision
candidates obtained by sampling from the learner itself or using responses from a more capable model,
whichever is more convenient. In this way, we are able to construct rollouts that demonstrate the learner
how it can improve its responses under its own distribution. Then, we fine-tune the learner on these data
using a reward-weighted regression (RWR [ 34,35]) objective, that is able to learn from both high- and
low-quality parts of such rollouts. By iteratively repeating this procedure, we are able to instill a general
self-improvement capability into an LLM. Our results show that LLMs trained via RISE can produce
correct responses on more prompts, improving over turns for more challenging prompts.
Even though strong base and intruction-tuned LLMs [ 23,58] often fail to improve their responses over
multiplesequentialattempts(evenwhenexplicitlytoldabouttheirmistakespreviously), RISEsuccessfully
2
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
endows similarly-sized LLMs with self-improvement capabilities, resulting in monotonically increasing
task performance after each turn. Specifically, on the GSM8K [ 11] dataset, RISE demonstrates significant
improvement over various models. RISE improves the performance of LLaMa3-8B by 8.2% and Mistral-7B
by 6.6%, entirely using their own data. RISE attains a 17.7% improvement for LLaMa2-7B over the course
of 5-turn introspection (outperforming parallel sampling from the first turn), and a 23.9% improvement
for Mistral-7B. In contrast, GPT-3.5 itself only improves by 4.6% over five turns. We see similar trends on
the MATH dataset [ 18], where RISE improves LLaMa2-7B by 4.6% and Mistral-7B by 11.1% over five
turns. We also study why and how RISE is able to induce self-improvement abilities and show that this
ability generalizes to out-of-distribution prompts as well. These results consistently demonstrate RISE’s
effectiveness in enhancing mathematical reasoning capabilities for different models.
2. | Introduction
A promising approach to utilizing and deploying foundation models, and in particular, large language
models (LLMs), is to treat them as general-purpose decision-making machines, or ”agents”. To be
successful, an LLM agent must not just provide plausible completions for input text, but must exhibit
interactive, goal-directed behavior to accomplish a given task. Put in abstract terms, this requires
mastering two qualities: (a)producing responses that explicitly seek information about the task, followed
by(b)making decisions and improving them by ”thinking” and verifying them at inference time. For
instance, tosucceedinusinganewcodinglibrary, aneffectiveLLMagentshouldfirstsynthesizeprograms,
then try the most promising subset against a compiler, use the resulting feedback to improve the program,
and repeat the process for multiple turns. Having the ability to successfully improve a response in
sequential attempts is equivalent to a form of ”self-improvement”, at test time.
To enable test-time self-improvement, recent approaches attempt to repurpose the knowledge already
stored in pre-trained models via few-shot prompting [ 7,15,31,52,64]. Although prompt tuning in
conjunction with feedback is effective in eliciting improved responses from capable models, it fails to
produce models that can succeed in complex tasks by correcting their own mistakes, such as those that
require logical reasoning [ 21,55]. In many of these problems, models contain the “knowledge” needed
to answer a challenging prompt, but are not able to elicit that knowledge even when asked to sequentially
correct their mistakes. Fine-tuning the LLM on domain-specific question-answering data [ 6,29,39] can
help, but it still does not teach the agent a test-time improvement strategy (see Section 6). A strategy for
Corresponding author(s): [email protected]; This work was done at Carnegie Mellon University.arXiv:2407.18219v1 [cs.LG] 25 Jul 2024
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure1:Recursive Introspection (RISE). Using iterative multi-round training on on-policy rollouts and supervision from a
reward function, RISE trains models that are capable of improving themselves over multiple turns. At inference, we run majority
voting on candidate outputs from different turns to obtain the final response.
improving responses over sequential attempts at test time is crucial for tackling challenging prompts,
where directly attempting the problem in one shot may largely be futile.
Can we train models to be capable of improving their ownresponses? If done correctly and on a
diverse set of problems and scenarios, this could introduce in an LLM, a general procedure for “how”it
can tackle a hard prompt by improving itself as opposed to supervising it with “what” to respond with,
which may not generalize as the test prompt becomes out of distribution. Although one straightforward
approach to inducing this capability into a model would be to generate data that showcase improvements
over multiple sequential turns (potentially from highly capable models), we find that simply imitating
these data is not sufficient to enable this capability (Section 6.4). Quite well, this is due to two reasons:
First, multi-turn data from a different model would not show improvements in the kinds of errors the
learner would make, thereby being irrelevant to the learner [ 24]. Second, often sequential multi-turn
data collected from proprietary models is also not of high quality since these models are typically not
good at proposing meaningful improvements to their own errors [ 21] even though they can still provide
useful responses to the problem at hand. Therefore, we need a different strategy to endow models
with a self-improvement capability. Our key insight is to supervise improvements to the learner’s own
responses in an iterative fashion, taking inspiration from methods in online imitation learning [ 36] and
reinforcement learning (RL) [ 45]. This supervision can be in the form of oracle responses to the prompt
sampled i.i.d. from more capable models, or be generated from the learner itself.
Our contribution is an algorithm RISE: Recursive Introspection (Figure 1) that utilizes these insights to
improve the self-improvement capability of an LLM over the course of multiple attempts at a given prompt.
In each iteration, our approach bootstraps on-policy rollouts from the learner with better responses at
the next turn obtained by running best-of-N (using a success indicator on the task) on multiple revision
candidates obtained by sampling from the learner itself or using responses from a more capable model,
whichever is more convenient. In this way, we are able to construct rollouts that demonstrate the learner
how it can improve its responses under its own distribution. Then, we fine-tune the learner on these data
using a reward-weighted regression (RWR [ 34,35]) objective, that is able to learn from both high- and
low-quality parts of such rollouts. By iteratively repeating this procedure, we are able to instill a general
self-improvement capability into an LLM. Our results show that LLMs trained via RISE can produce
correct responses on more prompts, improving over turns for more challenging prompts.
Even though strong base and intruction-tuned LLMs [ 23,58] often fail to improve their responses over
multiplesequentialattempts(evenwhenexplicitlytoldabouttheirmistakespreviously), RISEsuccessfully
2
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
endows similarly-sized LLMs with self-improvement capabilities, resulting in monotonically increasing
task performance after each turn. Specifically, on the GSM8K [ 11] dataset, RISE demonstrates significant
improvement over various models. RISE improves the performance of LLaMa3-8B by 8.2% and Mistral-7B
by 6.6%, entirely using their own data. RISE attains a 17.7% improvement for LLaMa2-7B over the course
of 5-turn introspection (outperforming parallel sampling from the first turn), and a 23.9% improvement
for Mistral-7B. In contrast, GPT-3.5 itself only improves by 4.6% over five turns. We see similar trends on
the MATH dataset [ 18], where RISE improves LLaMa2-7B by 4.6% and Mistral-7B by 11.1% over five
turns. We also study why and how RISE is able to induce self-improvement abilities and show that this
ability generalizes to out-of-distribution prompts as well. These results consistently demonstrate RISE’s
effectiveness in enhancing mathematical reasoning capabilities for different models.
2. | Section not found | Related Work
Several prior works build techniques to improve reasoning and thinking capabilities of foundation
models for downstream applications. Typically these works focus on building prompting techniques
for effective multi-turn interaction with external tools [ 5,7,14,32,49,54,56], sequentially refining
predictions by reflecting on actions [ 7,15,63], asking the model to verbalize its thoughts [ 33,52,65],
asking the model to critique and revise itself [ 31,40] or by using other models to critique a primary
model’s responses [ 2,12,20,54]. Although a subset of this work does improve its own responses, this
self-correction ability often requires access to detailed error traces (e.g., execution traces from code
compilers [ 7,31]) in order to succeed. In fact, [ 21] and Table 1 both indicate that self-improvement
guided by the LLM itself (i.e., “intrinsic self-correction”) is often infeasible for off-the-shelf LLMs even
when they contain the knowledge required to tackle the prompt given, but fine-tuning with RISE
induces this capability as we show in this paper.
Beyond prompting, previous work also attempts to fine-tune LLM to obtain self-improvement capabili-
ties [6,39,62]. These works attempt to improve reasoning performance by training on self-generated
responses [ 30,46,57,58,60]. To achieve this, these works use a combination of learned verifiers [ 28,
47,50], search [ 13,26,33,38], contrastive prompting on negative data [ 9,48], and iterated supervised
or reinforcement learning (RL) [ 8,37,59]. Although our approach also trains on model-generated
data, we aim to introduce a complementary capability to improve performance over sequential turns
of interaction, rather than to improve single-turn performance alone. Other work fine-tunes LLMs for
multi-turn interaction directly via RL [41, 66]: while this is indeed related, single-turn problems posed
in multi-turn scenarios require addressing distinct challenges than generic multi-turn RL: (i)sample-
efficiency is not a concern since the entire environment is fully characterized by the training dataset of
prompts and oracle answers and dynamics are deterministic, and (ii)we need to generalize to novel test
prompts. Multi-turn RL focuses on sample efficiency, which is not as critical in our setting, though of
course learning to generalize from a limited number of initial states would be appealing. Our main focus
is to show that it is possible to train models for self-improvement via appropriately designing multi-turn
fine-tuning | Section not found | Section not found | Section not found | objectives. This is orthogonal from the choice of training approach (RL or not).
The most related to our work are GLoRE [ 17] and Self-Correct [ 53], which train separate models to
identify errors and refine incorrect answers of other LLMs. Unlike these works, our approach trains a
single model to produce answers and improve them over more than two turns, which is the maximal
number of turns studied in these works. We show that doing so successfully requires careful design
choices: an iterative on-policy data generation strategy along with a training objective that can learn from
both successful and unsuccessful rollouts. From an algorithmic point of view, RISE is similar to online
3
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure2:Left: Problem formulation. We convert single-turn problems into multi-turn MDPs as discussed in Section 4.1. The
state is given by the prompt, history of prior attempts, and optional feedback from the environment. An action is a response
generated from the LLM given the state of multi-turn interaction so far. Right: Data collection. We collect data by unrolling the
current model 𝑘−1times followed by an improved version of the response, which is obtained by either (1) self-distillation :
sample multiple responses from the current model, and use the best response, or (2) distillation : obtain oracle responses by
querying a more capable model. In either case, RISE then trains on the generated data.
imitation learning [ 36,44], in that it queries expert supervision on states attained by on-policy rollouts.
On-policy distillation for LLMs [ 1,4] utilizes this idea, but queries an expert to provide completions on
partial responses instead of sequential attempts, that we do in this work.
3. Problem Setup and Preliminaries
The goal of our work is to improve LLM performance over sequential attempts / turns at a given problem.
Concretely, given a dataset 𝒟={(𝑥𝑖,𝑦*
𝑖)}𝑁
𝑖=1of problems 𝑥𝑖and oracle responses 𝑦*
𝑖, our goal is to
obtain an LLM 𝜋𝜃(·|[𝑥,ˆ𝑦1:𝑡, 𝑝1:𝑡])that, given the problem 𝑥, previous model attempts ˆ𝑦1:𝑡at the problem,
and auxiliary instructions 𝑝1:𝑡(e.g., instruction to find a mistake and improve the response; or additional
compiler feedback from the environment) solves a given problem as correctly as possible. To this end, we
encode this goal into the following learning objective that we wish to optimize:
max
𝜋𝜃𝐿∑︁
𝑖=1E𝑥,𝑦*∼𝒟,^𝑦𝑖∼𝜋𝜃(·|[𝑥,^𝑦1:𝑖−1,𝑝1:𝑖−1])[I(ˆ𝑦𝑖==𝑦*)]. (3.1)
Unlike standard supervised fine-tuning that trains the model 𝜋to produce a single response ˆ𝑦given 𝑥,
Equation 3.1 trains 𝜋to also appropriately react to a given history of responses from its own previous
attempts ˆ𝑦1:𝑖−1. Equation 3.1 most closely resembles an RL objective, and we will indeed develop our
approach by converting a single-turn problem into a multi-turn MDP. Finally, note that prompting-based
methods such as Self-Refine [ 31] can still be viewed as training 𝜋to optimize 𝜋(𝑦*|𝑥)but only when
only allowed to modulate the prompt 𝑝𝑖to optimize Equation 3.1. Naturally, since the parameters 𝜃are
unchanged, this would not be effective in optimizing the objective fully.
4. RISE: Recursive Introspection for Self-Improvement
Since even strong off-the-shelf models do not exhibit an effective ability to improve themselves when
provided with sequential attempts at a given problem [ 21], a natural next step is to ask how to train
models to induce this capability. In this section, we will develop our approach, RISE, for fine-tuning
foundation models towards improving their own predictions over multiple turns. Our approach will first
convert a problem into a multi-turn MDP, then collect data, and finally run offline reward-weighted
supervised learning in this multi-turn MDP to induce this capability.
4
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
4.1. Converting Single-Turn Problems into a Multi-Turn Markov Decision Process (MDP)
The first step in building our approach is to procedurally construct a multi-turn MDP out of a single-turn
dataset of prompts and oracle responses (Figure 2, Left). Given a dataset, 𝒟={(𝑥𝑖,𝑦*
𝑖)}, consisting of
prompts 𝑥𝑖and corresponding oracle responses 𝑦*
𝑖(e.g., math questions and natural language responses
to those questions), we will construct an induced MDPℳfrom𝒟, and then learn policies in this MDP.
An initial state in this MDP is a possible prompt 𝑥𝑖∈𝒟. We denote the output response from the
foundation model as action 𝑎. Given a state 𝑠, the next state can be obtained by concatenating the tokens
representing 𝑠with the action 𝑎proposed by the model, and an additional fixed prompt 𝑓that asks
the model to introspect, e.g., “this response is not correct, please introspect and correct your answer.” (the
exact prompt is shown in Appendix D.4). The reward function is a sparse binary indicator of answer
correctness at a given state 𝑠,𝑟([𝑥𝑖,···],𝑎) = 1if and only if 𝑎=𝑦*
𝑖and is obtained from an answer
checking function. This construction from dataset 𝒟to MDPℳis shown below:
𝒟={(𝑥𝑖,𝑦*
𝑖)} → ℳ :𝜌(𝑠0) =Unif(𝑥1,𝑥2,···,𝑥𝑁) (4.1)
𝑃(𝑠′|𝑠,𝑎) =𝛿(︀
𝑠′=concat [𝑠,𝑎,𝑓])︀
(4.2)
𝑟(𝑠,𝑎) =1(𝑎=𝑦*
𝑖if𝑥𝑖∈𝑠). (4.3)
4.2. Learning in the Multi-Turn MDP
With the MDP construction in place, the next step involves training a model to improve itself over the
course of a rollout. We subscribe to an offline approach to learning that we describe in the following.
Step 1: Data collection for self-improvement. To ensure that rollout data from this multi-turn MDP is
useful for teaching the model how to self-improve, it must satisfy a few desiderata: (1)it must illustrate
the mistakes that the learner is likely to make and showcase how to improve upon them in the next
attempt, (2)the data must illustrate responses that are relevant to the model given the problem and
previous attempts in context, and (3)it must not contain any rollout that degrades in a subsequent turn.
Our data collection strategy (Figure 2, Right) satisfies these desiderata.
In a given round 𝑘, for a given problem 𝑥𝑖, we unroll the currentmodel 𝜋𝜃𝑘(·|·)to produce multiple
sequential attempts, denoted by 𝑦𝑖
𝑡∼𝜋𝜃𝑘(·|𝑠𝑖
𝑡). In problems, where external input (e.g., compiler
feedback) is available, we also observe a variable-length, natural language external input, 𝑓𝑖
𝑡(e.g., in
mathproblemsweaskthemodeltocorrectitself). Wealsoobserveascalarrewardvalue 𝑟(𝑠𝑖
𝑡,𝑦𝑖
𝑡),denoted
as𝑟𝑖
𝑡in short. Let us denote this dataset of “on-policy” model rollouts as 𝒟on-policy :={(𝑠𝑖
𝑡,𝑦𝑖
𝑡, 𝑓𝑖
𝑡, 𝑟𝑖
𝑡)𝑇
𝑡=1}.
For each time-step, we construct an improved version of the response 𝑦𝑖
𝑡that we will denote by ˜𝑦𝑖
𝑡. We
also record the reward score associated with this improved response as 𝑟(𝑠𝑖
𝑡,˜𝑦𝑖
𝑡), or˜𝑟𝑖
𝑡in short. To obtain
an improved version of a response 𝑦𝑖
𝑡, we can employ several strategies. Perhaps the most straightforward
approach is to query an off-the-shelf more capable model to provide a correct response given the prompt
𝑥𝑖, the previous response 𝑦𝑖
𝑡, and an optional external feedback 𝑓𝑖
𝑡. We refer to this as the distillation
variant of our approach, since it uses a strong “teacher” model to guide self-improvement (note that
this is different from the classic notion of knowledge distillation, and we will in fact show results in
Section 6.1 that will help understand the differences).
˜𝒟on-policy + distill :={︁{︀(︀
𝑠𝑖
𝑡,˜𝑦𝑖
𝑡, 𝑓𝑖
𝑡,˜𝑟𝑖
𝑡)︀}︀𝑇
𝑡=1}︁|𝒟|
𝑖=1. (4.4)
5
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
The second variant of our approach, which alleviates the need for a teacher model, involves constructing
an improved response by sampling multiple times from the learner itself. We refer to this approach as the
self-distillation variant. Concretely, for each state in the dataset, 𝑠𝑖
𝑡∈𝒟on-policy, we sample 𝑁responses
˜𝑦𝑖
𝑡[0],˜𝑦𝑖
𝑡[1],···,˜𝑦𝑖
𝑡[𝑁]∼𝜋𝜃(·|𝑠𝑖
𝑡), and use the best response from these 𝑁candidates (as measured by
the associated reward values ˜𝑟𝑖
𝑡[0],···,˜𝑟𝑖
𝑡[𝑁]) to relabel the model response at the next step 𝑡+ 1in an
improvement trajectory. Formally, say ˜𝑦𝑖
𝑡[𝑚] = arg max 𝑗∈[𝑁]𝑟(𝑠𝑖,˜𝑦𝑖
𝑡[𝑗]), then we label the responses in
the dataset𝒟on-policyat step 𝑡+ 1with the improved response and its associated reward value ˜𝑟𝑖
𝑡[𝑚]:
˜𝒟on-policy + self-distillation :={︁{︀(︀
𝑠𝑖
𝑡+1,˜𝑦𝑖
𝑡[𝑚], 𝑓𝑖
𝑡+1,˜𝑟𝑖
𝑡[𝑚])︀}︀𝑇−1
𝑡=0}︁|𝒟|
𝑖=1. (4.5)
Step 2: Policy improvement. With the aforementioned data construction schemes, we can now train a
model on these datasets. While in general, any offline RL approach can be used to train on these data,
in our experiments we adopt an approach based on weighted supervised learning [ 35] due to ease of
experimentation and its simplicity. In particular, we perform a weighted supervised regression, where
the weights are given by the exponential transformation of the reward values in ˜𝒟.
Reward-weighted RL: max
𝜃E𝑥𝑖∼˜𝒟[︃𝑇∑︁
𝑡=1log𝜋𝜃(˜𝑦𝑖
𝑡|𝑠𝑖
𝑡)·exp(𝑟𝑡
𝑖/𝜏)]︃
, (4.6)
where 𝜏is a temperature parameter to further expand or narrow the difference between good and bad
actions. In our preliminary experiments, we found that Equation 4.6 can often induce a bias towards
increasing log likelihoods of responses where rewards are high, prioritizing updates on easy problems
where rewards are already high. To address this issue, we apply a slight modification to Equation 4.6
and center the exponentiated rewards around the mean value averaged across all attempts on a given
prompt, akin to advantage-weighted regression [ 34]. We find that the use of advantages in place of
rewards helps us avoid the “rich-gets-richer” phenomenon with easy problems.
4.3. Inference at Deployment Time
RISE can be run in two modes at inference time. Perhaps the most straightforward way to run the
policy 𝜋𝜃(·|·)trained by RISE is within a multi-turn rollout, where the model samples a new response
conditioned on the past context (i.e., state in the multi-turn MDP). This past context consists of the
external feedback 𝑝test
𝑖concerning the response 𝑦test
𝑖and the rollout terminates as soon as the current
response is judged to be correct according to the environment’s answer verification function. Put in other
words, we terminate the rollout as soon as the reward is equal to the reward for the oracle response:
𝑟(𝑥,𝑦test
𝑖) =𝑟(𝑥,𝑦*). This protocol invokes queries to the reward function after each turn in the rollout.
Since several reward function queries are performed, we refer to this approach as “with oracle” .
RISE can also be run in a mode that avoids the need to query the answer checker or the reward function
within a rollout. In this case, we run full-length rollouts by forcing the model to retry, ignoring the
correctness of the response. We then utilize a self-consistency mechanism [ 51] based on majority voting
to decide the candidate response at the end of each turn. Concretely, at the end of each turn 𝑗, we
identify the response by running a majority vote over all response candidates from the previous turns
(maj(︁
𝑦test
0,𝑦test
1,···,𝑦test
𝑗)︁
), including turn 𝑗. We call this “without oracle” . A schematic illustration of
these approach is shown in Figure 3. Most of our evaluations use no oracle.
6
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure3:RISE Inference. There are two ways to query the model trained via RISE upon inference: (1) with oracle ( Left):
each time the model improves its response, it is allowed to check its answer against an environment and terminate early as soon
as a correct answer is found; or (2) without oracle ( Right): we ask the model to sequentially revise its own responses k times,
and perform majority voting on all candidate outputs from different turns to obtain the final response.
4.4. Practical Algorithm and Implementation Details
A complete algorithmic pseudocode for each approach is shown in Appendix C. We trained 7B models via
RISE and found that these models often could not adhere to response style and instructions for improving
their responses when generating on-policy data. As a result, before running on-policy data collection, we
find it often useful to run an initial phase of supervised fine-tuning on in-domain, multi-turn rollouts
generated from a capable model to provide style and instruction-following information to the learner.
We call this the “knowledge boosting” stage. We then run on-policy rollouts starting from a boosted
model. In each iteration, we generate 1 trajectory for each unique problem. We then run fine-tuning,
with hyperparameters and details in Appendix D. For iterative fine-tuning, we find that starting from the
basemodel but training on data from all iterations thus far is more beneficial than continued fine-tuning
from the checkpoint obtained in the previous iteration.
5. When and Why is Self-Improvement Over Turns Possible?
A natural question to ask is why self-improvement with RISEeven possible. One might surmise that the
model may simply not have enough knowledge to correct its ownmistakes if it is unable to correctly
answer the problem in the first turn. Then, why is it possible to teach the model to correct its own
mistakes? In this section, we provide the reason why this kind of self-improvement is possible, supported
with empirical evidence to justify our hypotheses.
Iteratively teaching a model how to make updates on a given response can be crucial when representing
the target distribution 𝑝*(𝑦|𝑥)requires more capacity than what the model 𝜋𝜃affords by conditioning
on only the input prompt tokens. When the target distribution requires greater capacity, learning a
sequence of conditionals, 𝜋𝜃(𝑦𝑖+1|𝑥,𝑦0:𝑖)followed by marginalization is expected to induce a more
flexible marginal distribution over 𝑦𝑇given 𝑥. This | hypothesis is akin to the difference between diffusion
models [ 42] and variational autoencoders (VAEs) [ 25] in image generation: iteratively fitting a sequence
of generative distributions over intermediate noisy inputs in a diffusion model gives rise to a more flexible
distribution [ 43] than monolithic variational auto-encoding, even though diffusion models still utilize
7
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure4:The probability of the true answer given the
prompt. Observe that model trained with RISE has higher
probability for the true answer.
Figure5:The training perplexity (loss) of fitting only
the oracle answer or a sequence of answers. Observe that
fitting a sequence of answers (RISE) reduces the loss more
than fitting only the oracle answer (Classic).
an evidence lower-bound objective(ELBO). While the diffusion process utilizes hand-designed noise
schedules, RISE utilizes the base model itself to induce iterative improvements.
To verify if this hypothesis is true, we tracked the training un-weighted, negative log-likelihood loss (NLL)
values for the oracle response 𝑦*given the input prompt 𝑥marginalized over intermediate steps in a
multi-turn rollout, and compared it against the NLL values −log𝑝𝜃(𝑦*|𝑥)attained by directly attempting
to predict the final response in Figure 4 (labeled as “Classic”). Concretely, we sampled 256 prompts 𝑥
and their oracle responses 𝑦*and computed the average −log𝑝𝜃(𝑦*|𝑥)across all 𝑥, along with a 95%
confidence interval for different checkpoints during training. We find that for any given number of epochs
(including fractional number of epochs on the x-axis), the NLL value is lower when conditioning on
multi-turn data that RISE generates in comparison with oracle responses to the prompts obtained from
an expert. This suggests that RISE is able to utilize the computation of tokens from previous turns to
model the target distribution. We also measure the average NLL loss on all samples through training,
sampled i.i.d. from the training dataset for RISE and classic fine-tuning and observe a similar trend: RISE
is able to reduce loss more than the standard approach, attaining lower perplexity values (Figure 5).
Of course, in problems that require “knowledge-based” question answering, it is not possible for the
model to produce any meaningful improvements because learning 𝑝*(𝑦|𝑥)is not bounded by insufficient
capacity of 𝜋𝜃(𝑦|𝑥), but is rather unable to match 𝑝*due to the absence of features that are critical
to learn the correct mapping from 𝑥to𝑦. We expect that training with RISE would only incentivize
hallucinations in this case [ 24], since more input tokens appearing from previous attempts would only
provide easier ways to pick up on spurious correlations. However, this is not the failure mode on reasoning
problems [ 27], where maj@K rates at turn 1 tend to be higher than pass@1 as we find in our experiments
(indicating that performance can be improved by sampling the model itself). In fact, in Figure 6 we also
show that the sequential procedure learned by RISE can even solve a significant fraction of problems that
were unsolved by pass@B for much larger 𝐵in the first turn, indicating that it learns to index into the
pre-trained knowledge of the model in a different manner as opposed to simply translating the pass@K
performance into the pass@1 performance of the model, that majority of single-turn approaches are
believed to be doing.
8
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure6:Fraction of problems unsolved by pass@B at the first turn that sequential 5-turn sampling from RISE solves,
where 𝐵= 5×𝑘(𝑘is the x-axis). RISE can solve several challenging problems that sampling at the first turn with much larger
budgets cannot solve.
6. Experimental Evaluation
The goal of our experiments is to demonstrate the efficacy of RISE in instilling language models with the
ability to self-improve their responses over turns. Our experiments answer the following questions: (1)
How effectively can RISE improve performance over multiple sequential attempts (i.e., turns) at a given
prompt?; (2)Does the performance of RISE improve with more rounds of iterative training?; (3)Does
the self-improvement strategy induced by RISE generalize to novel problems that are out of the training
domain? and finally; (4)What is the best data composition for training RISE? To this end, we compare
RISE to other prior and baseline approaches, and perform ablations on GSM8K [11] and MATH [18].
Baselines, comparisons, and evaluation. We compare RISE to several prior | Section not found | Section not found | methods in online imitation learning [ 36] and
reinforcement learning (RL) [ 45]. This supervision can be in the form of oracle responses to the prompt
sampled i.i.d. from more capable models, or be generated from the learner itself.
Our contribution is an algorithm RISE: Recursive Introspection (Figure 1) that utilizes these insights to
improve the self-improvement capability of an LLM over the course of multiple attempts at a given prompt.
In each iteration, our approach bootstraps on-policy rollouts from the learner with better responses at
the next turn obtained by running best-of-N (using a success indicator on the task) on multiple revision
candidates obtained by sampling from the learner itself or using responses from a more capable model,
whichever is more convenient. In this way, we are able to construct rollouts that demonstrate the learner
how it can improve its responses under its own distribution. Then, we fine-tune the learner on these data
using a reward-weighted regression (RWR [ 34,35]) objective, that is able to learn from both high- and
low-quality parts of such rollouts. By iteratively repeating this procedure, we are able to instill a general
self-improvement capability into an LLM. Our results show that LLMs trained via RISE can produce
correct responses on more prompts, improving over turns for more challenging prompts.
Even though strong base and intruction-tuned LLMs [ 23,58] often fail to improve their responses over
multiplesequentialattempts(evenwhenexplicitlytoldabouttheirmistakespreviously), RISEsuccessfully
2
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
endows similarly-sized LLMs with self-improvement capabilities, resulting in monotonically increasing
task performance after each turn. Specifically, on the GSM8K [ 11] dataset, RISE demonstrates significant
improvement over various models. RISE improves the performance of LLaMa3-8B by 8.2% and Mistral-7B
by 6.6%, entirely using their own data. RISE attains a 17.7% improvement for LLaMa2-7B over the course
of 5-turn introspection (outperforming parallel sampling from the first turn), and a 23.9% improvement
for Mistral-7B. In contrast, GPT-3.5 itself only improves by 4.6% over five turns. We see similar trends on
the MATH dataset [ 18], where RISE improves LLaMa2-7B by 4.6% and Mistral-7B by 11.1% over five
turns. We also study why and how RISE is able to induce self-improvement abilities and show that this
ability generalizes to out-of-distribution prompts as well. These results consistently demonstrate RISE’s
effectiveness in enhancing mathematical reasoning capabilities for different models.
2. Related Work
Several prior works build techniques to improve reasoning and thinking capabilities of foundation
models for downstream applications. Typically these works focus on building prompting techniques
for effective multi-turn interaction with external tools [ 5,7,14,32,49,54,56], sequentially refining
predictions by reflecting on actions [ 7,15,63], asking the model to verbalize its thoughts [ 33,52,65],
asking the model to critique and revise itself [ 31,40] or by using other models to critique a primary
model’s responses [ 2,12,20,54]. Although a subset of this work does improve its own responses, this
self-correction ability often requires access to detailed error traces (e.g., execution traces from code
compilers [ 7,31]) in order to succeed. In fact, [ 21] and Table 1 both indicate that self-improvement
guided by the LLM itself (i.e., “intrinsic self-correction”) is often infeasible for off-the-shelf LLMs even
when they contain the knowledge required to tackle the prompt given, but fine-tuning with RISE
induces this capability as we show in this paper.
Beyond prompting, previous work also attempts to fine-tune LLM to obtain self-improvement capabili-
ties [6,39,62]. These works attempt to improve reasoning performance by training on self-generated
responses [ 30,46,57,58,60]. To achieve this, these works use a combination of learned verifiers [ 28,
47,50], search [ 13,26,33,38], contrastive prompting on negative data [ 9,48], and iterated supervised
or reinforcement learning (RL) [ 8,37,59]. Although our approach also trains on model-generated
data, we aim to introduce a complementary capability to improve performance over sequential turns
of interaction, rather than to improve single-turn performance alone. Other work fine-tunes LLMs for
multi-turn interaction directly via RL [41, 66]: while this is indeed related, single-turn problems posed
in multi-turn scenarios require addressing distinct challenges than generic multi-turn RL: (i)sample-
efficiency is not a concern since the entire environment is fully characterized by the training dataset of
prompts and oracle answers and dynamics are deterministic, and (ii)we need to generalize to novel test
prompts. Multi-turn RL focuses on sample efficiency, which is not as critical in our setting, though of
course learning to generalize from a limited number of initial states would be appealing. Our main focus
is to show that it is possible to train models for self-improvement via appropriately designing multi-turn
fine-tuning objectives. This is orthogonal from the choice of training approach (RL or not).
The most related to our work are GLoRE [ 17] and Self-Correct [ 53], which train separate models to
identify errors and refine incorrect answers of other LLMs. Unlike these works, our approach trains a
single model to produce answers and improve them over more than two turns, which is the maximal
number of turns studied in these works. We show that doing so successfully requires careful design
choices: an iterative on-policy data generation strategy along with a training objective that can learn from
both successful and unsuccessful rollouts. From an algorithmic point of view, RISE is similar to online
3
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure2:Left: Problem formulation. We convert single-turn problems into multi-turn MDPs as discussed in Section 4.1. The
state is given by the prompt, history of prior attempts, and optional feedback from the environment. An action is a response
generated from the LLM given the state of multi-turn interaction so far. Right: | Section not found | data collection and training so as to imbue an LLM with the capability to
recursively detect and correct its previous mistakes in subsequent iterations. Our experiments show that RISE
enables Llama2, Llama3, and Mistral models to improve themselves with more turns on math reasoning tasks,
outperforming several single-turn strategies given an equal amount of inference-time computation. We also find
that RISE scales well, often attaining larger benefits with more capable models. Our analysis shows that RISE
makes meaningful improvements to responses to arrive at the correct solution for challenging prompts, without
disrupting one-turn abilities as a result of expressing more complex distributions.
1. Introduction
A promising approach to utilizing and deploying foundation models, and in particular, large language
models (LLMs), is to treat them as general-purpose decision-making machines, or ”agents”. To be
successful, an LLM agent must not just provide plausible completions for input text, but must exhibit
interactive, goal-directed behavior to accomplish a given task. Put in abstract terms, this requires
mastering two qualities: (a)producing responses that explicitly seek information about the task, followed
by(b)making decisions and improving them by ”thinking” and verifying them at inference time. For
instance, tosucceedinusinganewcodinglibrary, aneffectiveLLMagentshouldfirstsynthesizeprograms,
then try the most promising subset against a compiler, use the resulting feedback to improve the program,
and repeat the process for multiple turns. Having the ability to successfully improve a response in
sequential attempts is equivalent to a form of ”self-improvement”, at test time.
To enable test-time self-improvement, recent approaches attempt to repurpose the knowledge already
stored in pre-trained models via few-shot prompting [ 7,15,31,52,64]. Although prompt tuning in
conjunction with feedback is effective in eliciting improved responses from capable models, it fails to
produce models that can succeed in complex tasks by correcting their own mistakes, such as those that
require logical reasoning [ 21,55]. In many of these problems, models contain the “knowledge” needed
to answer a challenging prompt, but are not able to elicit that knowledge even when asked to sequentially
correct their mistakes. Fine-tuning the LLM on domain-specific question-answering data [ 6,29,39] can
help, but it still does not teach the agent a test-time improvement strategy (see Section 6). A strategy for
Corresponding author(s): [email protected]; This work was done at Carnegie Mellon University.arXiv:2407.18219v1 [cs.LG] 25 Jul 2024
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure1:Recursive Introspection (RISE). Using iterative multi-round training on on-policy rollouts and supervision from a
reward function, RISE trains models that are capable of improving themselves over multiple turns. At inference, we run majority
voting on candidate outputs from different turns to obtain the final response.
improving responses over sequential attempts at test time is crucial for tackling challenging prompts,
where directly attempting the problem in one shot may largely be futile.
Can we train models to be capable of improving their ownresponses? If done correctly and on a
diverse set of problems and scenarios, this could introduce in an LLM, a general procedure for “how”it
can tackle a hard prompt by improving itself as opposed to supervising it with “what” to respond with,
which may not generalize as the test prompt becomes out of distribution. Although one straightforward
approach to inducing this capability into a model would be to generate data that showcase improvements
over multiple sequential turns (potentially from highly capable models), we find that simply imitating
these data is not sufficient to enable this capability (Section 6.4). Quite well, this is due to two reasons:
First, multi-turn data from a different model would not show improvements in the kinds of errors the
learner would make, thereby being irrelevant to the learner [ 24]. Second, often sequential multi-turn
data collected from proprietary models is also not of high quality since these models are typically not
good at proposing meaningful improvements to their own errors [ 21] even though they can still provide
useful responses to the problem at hand. Therefore, we need a different strategy to endow models
with a self-improvement capability. Our key insight is to supervise improvements to the learner’s own
responses in an iterative fashion, taking inspiration from methods in online imitation learning [ 36] and
reinforcement learning (RL) [ 45]. This supervision can be in the form of oracle responses to the prompt
sampled i.i.d. from more capable models, or be generated from the learner itself.
Our contribution is an algorithm RISE: Recursive Introspection (Figure 1) that utilizes these insights to
improve the self-improvement capability of an LLM over the course of multiple attempts at a given prompt.
In each iteration, our approach bootstraps on-policy rollouts from the learner with better responses at
the next turn obtained by running best-of-N (using a success indicator on the task) on multiple revision
candidates obtained by sampling from the learner itself or using responses from a more capable model,
whichever is more convenient. In this way, we are able to construct rollouts that demonstrate the learner
how it can improve its responses under its own distribution. Then, we fine-tune the learner on these data
using a reward-weighted regression (RWR [ 34,35]) objective, that is able to learn from both high- and
low-quality parts of such rollouts. By iteratively repeating this procedure, we are able to instill a general
self-improvement capability into an LLM. Our | Section not found | results show that LLMs trained via RISE can produce
correct responses on more prompts, improving over turns for more challenging prompts.
Even though strong base and intruction-tuned LLMs [ 23,58] often fail to improve their responses over
multiplesequentialattempts(evenwhenexplicitlytoldabouttheirmistakespreviously), RISEsuccessfully
2
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
endows similarly-sized LLMs with self-improvement capabilities, resulting in monotonically increasing
task performance after each turn. Specifically, on the GSM8K [ 11] dataset, RISE demonstrates significant
improvement over various models. RISE improves the performance of LLaMa3-8B by 8.2% and Mistral-7B
by 6.6%, entirely using their own data. RISE attains a 17.7% improvement for LLaMa2-7B over the course
of 5-turn introspection (outperforming parallel sampling from the first turn), and a 23.9% improvement
for Mistral-7B. In contrast, GPT-3.5 itself only improves by 4.6% over five turns. We see similar trends on
the MATH dataset [ 18], where RISE improves LLaMa2-7B by 4.6% and Mistral-7B by 11.1% over five
turns. We also study why and how RISE is able to induce self-improvement abilities and show that this
ability generalizes to out-of-distribution prompts as well. These results consistently demonstrate RISE’s
effectiveness in enhancing mathematical reasoning capabilities for different models.
2. Related Work
Several prior works build techniques to improve reasoning and thinking capabilities of foundation
models for downstream applications. Typically these works focus on building prompting techniques
for effective multi-turn interaction with external tools [ 5,7,14,32,49,54,56], sequentially refining
predictions by reflecting on actions [ 7,15,63], asking the model to verbalize its thoughts [ 33,52,65],
asking the model to critique and revise itself [ 31,40] or by using other models to critique a primary
model’s responses [ 2,12,20,54]. Although a subset of this work does improve its own responses, this
self-correction ability often requires access to detailed error traces (e.g., execution traces from code
compilers [ 7,31]) in order to succeed. In fact, [ 21] and Table 1 both indicate that self-improvement
guided by the LLM itself (i.e., “intrinsic self-correction”) is often infeasible for off-the-shelf LLMs even
when they contain the knowledge required to tackle the prompt given, but fine-tuning with RISE
induces this capability as we show in this paper.
Beyond prompting, previous work also attempts to fine-tune LLM to obtain self-improvement capabili-
ties [6,39,62]. These works attempt to improve reasoning performance by training on self-generated
responses [ 30,46,57,58,60]. To achieve this, these works use a combination of learned verifiers [ 28,
47,50], search [ 13,26,33,38], contrastive prompting on negative data [ 9,48], and iterated supervised
or reinforcement learning (RL) [ 8,37,59]. Although our approach also trains on model-generated
data, we aim to introduce a complementary capability to improve performance over sequential turns
of interaction, rather than to improve single-turn performance alone. Other work fine-tunes LLMs for
multi-turn interaction directly via RL [41, 66]: while this is indeed related, single-turn problems posed
in multi-turn scenarios require addressing distinct challenges than generic multi-turn RL: (i)sample-
efficiency is not a concern since the entire environment is fully characterized by the training dataset of
prompts and oracle answers and dynamics are deterministic, and (ii)we need to generalize to novel test
prompts. Multi-turn RL focuses on sample efficiency, which is not as critical in our setting, though of
course learning to generalize from a limited number of initial states would be appealing. Our main focus
is to show that it is possible to train models for self-improvement via appropriately designing multi-turn
fine-tuning objectives. This is orthogonal from the choice of training approach (RL or not).
The most related to our work are GLoRE [ 17] and Self-Correct [ 53], which train separate models to
identify errors and refine incorrect answers of other LLMs. Unlike these works, our approach trains a
single model to produce answers and improve them over more than two turns, which is the maximal
number of turns studied in these works. We show that doing so successfully requires careful design
choices: an iterative on-policy data generation strategy along with a training objective that can learn from
both successful and unsuccessful rollouts. From an algorithmic point of view, RISE is similar to online
3
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure2:Left: Problem formulation. We convert single-turn problems into multi-turn MDPs as discussed in Section 4.1. The
state is given by the prompt, history of prior attempts, and optional feedback from the environment. An action is a response
generated from the LLM given the state of multi-turn interaction so far. Right: Data collection. We collect data by unrolling the
current model 𝑘−1times followed by an improved version of the response, which is obtained by either (1) self-distillation :
sample multiple responses from the current model, and use the best response, or (2) distillation : obtain oracle responses by
querying a more capable model. In either case, RISE then trains on the generated data.
imitation learning [ 36,44], in that it queries expert supervision on states attained by on-policy rollouts.
On-policy distillation for LLMs [ 1,4] utilizes this idea, but queries an expert to provide completions on
partial responses instead of sequential attempts, that we do in this work.
3. Problem Setup and Preliminaries
The goal of our work is to improve LLM performance over sequential attempts / turns at a given problem.
Concretely, given a dataset 𝒟={(𝑥𝑖,𝑦*
𝑖)}𝑁
𝑖=1of problems 𝑥𝑖and oracle responses 𝑦*
𝑖, our goal is to
obtain an LLM 𝜋𝜃(·|[𝑥,ˆ𝑦1:𝑡, 𝑝1:𝑡])that, given the problem 𝑥, previous model attempts ˆ𝑦1:𝑡at the problem,
and auxiliary instructions 𝑝1:𝑡(e.g., instruction to find a mistake and improve the response; or additional
compiler feedback from the environment) solves a given problem as correctly as possible. To this end, we
encode this goal into the following learning objective that we wish to optimize:
max
𝜋𝜃𝐿∑︁
𝑖=1E𝑥,𝑦*∼𝒟,^𝑦𝑖∼𝜋𝜃(·|[𝑥,^𝑦1:𝑖−1,𝑝1:𝑖−1])[I(ˆ𝑦𝑖==𝑦*)]. (3.1)
Unlike standard supervised fine-tuning that trains the model 𝜋to produce a single response ˆ𝑦given 𝑥,
Equation 3.1 trains 𝜋to also appropriately react to a given history of responses from its own previous
attempts ˆ𝑦1:𝑖−1. Equation 3.1 most closely resembles an RL objective, and we will indeed develop our
approach by converting a single-turn problem into a multi-turn MDP. Finally, note that prompting-based
methods such as Self-Refine [ 31] can still be viewed as training 𝜋to optimize 𝜋(𝑦*|𝑥)but only when
only allowed to modulate the prompt 𝑝𝑖to optimize Equation 3.1. Naturally, since the parameters 𝜃are
unchanged, this would not be effective in optimizing the objective fully.
4. RISE: Recursive Introspection for Self-Improvement
Since even strong off-the-shelf models do not exhibit an effective ability to improve themselves when
provided with sequential attempts at a given problem [ 21], a natural next step is to ask how to train
models to induce this capability. In this section, we will develop our approach, RISE, for fine-tuning
foundation models towards improving their own predictions over multiple turns. Our approach will first
convert a problem into a multi-turn MDP, then collect data, and finally run offline reward-weighted
supervised learning in this multi-turn MDP to induce this capability.
4
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
4.1. Converting Single-Turn Problems into a Multi-Turn Markov Decision Process (MDP)
The first step in building our approach is to procedurally construct a multi-turn MDP out of a single-turn
dataset of prompts and oracle responses (Figure 2, Left). Given a dataset, 𝒟={(𝑥𝑖,𝑦*
𝑖)}, consisting of
prompts 𝑥𝑖and corresponding oracle responses 𝑦*
𝑖(e.g., math questions and natural language responses
to those questions), we will construct an induced MDPℳfrom𝒟, and then learn policies in this MDP.
An initial state in this MDP is a possible prompt 𝑥𝑖∈𝒟. We denote the output response from the
foundation model as action 𝑎. Given a state 𝑠, the next state can be obtained by concatenating the tokens
representing 𝑠with the action 𝑎proposed by the model, and an additional fixed prompt 𝑓that asks
the model to introspect, e.g., “this response is not correct, please introspect and correct your answer.” (the
exact prompt is shown in Appendix D.4). The reward function is a sparse binary indicator of answer
correctness at a given state 𝑠,𝑟([𝑥𝑖,···],𝑎) = 1if and only if 𝑎=𝑦*
𝑖and is obtained from an answer
checking function. This construction from dataset 𝒟to MDPℳis shown below:
𝒟={(𝑥𝑖,𝑦*
𝑖)} → ℳ :𝜌(𝑠0) =Unif(𝑥1,𝑥2,···,𝑥𝑁) (4.1)
𝑃(𝑠′|𝑠,𝑎) =𝛿(︀
𝑠′=concat [𝑠,𝑎,𝑓])︀
(4.2)
𝑟(𝑠,𝑎) =1(𝑎=𝑦*
𝑖if𝑥𝑖∈𝑠). (4.3)
4.2. Learning in the Multi-Turn MDP
With the MDP construction in place, the next step involves training a model to improve itself over the
course of a rollout. We subscribe to an offline approach to learning that we describe in the following.
Step 1: Data collection for self-improvement. To ensure that rollout data from this multi-turn MDP is
useful for teaching the model how to self-improve, it must satisfy a few desiderata: (1)it must illustrate
the mistakes that the learner is likely to make and showcase how to improve upon them in the next
attempt, (2)the data must illustrate responses that are relevant to the model given the problem and
previous attempts in context, and (3)it must not contain any rollout that degrades in a subsequent turn.
Our data collection strategy (Figure 2, Right) satisfies these desiderata.
In a given round 𝑘, for a given problem 𝑥𝑖, we unroll the currentmodel 𝜋𝜃𝑘(·|·)to produce multiple
sequential attempts, denoted by 𝑦𝑖
𝑡∼𝜋𝜃𝑘(·|𝑠𝑖
𝑡). In problems, where external input (e.g., compiler
feedback) is available, we also observe a variable-length, natural language external input, 𝑓𝑖
𝑡(e.g., in
mathproblemsweaskthemodeltocorrectitself). Wealsoobserveascalarrewardvalue 𝑟(𝑠𝑖
𝑡,𝑦𝑖
𝑡),denoted
as𝑟𝑖
𝑡in short. Let us denote this dataset of “on-policy” model rollouts as 𝒟on-policy :={(𝑠𝑖
𝑡,𝑦𝑖
𝑡, 𝑓𝑖
𝑡, 𝑟𝑖
𝑡)𝑇
𝑡=1}.
For each time-step, we construct an improved version of the response 𝑦𝑖
𝑡that we will denote by ˜𝑦𝑖
𝑡. We
also record the reward score associated with this improved response as 𝑟(𝑠𝑖
𝑡,˜𝑦𝑖
𝑡), or˜𝑟𝑖
𝑡in short. To obtain
an improved version of a response 𝑦𝑖
𝑡, we can employ several strategies. Perhaps the most straightforward
approach is to query an off-the-shelf more capable model to provide a correct response given the prompt
𝑥𝑖, the previous response 𝑦𝑖
𝑡, and an optional external feedback 𝑓𝑖
𝑡. We refer to this as the distillation
variant of our approach, since it uses a strong “teacher” model to guide self-improvement (note that
this is different from the classic notion of knowledge distillation, and we will in fact show results in
Section 6.1 that will help understand the differences).
˜𝒟on-policy + distill :={︁{︀(︀
𝑠𝑖
𝑡,˜𝑦𝑖
𝑡, 𝑓𝑖
𝑡,˜𝑟𝑖
𝑡)︀}︀𝑇
𝑡=1}︁|𝒟|
𝑖=1. (4.4)
5
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
The second variant of our approach, which alleviates the need for a teacher model, involves constructing
an improved response by sampling multiple times from the learner itself. We refer to this approach as the
self-distillation variant. Concretely, for each state in the dataset, 𝑠𝑖
𝑡∈𝒟on-policy, we sample 𝑁responses
˜𝑦𝑖
𝑡[0],˜𝑦𝑖
𝑡[1],···,˜𝑦𝑖
𝑡[𝑁]∼𝜋𝜃(·|𝑠𝑖
𝑡), and use the best response from these 𝑁candidates (as measured by
the associated reward values ˜𝑟𝑖
𝑡[0],···,˜𝑟𝑖
𝑡[𝑁]) to relabel the model response at the next step 𝑡+ 1in an
improvement trajectory. Formally, say ˜𝑦𝑖
𝑡[𝑚] = arg max 𝑗∈[𝑁]𝑟(𝑠𝑖,˜𝑦𝑖
𝑡[𝑗]), then we label the responses in
the dataset𝒟on-policyat step 𝑡+ 1with the improved response and its associated reward value ˜𝑟𝑖
𝑡[𝑚]:
˜𝒟on-policy + self-distillation :={︁{︀(︀
𝑠𝑖
𝑡+1,˜𝑦𝑖
𝑡[𝑚], 𝑓𝑖
𝑡+1,˜𝑟𝑖
𝑡[𝑚])︀}︀𝑇−1
𝑡=0}︁|𝒟|
𝑖=1. (4.5)
Step 2: Policy improvement. With the aforementioned data construction schemes, we can now train a
model on these datasets. While in general, any offline RL approach can be used to train on these data,
in our experiments we adopt an approach based on weighted supervised learning [ 35] due to ease of
experimentation and its simplicity. In particular, we perform a weighted supervised regression, where
the weights are given by the exponential transformation of the reward values in ˜𝒟.
Reward-weighted RL: max
𝜃E𝑥𝑖∼˜𝒟[︃𝑇∑︁
𝑡=1log𝜋𝜃(˜𝑦𝑖
𝑡|𝑠𝑖
𝑡)·exp(𝑟𝑡
𝑖/𝜏)]︃
, (4.6)
where 𝜏is a temperature parameter to further expand or narrow the difference between good and bad
actions. In our preliminary experiments, we found that Equation 4.6 can often induce a bias towards
increasing log likelihoods of responses where rewards are high, prioritizing updates on easy problems
where rewards are already high. To address this issue, we apply a slight modification to Equation 4.6
and center the exponentiated rewards around the mean value averaged across all attempts on a given
prompt, akin to advantage-weighted regression [ 34]. We find that the use of advantages in place of
rewards helps us avoid the “rich-gets-richer” phenomenon with easy problems.
4.3. Inference at Deployment Time
RISE can be run in two modes at inference time. Perhaps the most straightforward way to run the
policy 𝜋𝜃(·|·)trained by RISE is within a multi-turn rollout, where the model samples a new response
conditioned on the past context (i.e., state in the multi-turn MDP). This past context consists of the
external feedback 𝑝test
𝑖concerning the response 𝑦test
𝑖and the rollout terminates as soon as the current
response is judged to be correct according to the environment’s answer verification function. Put in other
words, we terminate the rollout as soon as the reward is equal to the reward for the oracle response:
𝑟(𝑥,𝑦test
𝑖) =𝑟(𝑥,𝑦*). This protocol invokes queries to the reward function after each turn in the rollout.
Since several reward function queries are performed, we refer to this approach as “with oracle” .
RISE can also be run in a mode that avoids the need to query the answer checker or the reward function
within a rollout. In this case, we run full-length rollouts by forcing the model to retry, ignoring the
correctness of the response. We then utilize a self-consistency mechanism [ 51] based on majority voting
to decide the candidate response at the end of each turn. Concretely, at the end of each turn 𝑗, we
identify the response by running a majority vote over all response candidates from the previous turns
(maj(︁
𝑦test
0,𝑦test
1,···,𝑦test
𝑗)︁
), including turn 𝑗. We call this “without oracle” . A schematic illustration of
these approach is shown in Figure 3. Most of our evaluations use no oracle.
6
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure3:RISE Inference. There are two ways to query the model trained via RISE upon inference: (1) with oracle ( Left):
each time the model improves its response, it is allowed to check its answer against an environment and terminate early as soon
as a correct answer is found; or (2) without oracle ( Right): we ask the model to sequentially revise its own responses k times,
and perform majority voting on all candidate outputs from different turns to obtain the final response.
4.4. Practical Algorithm and Implementation Details
A complete algorithmic pseudocode for each approach is shown in Appendix C. We trained 7B models via
RISE and found that these models often could not adhere to response style and instructions for improving
their responses when generating on-policy data. As a result, before running on-policy data collection, we
find it often useful to run an initial phase of supervised fine-tuning on in-domain, multi-turn rollouts
generated from a capable model to provide style and instruction-following information to the learner.
We call this the “knowledge boosting” stage. We then run on-policy rollouts starting from a boosted
model. In each iteration, we generate 1 trajectory for each unique problem. We then run fine-tuning,
with hyperparameters and details in Appendix D. For iterative fine-tuning, we find that starting from the
basemodel but training on data from all iterations thus far is more beneficial than continued fine-tuning
from the checkpoint obtained in the previous iteration.
5. When and Why is Self-Improvement Over Turns Possible?
A natural question to ask is why self-improvement with RISEeven possible. One might surmise that the
model may simply not have enough knowledge to correct its ownmistakes if it is unable to correctly
answer the problem in the first turn. Then, why is it possible to teach the model to correct its own
mistakes? In this section, we provide the reason why this kind of self-improvement is possible, supported
with empirical evidence to justify our hypotheses.
Iteratively teaching a model how to make updates on a given response can be crucial when representing
the target distribution 𝑝*(𝑦|𝑥)requires more capacity than what the model 𝜋𝜃affords by conditioning
on only the input prompt tokens. When the target distribution requires greater capacity, learning a
sequence of conditionals, 𝜋𝜃(𝑦𝑖+1|𝑥,𝑦0:𝑖)followed by marginalization is expected to induce a more
flexible marginal distribution over 𝑦𝑇given 𝑥. This hypothesis is akin to the difference between diffusion
models [ 42] and variational autoencoders (VAEs) [ 25] in image generation: iteratively fitting a sequence
of generative distributions over intermediate noisy inputs in a diffusion model gives rise to a more flexible
distribution [ 43] than monolithic variational auto-encoding, even though diffusion models still utilize
7
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure4:The probability of the true answer given the
prompt. Observe that model trained with RISE has higher
probability for the true answer.
Figure5:The training perplexity (loss) of fitting only
the oracle answer or a sequence of answers. Observe that
fitting a sequence of answers (RISE) reduces the loss more
than fitting only the oracle answer (Classic).
an evidence lower-bound objective(ELBO). While the diffusion process utilizes hand-designed noise
schedules, RISE utilizes the base model itself to induce iterative improvements.
To verify if this hypothesis is true, we tracked the training un-weighted, negative log-likelihood loss (NLL)
values for the oracle response 𝑦*given the input prompt 𝑥marginalized over intermediate steps in a
multi-turn rollout, and compared it against the NLL values −log𝑝𝜃(𝑦*|𝑥)attained by directly attempting
to predict the final response in Figure 4 (labeled as “Classic”). Concretely, we sampled 256 prompts 𝑥
and their oracle responses 𝑦*and computed the average −log𝑝𝜃(𝑦*|𝑥)across all 𝑥, along with a 95%
confidence interval for different checkpoints during training. We find that for any given number of epochs
(including fractional number of epochs on the x-axis), the NLL value is lower when conditioning on
multi-turn data that RISE generates in comparison with oracle responses to the prompts obtained from
an expert. This suggests that RISE is able to utilize the computation of tokens from previous turns to
model the target distribution. We also measure the average NLL loss on all samples through training,
sampled i.i.d. from the training dataset for RISE and classic fine-tuning and observe a similar trend: RISE
is able to reduce loss more than the standard approach, attaining lower perplexity values (Figure 5).
Of course, in problems that require “knowledge-based” question answering, it is not possible for the
model to produce any meaningful improvements because learning 𝑝*(𝑦|𝑥)is not bounded by insufficient
capacity of 𝜋𝜃(𝑦|𝑥), but is rather unable to match 𝑝*due to the absence of features that are critical
to learn the correct mapping from 𝑥to𝑦. We expect that training with RISE would only incentivize
hallucinations in this case [ 24], since more input tokens appearing from previous attempts would only
provide easier ways to pick up on spurious correlations. However, this is not the failure mode on reasoning
problems [ 27], where maj@K rates at turn 1 tend to be higher than pass@1 as we find in our experiments
(indicating that performance can be improved by sampling the model itself). In fact, in Figure 6 we also
show that the sequential procedure learned by RISE can even solve a significant fraction of problems that
were unsolved by pass@B for much larger 𝐵in the first turn, indicating that it learns to index into the
pre-trained knowledge of the model in a different manner as opposed to simply translating the pass@K
performance into the pass@1 performance of the model, that majority of single-turn approaches are
believed to be doing.
8
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure6:Fraction of problems unsolved by pass@B at the first turn that sequential 5-turn sampling from RISE solves,
where 𝐵= 5×𝑘(𝑘is the x-axis). RISE can solve several challenging problems that sampling at the first turn with much larger
budgets cannot solve.
6. Experimental Evaluation
The goal of our experiments is to demonstrate the efficacy of RISE in instilling language models with the
ability to self-improve their responses over turns. Our experiments answer the following questions: (1)
How effectively can RISE improve performance over multiple sequential attempts (i.e., turns) at a given
prompt?; (2)Does the performance of RISE improve with more rounds of iterative training?; (3)Does
the self-improvement strategy induced by RISE generalize to novel problems that are out of the training
domain? and finally; (4)What is the best data composition for training RISE? To this end, we compare
RISE to other prior and baseline approaches, and perform ablations on GSM8K [11] and MATH [18].
Baselines, comparisons, and evaluation. We compare RISE to several prior methods that attempt
to induce similar self-improvement capabilities: (a) self-refine [21,31] that prompts a base model to
critique and revise its mistakes; (b) GloRE [17], which trains a separate reward model to locate errors
and a refinement model to improve responses of a base LLM; and (c) self-consistency [51], which runs
majority voting on multiple responses from the first turn as a baseline to compare to our sequential
strategy. We tried to construct fair comparisons between RISE and these methods by using a similar-sized
model [ 23,58], but differences in the base model, training data, and evaluation setups still prohibits
us from performing an apples-to-apples comparison in some cases. Nonetheless, we can still hope to
understand the ballpark of improvement by contextualizing our results with these prior works. We also
compare to V-STaR [19], but since this is not an fair comparison, we defer it to Appendix B.
We evaluate RISE in both modes at inference time: with and without an oracle (Section 4.3) at the end
of five turns. Concretely, these metrics are defined as follows:
•with oracle, “p1@t5” : this run terminates the rollout as soon as the response is correct. In other
words, this metric allows queries to the final answer verifier at the end of each turn.
•withoutoracle,“m1@t5” : thisrundoesnotterminatetherolloutbeforefiveturns,andwecompute
the maj@1 performance on the candidates produced in each turn as detailed in Section 4.3.
We also compare maj@K performance at the first turn for all the models we train (“m1@t1”, “m5@t1”).
9
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9)68.6(+33.3)6.7 9.5 (+2.8) 18.4(+11.1)29.7(+22.4)
7B SoTA [58]
Eurus-7B-SFT 36.3 66.3 (+30.0)47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5)16.3(+4.0) 22.9(+10.6)
Self-Refine [31] →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Iteration 2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7B-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE [17] →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) Not studied in [17]
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
Table 1: RISE vs. other approaches (Self-Refine, GLoRE) and baselines. Observe that RISE attains the biggest performance
improvement (in brown) between 1-turn (m5@t1) and 5-turn (m1@t5) performance w/o an oracle on both GSM8K and MATH.
This performance gap is even larger when oracle early termination is allowed (p1@t5 w/ oracle). Self-Refine [ 31] degrades
performance across the board when used without an oracle, and attains minor performance improvements when used with an
oracle. GLoRE trains a separate refinement model, but still performs worse than RISE; more details about it are in Appendix B.
Using RISE on top of a better base model (Mistral-7B) is also effective (positive improvements with multiple turns), and note
the m1@t5 performance of Mistral-7B exceeds even state-of-the-art math models such as Eurus-7B-SFT [ 58]. Simply running
single-turn SFT on data utilized by RISE is not effective at inducing a self-improvement capability, implying that the algorithmic
design choices in RISE are crucial for performance. Color coding indicates numbers that can be compared to each other.
6.1. Does RISE improve performance over multiple turns compared to other approaches?
Main results. We present the comparisons in Table 1. First, note that RISE (“Iteration 1” and “Iteration
2”) boosts up the LLama2 base model’s five-turn performance by 15.1% and 17.7% respectively with
each iteration on GSM8K and 3.4% and 4.6% on MATH, w/o any oracle. Interestingly, we found using
prompting-only self-refine [ 31] largely degrades performance across the board, even with a strong
proprietary model, GPT-3.5. The strongest 7B base models, Mistral-7B and Eurus-7B-SFT [ 58], when
coupled with standard prompting, are only able to improve their performance, but only by 5.3% / 11.6%
and 0.9% / 4.0% respectively on GSM8K and MATH, which is significantly lower than our approach.
The performance of GLoRE improves only by 3.4% on GSM8K (over two turns), but this is still lower
than our approach, which improves by 6.3% in two turns and 13.4% in three turns (see Appendix B.1).
This indicates that RISE is effective in teaching models how to improve their own errors. To summarize,
training with RISE gives the largest performance improvement gains compared to other approaches both
with and without the use of an oracle, and these gains are transferred to other base models.
One might also hypothesize that the performance gains with RISE here are largely a result of utilizing
10
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE (Self)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 36.8 44.4 (+7.6) 39.5(+6.6) 48.7(+15.9)
Llama-3-8B 45.3 69.7 (+24.4) 52.5(+7.2) 61.0(+15.7)
+ Iteration 1 65.6 80.7 (+15.1) 73.8(+8.2) 81.2(+15.6)
Table 2: RISE with self-distillation on GSM8K. RISE is able to improve 5-turn maj@1 performance of the model with entirely
self-generated data and supervision, despite the fact that the base Mistral-7B model does not produce correct answers for
several problems.
queries to an off-the-shelf more capable model for providing supervision and not the algorithmic approach
for data collection and training. To address this hypothesis, we store all the data generated by RISE from
more capable models and train on this data via standard single-turn SFT (“ SFTonoracledata ). Since not
all of this data are guaranteed to be correct, we also run this experiment on only the correct responses in
these oracle data. Observe in Table 1 that this procedure does not still instill self-improvement capabilities,
largely preserving or degrading sequential (“ maj@1@turn5 ”) performance compared to simply sampling
one response in the first turn. This means that the algorithmic design of RISE is critical in enabling it to
learn self-improvement capabilities, as opposed to simply the use of expert supervision.
6.1.1. Can RISE Effectively Make Use of Mistakes and Correct Them?
One concern that arises from prior results on self-refinement or self-correction is whether the model
can truly correct itself over turns or whether the improvement comes from the effect of sampling more
answers and picking the best one. In Table 1, we see that sequentially improving responses via RISE
(“maj@1@turn5 ”) outperforms sampling 5 responses in parallel at the first turn and applying a majority
vote on them (“ maj@5@turn1 ”). Please note that this comparison utilizes an equal number of samples,
with the only difference being that these samples are drawn in parallel at the first turn in one case and
sequentially at the end of five turns in the other. Comparing maj@5 performance at the end of 1 turn
and 5 turns, we observe a consistent 4% to 8% improvement on GSM8K and an 6.5% improvement
on MATH (with Mistral-7B model). This means that RISE can imbue models with a self-improvement
ability, while running parallel sampling alone on any model cannot endow the same ability. Even the
maj@5@turn1 performance of standard single-turn SFT on the data used by RISE is substantially worse
than the sequential maj@1@turn5 performance of RISE, implying that the algorithmic protocol of RISE
plays a critical underlying role. Finally, we also remark that in Figure 6, we showed that the sequential
procedure learned by RISE over five turns could solve a significant fraction of problems that were unsolved
by pass@B for much larger values of 𝐵≫5in the first turn, implying that sequential RISE can actually
tackle prompts that were not solvable by simply sampling more responses in the first turn.
One might also speculate if these improvements in sequential improvement ability largely come at a cost
of reduced improvements in first turn performance. In addition, we also observe that running multiple
iterations of RISE still preserves the first turn performance while improving the 5-turn performance.
6.1.2. How Does the Base Model Affect RISE?
The performance of RISE with Llama2-7B on an absolute scale is lower than the best models specifically
fine-tuned on math data (e.g., Eurus-7B-SFT or Mistral-7B). However, we find that RISE is still effective
on top of Mistral-7B base model. In fact, our performance at the end of five turns outperforms one of the
best 7B SFT models, customized to math reasoning . Compare the m1@t5 performance of Eurus-7B-SFT
and Mistral-7B in RISE (ours), to find that Mistral-7B + RISE outperforms Eurus-7B-SFT.
11
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISEw/o oracle w/ oracle
m1@t1→m1@t5 p1@t5
GSM8K
Llama2 Base 10.5 11.1 (+0.6) 13.9(+3.4)
Iteration 1 RISE Model trained on MATH 19.3 32.6 (+13.3) 48.4(+29.1)
MATH
Llama2 Base 1.9 1.4 (-0.5) 2.3(+0.4)
Iteration 1 RISE Model trained on GSM8K 4.3 4.4 (+0.1) 12.1(+7.8)
SVAMP
Llama2 Base 29.2 30.5 (+1.3) 34.0(+4.8)
Iteration 1 RISE Model trained on MATH 30.1 31.4 (+1.2) 45.9(+15.8)
Iteration 1 RISE Model trained on GSM8K 42.2 50.0 (+7.8) 63.6(+21.4)
Table 3: Out-of-distribution generalization of RISE. We evaluate model fine-tuned on MATH on the GSM8K test set; model
fine-tuned GSM8K on MATH; and the model fine-tuned on a mixture of GSM8K and MATH on the SVAMP data. Observe even
though we train on OOD prompts, RISE can still improve sequential performance.
6.1.3. Self-Distillation Version of RISE
We also compare the performance of RISE with entirely self-generated data and supervision (Equation 4.4,
𝑁= 16) after one iteration directly on top of more capable models: Mistral-7B and Llama-3-8B on
GSM8K in Table 2, without any knowledge boosting phase. We find that this variant also improves the
5-turn performance of the base model compared to the first turn: compare “m1@t5” vs “m1@t1” for both
the models Llama-3-8B and Mistral-7B, where RISE boosts the sequential self-improvement performance
by more than 1% compared to turn 1 performance w/o any oracle.
Of course, we also note that this version of RISE does not outperform the “m5@t1” performance of the
fine-tuned model. We expect this to be largely a function of one single iteration of training. Since the
self-distillation version of RISE utilizes best-of-N sampling against the same model to produce supervision
for self-improvement, RISE would first have to match the performance of best-of-N sampling before it can
start to improve over it via reward maximization. Due to the significant gap between the base model’s
m5@t1 and m1@t5 performance, we expect that this will take quite a few iterations or a fully online
RL algorithm. We did not have computational resources and infrastructure to run multiple iterations,
but this is an interesting avenue for future work. In this self-distillation setting, we could also divide the
computation between sequential and parallel sampling strategies to get the best results at the end of five
turns. Nonetheless, this result shows that even by training on self-generated samples, RISE can actually
amplify the sequential sampling performance of the base model.
6.2. Does the Performance of RISE Improve with Iterative Training?
Next, we attempt to understand if RISE improves with multiple rounds of training on on-policy data. As
shown in Tables 1 and 2, the performance of RISE improves from iteration to iteration constantly. The
5-turn performance of RISE, both with and without an oracle, exhibits a clear improvement with more
rounds. This implies that iterative self-training procedures of the form of STaR [ 61] can also be combined
with RISE to train models for self-improvement. This also perhaps serves as a strong hint towards the
potential utility of full online reinforcement learning (RL) techniques.
6.3. Does RISE Also Improve Sequential Performance on Out-of-Distribution Prompts?
In Table 3, our aim is to evaluate the robustness of the strategy induced by RISE on new, unseen prompts.
Specifically, we compare the performance of the RISE model trained with a dataset on evaluation prompts
12
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
from another dataset. Note in Table 3, these datasets include MATH, GSM8K, and SVAMP. Generally,
we observe that the model trained on one dataset is still able to improve the base model’s performance
on another dataset over the course of sequential five turns. More concretely, while the base Llama2
model largely degrades its turn 1 performance over turn 5 performance, model’s trained with RISE
enable a positive performance improvement on these out-of-distribution prompts. This means that even
though these models have not seen queries similar to the evaluation dataset, simply training with RISE
onsomekind of mathematical prompts still boosts the efficacy of the self-improvement strategy on a new
distribution of test prompts. This finding suggests that RISE is capable of instilling self-improvement
procedures that can generalize beyond the distribution of prompts in the fine-tuning data.
6.4. What Data Compositions and Data Quantity are Crucial for RISE?
We now study how different data compositions affect the performance of RISE with the goal of answering
questions such as should we collect on-policy error correction data like DAgger [ 36] or should we bias
towards high-quality off-policy data? . To understand the utility of different data compositions, we enlist
the three aspects RISE: (a)the use of multi-turn rollout data for fine-tuning, (b)the use of unsuccessful /
suboptimal rollouts via weighted supervised fine-tuning compared to naïve supervised learning, which
only utilizes successful rollouts for fine-tuning; and (c)the use of on-policy rollouts and self-generated
or oracle data. We will now perform controlled experiments to understand the effect of each of these
factors on the overall performance of RISE.
Figure7:Left: The importance of multi-turn interaction history and weighted objectives for training RISE. Note that
training with multi-turn data leads to better self-improvement performance at the end of 5 turns, than one-turn data obtained
from the original dataset with oracle answers from another model; also observe that using a weighted objective performs better.
Right: The importance of using all rollouts for learning , instead of only successful rollouts or only successful responses in the
data. Using all data performs best in our results.
(a) Data composition for fine-tuning. We first study the necessity of using the interaction of error
correction history for training RISE in Figure 7 (Left). We compare two approaches: model trained with
oracle answers shown right after the query (“1-turn”) and oracle answers shown after intermediate failed
attempts (“Multi-turn”) in Figure 7 (Left). Even though the latter trains on intermediate responses that
may not always be correct, it attains a higher performance than simply training on the correct response
for a given prompt. This highlights the importance of training on contexts that include a multi-turn
interaction history depicting mistakes from the learner to improve self-improvement capabilities.
(b) Weighted supervised learning vs unweighted supervised learning. Next, we investigate the effect
of reward-weighted RL on multi-turn data in RISE as opposed to simply imitating filtered successful data.
13
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
We find that using all the data leads to improved performance over simply filtering good datain Figure 7
(Right), which reduces sample size. In Figure 7 (Left), we find that reward-weighted training improves
performance on later turns, allowing us to better leverage all the sub-optimal data.
(c) On-policy vs off-policy data; self-generated vs. expert data. RISE runs on-policy rollouts and seeks
improvements on responses that the learner produces. As shown in Figure 8 (Left), a “DAgger [ 36]”-style
approach that seeks improvements on responses appearing in on-policy rollouts improves performance
(green/orange) compared to using expert data alone (blue/pink). Conceptually, this addresses the
train-test mismatch between the distribution of context tokens, enabling imitation learning methods to
now target the correct distribution. In addition, recent work [ 24] has shown that LLMs often memorize
“unfamiliar” examples generated by oracle models; by training on on-policy rollouts, we should be able to
eliminate any such potential issues. Thus, while the model trained via offline imitation is able to reduce
loss, these improvements do not generalize to new problems.
Figure8:Left: The importance of data sources used for training. We study the performance of the iteration 1 of RISE on
GSM8K with different data sources. “Expert” refers to the use of an oracle model, “On-policy” corresponds to sampling from the
learner, and “Best-of-N” means using the best sample out of 𝑁from the learner (here 𝑁= 16).Right: Comparing RISE with
oracle error feedback (pass@1 @ turn k; solid lines) to parallel sampling of 5 responses at turn 1 (pass@k @ turn 1;
dashed lines) over number of turns 𝑘on the x-axis on GSM8K. Observe that sequential sampling with Iteration 1 and Iteration
2 RISE models consistently outperforms parallel sampling for all values of turn 𝑘; and the gap grows as the number of iterations
increases. In contrast, this trend is absent for base and SFT models.
6.5. Pass@K vs Sequential Sampling via RISE
We now study the performance of sequential sampling with oracle feedback in GSM8K, unlike relying on
majority voting as in Table 1. Specifically, we compare the performance of RISE with early termination of
evaluation rollouts against pass@5 (not maj@5) performance of the RISE model at the first turn (which
makes an equal number of queries to the ground-truth correctness indicator). Access to ground-truth
correctness indicator is expected to improve performance for both parallel and sequential sampling
unsurprisingly, but we see in Figure 8 (Right) that RISE is able to improve performance more beyond
simply sampling more samples at the first turn and computing pass@K, despite this strong assumption of
access to an oracle final answer verifier made by the parallel sampling approach.
We would expect parallel sampling via pass@K to be most performant when provided access to oracle
answer checking as the model can choose to simply sample 𝐾independent responses, if the base model
accuracy on this task is reasonable. Pass@K @ turn 1 also upper bounds the first turn accuracy of any
procedure that does not query the oracle (e.g., with verifiers, with majority voting, etc.). Hence, access
to oracle answer checking for each individual response presents the strongest result one couldexpect out
14
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
of parallel sampling, in one turn. On the other hand, sequential sampling produces correlated samples
and hence should, in principle, not be able to improve over parallel sampling, unlessthe model is unable
to use the additional tokens and computation provided by the feedback self-improvement prompt to
meaningfully correct itself. Since the sequential performance of the model is larger than the parallel
performance above, this means that RISE indeed does this successfully.
6.6. Error Analysis of RISE over Turns
Following the protocol of Huang et al. [21], in this section, we perform an error analysis of the improve-
ment performed by RISE (without any oracle feedback) to understand how the fraction of incorrect and
correct responses changes over turns, when no oracle is used for early termination. We demonstrate this
in the form of Venn diagrams in Figure 9. First note that there is a consistent increase in the portion
of problems that stay correct and a consistent decrease in the portion of problems that stay incorrect,
which means that the model is able to answer more and more problems as we increase the number
of turns. Second, there is a consistent decrease in the number of problems that change from being
correct to incorrect, which is often also not the case for strong proprietary LLMs such as GPT in Huang
et al.[21]. We also note that there is a decrease in the total number of incorrect problems that become
correct in the subsequent turn, but this is a direct consequence of a shrinkage in the size of the incorrect
response set as more problems become correct over turns. This indicates that one can induce “intrinsic”
self-improvement (per the terminology of Huang et al. [21]) via fine-tuning with RISE, even though no
external environment input is provided during evaluation.
Figure9:Change in the fraction of responses that transition their correctness values over the course of multi-turn
rollouts from RISE, w/o oracle. Observe that in general, the fraction of Correct →Correct responses increases; Incorrect →
Incorrect responses decreases; and the fraction of Correct →Incorrect responses also decreases, indicating that RISE (w/o any
oracle) is able to iteratively improve its responses.
Qualitative examples. We also inspect several examples from the GSM8K test set to qualitatively
understand the behavior of RISE over turns and observe different behavior patterns, that we show in
Appendix B.2. For instance, the trained model may choose to completely rewrite its previous response if
it is totally incorrect in order to get to the correct answer or make small edits if the previous response is
mostly correct. Another interesting pattern we note is that the model implicitly has the ability to locate
errors in previous responses and only refine the erroneous steps. Additionally, the model is tolerant of
noisy environmental feedback when there is no oracle-assisted early termination.
7. Discussion, Future Directions, and Limitations
We presented RISE, an approach for fine-tuning LLMs to be able to improve their own responses over
multiple turns sequentially. RISE prescribes an iterative RL recipe on top of on-policy rollout data, with
15
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
expert or self-generated supervision to steer self-improvement. RISE significantly improves the self-
improvement abilities of 7B models on reasoning tasks (GSM8K and MATH), attaining an improvement
over turns that previous work [ 21] has not observed in strong proprietary models. In addition, RISE
outperforms prior approaches that attempt to tackle similar problems of refinement and correction, while
being simpler in that it does not require running multiple models and works well with just one model.
Despite these good results, there are still many open questions and limitations. Due to computational
constraints, we were not able to perform more than two iterations of training with RISE, and no more
than one iteration when the supervision comes from the learner itself. Improving with self-generated
supervision will likely require more computation and more iterations, since it will be slower than when
using an off-the-shelf expert model. RISE requires running manual iterations and hence, a more “online”
variant of RISE is likely the solution in the long run, especially when we wish to scale on-policy learning
in a data-efficient manner. Additionally, while our work fine-tunes models on one task at a time, it will
be certainly interesting to include data from the protocols specified by RISE into general instruction
tuning and post-training pipelines. Given the results that fine-tuning on data prescribed by RISE does not
hurt the first-turn performance of any model we trained, we hypothesize that adding this sort of data in
generalinstruction-tuningpipelinesshouldnothurteither,whileenablingthesequentialself-improvement
capability that is largely absent from models today.
Acknowledgements
This work was done at CMU. We thank Fahim Tajwar, Abitha Thankaraj, Amrith Setlur, and Charlie Snell
for their feedback and informative discussions. This work was supported by ONR under N000142412206,
OpenAI superalignment fast grants, and used the Delta system and JetStream2 [ 16] at the National
Center for Supercomputing Applications through CIS240249 and CIS230278, supported by the National
Science Foundation. We thank OpenAI for providing GPT-4 credits for academic use.
References
[1]Rishabh Agarwal, Nino Vieillard, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Gkd: Generalized knowledge distillation for auto-regressive sequence models. arXiv preprint
arXiv:2306.13649 , 2023.
[2]Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna
Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. Constitutional ai: Harmlessness
from ai feedback. arXiv preprint arXiv:2212.08073 , 2022.
[3]Collin Burns, Pavel Izmailov, Jan Hendrik Kirchner, Bowen Baker, Leo Gao, Leopold Aschenbrenner,
Yining Chen, Adrien Ecoffet, Manas Joglekar, Jan Leike, Ilya Sutskever, and Jeff Wu. Weak-to-
strong generalization: Eliciting strong capabilities with weak supervision, 2023. URL https:
//arxiv.org/abs/2312.09390 .
[4]Jonathan D Chang, Wenhao Shan, Owen Oertell, Kianté Brantley, Dipendra Misra, Jason D Lee,
and Wen Sun. Dataset reset policy optimization for rlhf. arXiv preprint arXiv:2404.08495 , 2024.
[5]Yiannis Charalambous, Norbert Tihanyi, Ridhi Jain, Youcheng Sun, Mohamed Amine Ferrag, and
Lucas C Cordeiro. A new era in software security: Towards self-healing software via large language
models and formal verification. arXiv preprint arXiv:2305.14752 , 2023.
16
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[6]Baian Chen, Chang Shu, Ehsan Shareghi, Nigel Collier, Karthik Narasimhan, and Shunyu Yao.
Fireact: Toward language agent fine-tuning, 2023.
[7]Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models
to self-debug. arXiv preprint arXiv:2304.05128 , 2023.
[8]Zixiang Chen, Yihe Deng, Huizhuo Yuan, Kaixuan Ji, and Quanquan Gu. Self-play fine-tuning
converts weak language models to strong language models. arXiv preprint arXiv:2401.01335 , 2024.
[9]Yew Ken Chia, Guizhen Chen, Luu Anh Tuan, Soujanya Poria, and Lidong Bing. Contrastive
chain-of-thought prompting. arXiv preprint arXiv:2311.09277 , 2023.
[10]KarlCobbe, ChristopherHesse, JacobHilton, andJohnSchulman. Leveragingproceduralgeneration
to benchmark reinforcement learning. arXiv preprint arXiv:1912.01588 , 2019.
[11]KarlCobbe,VineetKosaraju,MohammadBavarian,MarkChen,HeewooJun,LukaszKaiser,Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman.
Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168 , 2021.
[12]Yilun Du, Shuang Li, Antonio Torralba, Joshua B Tenenbaum, and Igor Mordatch. Improving factual-
ity and reasoning in language models through multiagent debate. arXiv preprint arXiv:2305.14325 ,
2023.
[13]Kanishk Gandhi, Denise Lee, Gabriel Grand, Muxin Liu, Winson Cheng, Archit Sharma, and Noah D
Goodman. Stream of search (sos): Learning to search in language. arXiv preprint arXiv:2404.03683 ,
2024.
[14]Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and
Graham Neubig. Pal: Program-aided language models. In International Conference on Machine
Learning , pages 10764–10799. PMLR, 2023.
[15]Zhibin Gou, Zhihong Shao, Yeyun Gong, Yelong Shen, Yujiu Yang, Nan Duan, and Weizhu Chen.
Critic: Large Language Models can Self-Correct with Tool-Interactive Critiquing. arXiv preprint
arXiv:2305.11738 , 2023.
[16]David Y. Hancock, Jeremy Fischer, John Michael Lowe, Winona Snapp-Childs, Marlon Pierce,
Suresh Marru, J. Eric Coulter, Matthew Vaughn, Brian Beck, Nirav Merchant, Edwin Skidmore,
and Gwen Jacobs. Jetstream2: Accelerating cloud computing via jetstream. In Practice and
Experience in Advanced Research Computing , PEARC ’21, New York, NY, USA, 2021. Association
for Computing Machinery. ISBN 9781450382922. doi: 10.1145/3437359.3465565. URL https:
//doi.org/10.1145/3437359.3465565 .
[17]Alex Havrilla, Sharath Raparthy, Christoforus Nalmpantis, Jane Dwivedi-Yu, Maksym Zhuravinskyi,
Eric Hambro, and Roberta Railneau. Glore: When, where, and how to improve llm reasoning via
global and local refinements. arXiv preprint arXiv:2402.10963 , 2024.
[18]Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song,
and Jacob Steinhardt. Measuring mathematical problem solving with the math dataset. NeurIPS ,
2021.
17
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[19]Arian Hosseini, Xingdi Yuan, Nikolay Malkin, Aaron Courville, Alessandro Sordoni, and Rishabh
Agarwal. V-star: Training verifiers for self-taught reasoners. arXiv preprint arXiv:2402.06457 , 2024.
[20]Dong Huang, Qingwen Bu, Jie M Zhang, Michael Luck, and Heming Cui. Agentcoder: Multi-agent-
based code generation with iterative testing and optimisation. arXiv preprint arXiv:2312.13010 ,
2023.
[21]Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Wei Yu, Xinying Song,
and Denny Zhou. Large language models cannot self-correct reasoning yet. arXiv preprint
arXiv:2310.01798 , 2023.
[22]Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot
planners: Extracting actionable knowledge for embodied agents. In International Conference on
Machine Learning , pages 9118–9147. PMLR, 2022.
[23]Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot,
Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, et al.
Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[24]Katie Kang, Eric Wallace, Claire Tomlin, Aviral Kumar, and Sergey Levine. Unfamiliar finetuning
examples control how language models hallucinate, 2024.
[25]Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2022. URL https://
arxiv.org/abs/1312.6114 .
[26]Lucas Lehnert, Sainbayar Sukhbaatar, Paul Mcvay, Michael Rabbat, and Yuandong Tian. Be-
yond a*: Better planning with transformers via search dynamics bootstrapping. arXiv preprint
arXiv:2402.14083 , 2024.
[27]Chen Li, Weiqi Wang, Jingcheng Hu, Yixuan Wei, Nanning Zheng, Han Hu, Zheng Zhang, and
HouwenPeng. Common7blanguagemodelsalreadypossessstrongmathcapabilities. arXivpreprint
arXiv:2403.04706 , 2024.
[28]Hunter Lightman, Vineet Kosaraju, Yura Burda, Harri Edwards, Bowen Baker, Teddy Lee, Jan
Leike, John Schulman, Ilya Sutskever, and Karl Cobbe. Let’s verify step by step. arXiv preprint
arXiv:2305.20050 , 2023.
[29]XiaoLiu, HaoYu, HanchenZhang, YifanXu, XuanyuLei, HanyuLai, YuGu, HangliangDing, Kaiwen
Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688 ,
2023.
[30]HaipengLuo,QingfengSun,CanXu,PuZhao,JianguangLou,ChongyangTao,XiuboGeng,Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. Wizardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct. arXiv preprint arXiv:2308.09583 , 2023.
[31]Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri
Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with
self-feedback. arXiv preprint arXiv:2303.17651 , 2023.
18
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[32]Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and
Caiming Xiong. CodeGen: An Open Large Language Model for Code with Multi-Turn Program
Synthesis. ICLR, 2023.
[33]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David
Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. Show your work:
Scratchpads for intermediate computation with language models. arXiv preprint arXiv:2112.00114 ,
2021.
[34]Xue Bin Peng, Aviral Kumar, Grace Zhang, and Sergey Levine. Advantage-weighted regression:
Simple and scalable off-policy reinforcement learning. arXiv preprint arXiv:1910.00177 , 2019.
[35]JanPetersandStefanSchaal. Reinforcementlearningbyreward-weightedregressionforoperational
spacecontrol. In Proceedingsofthe24thinternationalconferenceonMachinelearning ,pages745–750.
ACM, 2007.
[36]StephaneRoss,GeoffreyGordon,andDrewBagnell. Areductionofimitationlearningandstructured
prediction to no-regret online learning. In Geoffrey Gordon, David Dunson, and Miroslav Dudík,
editors, Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics ,
volume 15 of Proceedings of Machine Learning Research , pages 627–635, Fort Lauderdale, FL, USA,
11–13 Apr 2011. PMLR. URL http://proceedings.mlr.press/v15/ross11a.html .
[37]Corby Rosset, Ching-An Cheng, Arindam Mitra, Michael Santacroce, Ahmed Awadallah, and
Tengyang Xie. Direct nash optimization: Teaching language models to self-improve with general
preferences. arXiv preprint arXiv:2404.03715 , 2024.
[38]Swarnadeep Saha, Omer Levy, Asli Celikyilmaz, Mohit Bansal, Jason Weston, and Xian Li.
Branch-solve-merge improves large language model evaluation and generation. arXiv preprint
arXiv:2310.15123 , 2023.
[39]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer,
Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use
tools.arXiv preprint arXiv:2302.04761 , 2023.
[40]Noah Shinn, Beck Labash, and Ashwin Gopinath. Reflexion: an autonomous agent with dynamic
memory and self-reflection. arXiv preprint arXiv:2303.11366 , 2023.
[41]Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, and Sergey Levine. Offline rl for natural
language generation with implicit language q learning. arXiv preprint arXiv:2206.11871 , 2022.
[42]JaschaSohl-Dickstein,EricA.Weiss,NiruMaheswaranathan,andSuryaGanguli. Deepunsupervised
learning using nonequilibrium thermodynamics, 2015. URL https://arxiv.org/abs/1503.
03585.
[43]Yang Song and Diederik P. Kingma. How to train your energy-based models, 2021. URL https:
//arxiv.org/abs/2101.03288 .
[44]Liting Sun, Cheng Peng, Wei Zhan, and Masayoshi Tomizuka. A fast integrated planning and
control framework for autonomous driving via imitation learning. In Dynamic Systems and Control
Conference , volume 51913, page V003T37A012. American Society of Mechanical Engineers, 2018.
19
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[45]Gokul Swamy, Sanjiban Choudhury, J. Andrew Bagnell, and Zhiwei Steven Wu. Inverse reinforce-
ment learning without reinforcement learning, 2024. URL https://arxiv.org/abs/2303.
14623.
[46]Shubham Toshniwal, Ivan Moshkov, Sean Narenthiran, Daria Gitman, Fei Jia, and Igor Gitman.
Openmathinstruct-1: A1.8millionmathinstructiontuningdataset. arXivpreprintarXiv:2402.10176 ,
2024.
[47]Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia
Creswell, Geoffrey Irving, and Irina Higgins. Solving math word problems with process-and
outcome-based feedback. arXiv preprint arXiv:2211.14275 , 2022.
[48]Boshi Wang, Sewon Min, Xiang Deng, Jiaming Shen, You Wu, Luke Zettlemoyer, and Huan Sun.
Towards understanding chain-of-thought prompting: An empirical study of what matters. arXiv
preprint arXiv:2212.10001 , 2022.
[49]Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and
Anima Anandkumar. Voyager: An open-ended embodied agent with large language models. arXiv
preprint arXiv: Arxiv-2305.16291 , 2023.
[50]Peiyi Wang, Lei Li, Zhihong Shao, RX Xu, Damai Dai, Yifei Li, Deli Chen, Y Wu, and Zhifang
Sui. Math-shepherd: Verify and reinforce llms step-by-step without human annotations. CoRR,
abs/2312.08935 , 2023.
[51]XuezhiWang,JasonWei,DaleSchuurmans,QuocLe,EdChi,SharanNarang,AakankshaChowdhery,
and Denny Zhou. Self-consistency improves chain of thought reasoning in language models. arXiv
preprint arXiv:2203.11171 , 2022.
[52]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny
Zhou, et al. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS ,
2022.
[53]Sean Welleck, Ximing Lu, Peter West, Faeze Brahman, Tianxiao Shen, Daniel Khashabi, and Yejin
Choi. Generating sequences by learning to self-correct. In The Eleventh International Conference on
Learning Representations , 2023. URL https://openreview.net/forum?id=hH36JeQZDaO .
[54]Hui Yang, Sifu Yue, and Yunzhong He. Auto-gpt for online decision making: Benchmarks and
additional opinions. arXiv preprint arXiv:2306.02224 , 2023.
[55]Kaiyu Yang, Aidan M Swope, Alex Gu, Rahul Chalamala, Peiyang Song, Shixing Yu, Saad Godil,
Ryan Prenger, and Anima Anandkumar. LeanDojo: Theorem Proving with Retrieval-Augmented
Language Models. arXiv preprint arXiv:2306.15626 , 2023.
[56]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao.
React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629 ,
2022.
[57]LonghuiYu, WeisenJiang, HanShi, JinchengYu, ZhengyingLiu, YuZhang, JamesTKwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. Metamath: Bootstrap your own mathematical questions for
large language models. arXiv preprint arXiv:2309.12284 , 2023.
20
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[58]Lifan Yuan, Ganqu Cui, Hanbin Wang, Ning Ding, Xingyao Wang, Jia Deng, Boji Shan, Huimin
Chen, Ruobing Xie, Yankai Lin, et al. Advancing llm reasoning generalists with preference trees.
arXiv preprint arXiv:2404.02078 , 2024.
[59] Weizhe Yuan, Richard Yuanzhe Pang, Kyunghyun Cho, Sainbayar Sukhbaatar, Jing Xu, and Jason
Weston. Self-rewarding language models. arXiv preprint arXiv:2401.10020 , 2024.
[60]Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wenhao Huang, Huan Sun, Yu Su, and Wenhu Chen.
Mammoth: Building math generalist models through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 , 2023.
[61]Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Goodman. Star: Bootstrapping reasoning with
reasoning. Advances in Neural Information Processing Systems , 35:15476–15488, 2022.
[62]Aohan Zeng, Mingdao Liu, Rui Lu, Bowen Wang, Xiao Liu, Yuxiao Dong, and Jie Tang. Agenttuning:
Enabling generalized agent abilities for llms. arXiv preprint arXiv:2310.12823 , 2023.
[63]Tianjun Zhang, Xuezhi Wang, Denny Zhou, Dale Schuurmans, and Joseph E Gonzalez. Tempera:
Test-time prompting via reinforcement learning. arXiv preprint arXiv:2211.11890 , 2022.
[64]Tianjun Zhang, Aman Madaan, Luyu Gao, Steven Zheng, Swaroop Mishra, Yiming Yang, Niket
Tandon, and Uri Alon. In-context principle learning from mistakes. arXiv preprint arXiv:2402.05403 ,
2024.
[65]Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang, and Yu-Xiong Wang. Lan-
guage agent tree search unifies reasoning acting and planning in language models. arXiv preprint
arXiv:2310.04406 , 2023.
[66]Yifei Zhou, Andrea Zanette, Jiayi Pan, Sergey Levine, and Aviral Kumar. Archer: Training language
model agents via hierarchical multi-turn rl. arXiv preprint arXiv:2402.19446 , 2024.
21
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Appendices
A. Additional Ablations on Data Composition and Weak-to-Strong Generalization
A.1. Inclusion of Correct-to-Correct Data
Intuitively, self-improvement over turns is largely only possible when the model can learn to verify the
correctness of its previous response and decide to appropriately modify its response toward correctness.
Thus far, the RISE has only trained on data that showed how to convert incorrect responses to correct
responses but never illustrated how the model could act on correct responses. To understand if perfor-
mance can be boosted by also illustrating examples of how the model could act on correct responses, we
ran a number of ablations. We took the RISE data generated during Iteration 1 of training on GSM8K
with Llama2-7B and modified the multi-turn rollouts to create several cases. First, we duplicated the
correct response appearing at the end of every successful multi-turn rollout and trained for one extra turn.
This should teach the model that correct responses should not be modified, unlike incorrect responses
appearing in previous turns in the rollout. Second, we also ran a variant in which the correct response
appearing at the end of every successful rollout is followed by a different correct response. This variant
should teach the model that if it chooses to modify a correct response, it must still produce another
correct response.
As shown in Table 4, all methods improved performance over the base model, though only appending
with a successful rollout with a novel correct response leads to best performance. The default design of
RISE in the main paper attains a close second position, and repeating a correct response at the end of a
successful rollout largely reduces performance. We suspect that the poor performance of repeating the
same correct response is largely a result of inducing spurious correlations due to data duplication.
RISE (Llama2)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0)
+RISE (default) 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+Repeating a correct response 34.2 48.9 (+14.6) 46.2(+12.6) 57.7(+23.5)
+Appending a different correct response 33.1 49.3 (+16.2) 51.1(+18.0) 64.9(+31.8)
Table 4: Comparison of model performance on GSM8K with different mechanisms of adding correct-to-correct data in
RISE.Values in parentheses indicate improvement over m1@t1, note that appending a successful rollout with a a novel correct
response leads to the highest performance gains.
To further investigate self-improvement capabilities, we analyzed the percentage of correct responses
changing to incorrect responses in consecutive turns (T 𝑖to T𝑖+ 1), as illustrated in Figure 10. Generally, a
decreasing trend suggests better self-improvement, while lower absolute values indicate better resistance
to noisy feedback. The results reveal unexpected patterns across configurations. The Boost configuration
shows the poorest performance, with the highest overall percentages and an increase from turn 4 to
5, suggesting that it struggles to consistently maintain correct responses. Repeating a correct response
shows the lowest initial percentage (6.3%) but increases from turn 3 onward, indicating potential issues
in extended interactions. Both Default RISE and appending a different correct response demonstrate a
favorable trend, steadily decreasing from 12.3% to 3.9% and from 9.8% to 3.3%, respectively, suggesting
a good balance between maintaining correct responses and allowing improvements. These | findings
provide nuanced insights into the stability and self-improvement capabilities of RISE and align with our
earlier observation of its superior performance in overall accuracy.
22
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure10:Percentage of correct responses in turn T 𝑖that change to being incorrect in turn T 𝑖+1.This figure illustrates
the percentage of correct responses that change to incorrect responses across consecutive turns (T 𝑖to T𝑖+1) for different model
configurations. A continuously decreasing trend suggests better self-improvement performance.
A.2. Weak-to-Strong Generalization: RISE on Weak Model Data Improves Strong Models
In this section, we compare the performance of Llama2 and Mistral-7B with RISE in the weak-to-strong
setting[ 3]. Concretely,weareinterestedinusingdatageneratedviaRISEwithaweakmodel(Llama2-7B)
to train a strong model (Mistral-7B). Our analysis reveals intriguing insights into the transferability of
RISE-generated data across models of different capabilities.
RISEw/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Llama2-7B 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4)
+ Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+ Iteration 1 (Mistral-7B) 27.1 40.1 (+13.0) 45.2(+18.1) 59.1(+32.0)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3)
+ Iteration 1 (Llama2-7B) 38.2 55.4 (+17.2) 62.7(+24.5) 73.5(+35.3)
Table 5: Weak-to-strong generalization on GSM8K. Comparing performance of RISE when training on rollouts generated
by Llama2-7B vs Mistral-7B. Note that training the Mistral-7B model on rollouts generated by the weaker Llama2-7B with
RISE improves performance compared to using data generated by the Mistral-7B model itself. However, the reverse is not true:
training the Llama2 model on Mistral’s mistakes leads to worse performance, likely because errors from the Mistral-7B model
are harder to comprehend for a worse base model. All values are in % accuracy, and values in parentheses indicate improvement
over m1@t1.
As shown in Table 5, we find that Mistral-7B + Iteration 1 data generated from Llama2 outperforms
training the Llama2-7B model itself on these data (i.e., Llama2-7B + Iteration1) on all the metrics
reported with particularly significant improvements in multi-turn reasoning (m1@t5). In fact, training
on multi-turn rollouts from Llama2-7B also outperforms training on on-policy Mistral-7B rollouts as well.
Interestingly, we observed that training Llama2-7B on multi-turn rollouts from Mistral-7B performs worse
than training on on-policy Llama2-7B rollouts, suggesting that Llama2-7B, despite its lower absolute
performance, demonstrates more informative mistakes that can be leveraged to better boost the self-
improvement capability. This phenomenon underscores the importance of the quality and nature of
errors in the training data, rather than just the overall performance of the model that generates them.
These findings collectively suggest that the data generated from a weaker Llama2 model can still be used
to induce a self-improvement capability in a stronger model, although the reverse is not true (as is also
evident from the fact that using GPT-3.5 rollouts in the boosting phase for training does not improve
performance for any model in Table 1). We suspect that this is becaue the reverse poses a much harder
23
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
learning problem since a weak model need to internalize the mistakes of a stronger model, resulting in
hallucinations and memorization [ 24]. Note that training on these data does not degrade single-turn
performance either. This hints at an added benefit of training with RISE: weak-to-strong generalization,
which can be quite useful in practice when rolling out stronger models is expensive.
B. Additional Results
B.1. Complete Comparisons and | Discussion, Future Directions, and | Section not found | Section not found | Limitations
We presented RISE, an approach for fine-tuning LLMs to be able to improve their own responses over
multiple turns sequentially. RISE prescribes an iterative RL recipe on top of on-policy rollout data, with
15
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
expert or self-generated supervision to steer self-improvement. RISE significantly improves the self-
improvement abilities of 7B models on reasoning tasks (GSM8K and MATH), attaining an improvement
over turns that previous work [ 21] has not observed in strong proprietary models. In addition, RISE
outperforms prior approaches that attempt to tackle similar problems of refinement and correction, while
being simpler in that it does not require running multiple models and works well with just one model.
Despite these good results, there are still many open questions and limitations. Due to computational
constraints, we were not able to perform more than two iterations of training with RISE, and no more
than one iteration when the supervision comes from the learner itself. Improving with self-generated
supervision will likely require more computation and more iterations, since it will be slower than when
using an off-the-shelf expert model. RISE requires running manual iterations and hence, a more “online”
variant of RISE is likely the solution in the long run, especially when we wish to scale on-policy learning
in a data-efficient manner. Additionally, while our work fine-tunes models on one task at a time, it will
be certainly interesting to include data from the protocols specified by RISE into general instruction
tuning and post-training pipelines. Given the results that fine-tuning on data prescribed by RISE does not
hurt the first-turn performance of any model we trained, we hypothesize that adding this sort of data in
generalinstruction-tuningpipelinesshouldnothurteither,whileenablingthesequentialself-improvement
capability that is largely absent from models today.
Acknowledgements
This work was done at CMU. We thank Fahim Tajwar, Abitha Thankaraj, Amrith Setlur, and Charlie Snell
for their feedback and informative discussions. This work was supported by ONR under N000142412206,
OpenAI superalignment fast grants, and used the Delta system and JetStream2 [ 16] at the National
Center for Supercomputing Applications through CIS240249 and CIS230278, supported by the National
Science Foundation. We thank OpenAI for providing GPT-4 credits for academic use.
References
[1]Rishabh Agarwal, Nino Vieillard, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Gkd: Generalized knowledge distillation for auto-regressive sequence models. arXiv preprint
arXiv:2306.13649 , 2023.
[2]Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna
Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. Constitutional ai: Harmlessness
from ai feedback. arXiv preprint arXiv:2212.08073 , 2022.
[3]Collin Burns, Pavel Izmailov, Jan Hendrik Kirchner, Bowen Baker, Leo Gao, Leopold Aschenbrenner,
Yining Chen, Adrien Ecoffet, Manas Joglekar, Jan Leike, Ilya Sutskever, and Jeff Wu. Weak-to-
strong generalization: Eliciting strong capabilities with weak supervision, 2023. URL https:
//arxiv.org/abs/2312.09390 .
[4]Jonathan D Chang, Wenhao Shan, Owen Oertell, Kianté Brantley, Dipendra Misra, Jason D Lee,
and Wen Sun. Dataset reset policy optimization for rlhf. arXiv preprint arXiv:2404.08495 , 2024.
[5]Yiannis Charalambous, Norbert Tihanyi, Ridhi Jain, Youcheng Sun, Mohamed Amine Ferrag, and
Lucas C Cordeiro. A new era in software security: Towards self-healing software via large language
models and formal verification. arXiv preprint arXiv:2305.14752 , 2023.
16
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[6]Baian Chen, Chang Shu, Ehsan Shareghi, Nigel Collier, Karthik Narasimhan, and Shunyu Yao.
Fireact: Toward language agent fine-tuning, 2023.
[7]Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models
to self-debug. arXiv preprint arXiv:2304.05128 , 2023.
[8]Zixiang Chen, Yihe Deng, Huizhuo Yuan, Kaixuan Ji, and Quanquan Gu. Self-play fine-tuning
converts weak language models to strong language models. arXiv preprint arXiv:2401.01335 , 2024.
[9]Yew Ken Chia, Guizhen Chen, Luu Anh Tuan, Soujanya Poria, and Lidong Bing. Contrastive
chain-of-thought prompting. arXiv preprint arXiv:2311.09277 , 2023.
[10]KarlCobbe, ChristopherHesse, JacobHilton, andJohnSchulman. Leveragingproceduralgeneration
to benchmark reinforcement learning. arXiv preprint arXiv:1912.01588 , 2019.
[11]KarlCobbe,VineetKosaraju,MohammadBavarian,MarkChen,HeewooJun,LukaszKaiser,Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman.
Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168 , 2021.
[12]Yilun Du, Shuang Li, Antonio Torralba, Joshua B Tenenbaum, and Igor Mordatch. Improving factual-
ity and reasoning in language models through multiagent debate. arXiv preprint arXiv:2305.14325 ,
2023.
[13]Kanishk Gandhi, Denise Lee, Gabriel Grand, Muxin Liu, Winson Cheng, Archit Sharma, and Noah D
Goodman. Stream of search (sos): Learning to search in language. arXiv preprint arXiv:2404.03683 ,
2024.
[14]Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and
Graham Neubig. Pal: Program-aided language models. In International Conference on Machine
Learning , pages 10764–10799. PMLR, 2023.
[15]Zhibin Gou, Zhihong Shao, Yeyun Gong, Yelong Shen, Yujiu Yang, Nan Duan, and Weizhu Chen.
Critic: Large Language Models can Self-Correct with Tool-Interactive Critiquing. arXiv preprint
arXiv:2305.11738 , 2023.
[16]David Y. Hancock, Jeremy Fischer, John Michael Lowe, Winona Snapp-Childs, Marlon Pierce,
Suresh Marru, J. Eric Coulter, Matthew Vaughn, Brian Beck, Nirav Merchant, Edwin Skidmore,
and Gwen Jacobs. Jetstream2: Accelerating cloud computing via jetstream. In Practice and
Experience in Advanced Research Computing , PEARC ’21, New York, NY, USA, 2021. Association
for Computing Machinery. ISBN 9781450382922. doi: 10.1145/3437359.3465565. URL https:
//doi.org/10.1145/3437359.3465565 .
[17]Alex Havrilla, Sharath Raparthy, Christoforus Nalmpantis, Jane Dwivedi-Yu, Maksym Zhuravinskyi,
Eric Hambro, and Roberta Railneau. Glore: When, where, and how to improve llm reasoning via
global and local refinements. arXiv preprint arXiv:2402.10963 , 2024.
[18]Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song,
and Jacob Steinhardt. Measuring mathematical problem solving with the math dataset. NeurIPS ,
2021.
17
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[19]Arian Hosseini, Xingdi Yuan, Nikolay Malkin, Aaron Courville, Alessandro Sordoni, and Rishabh
Agarwal. V-star: Training verifiers for self-taught reasoners. arXiv preprint arXiv:2402.06457 , 2024.
[20]Dong Huang, Qingwen Bu, Jie M Zhang, Michael Luck, and Heming Cui. Agentcoder: Multi-agent-
based code generation with iterative testing and optimisation. arXiv preprint arXiv:2312.13010 ,
2023.
[21]Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Wei Yu, Xinying Song,
and Denny Zhou. Large language models cannot self-correct reasoning yet. arXiv preprint
arXiv:2310.01798 , 2023.
[22]Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot
planners: Extracting actionable knowledge for embodied agents. In International Conference on
Machine Learning , pages 9118–9147. PMLR, 2022.
[23]Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot,
Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, et al.
Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[24]Katie Kang, Eric Wallace, Claire Tomlin, Aviral Kumar, and Sergey Levine. Unfamiliar finetuning
examples control how language models hallucinate, 2024.
[25]Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2022. URL https://
arxiv.org/abs/1312.6114 .
[26]Lucas Lehnert, Sainbayar Sukhbaatar, Paul Mcvay, Michael Rabbat, and Yuandong Tian. Be-
yond a*: Better planning with transformers via search dynamics bootstrapping. arXiv preprint
arXiv:2402.14083 , 2024.
[27]Chen Li, Weiqi Wang, Jingcheng Hu, Yixuan Wei, Nanning Zheng, Han Hu, Zheng Zhang, and
HouwenPeng. Common7blanguagemodelsalreadypossessstrongmathcapabilities. arXivpreprint
arXiv:2403.04706 , 2024.
[28]Hunter Lightman, Vineet Kosaraju, Yura Burda, Harri Edwards, Bowen Baker, Teddy Lee, Jan
Leike, John Schulman, Ilya Sutskever, and Karl Cobbe. Let’s verify step by step. arXiv preprint
arXiv:2305.20050 , 2023.
[29]XiaoLiu, HaoYu, HanchenZhang, YifanXu, XuanyuLei, HanyuLai, YuGu, HangliangDing, Kaiwen
Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688 ,
2023.
[30]HaipengLuo,QingfengSun,CanXu,PuZhao,JianguangLou,ChongyangTao,XiuboGeng,Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. Wizardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct. arXiv preprint arXiv:2308.09583 , 2023.
[31]Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri
Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with
self-feedback. arXiv preprint arXiv:2303.17651 , 2023.
18
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[32]Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and
Caiming Xiong. CodeGen: An Open Large Language Model for Code with Multi-Turn Program
Synthesis. ICLR, 2023.
[33]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David
Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. Show your work:
Scratchpads for intermediate computation with language models. arXiv preprint arXiv:2112.00114 ,
2021.
[34]Xue Bin Peng, Aviral Kumar, Grace Zhang, and Sergey Levine. Advantage-weighted regression:
Simple and scalable off-policy reinforcement learning. arXiv preprint arXiv:1910.00177 , 2019.
[35]JanPetersandStefanSchaal. Reinforcementlearningbyreward-weightedregressionforoperational
spacecontrol. In Proceedingsofthe24thinternationalconferenceonMachinelearning ,pages745–750.
ACM, 2007.
[36]StephaneRoss,GeoffreyGordon,andDrewBagnell. Areductionofimitationlearningandstructured
prediction to no-regret online learning. In Geoffrey Gordon, David Dunson, and Miroslav Dudík,
editors, Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics ,
volume 15 of Proceedings of Machine Learning Research , pages 627–635, Fort Lauderdale, FL, USA,
11–13 Apr 2011. PMLR. URL http://proceedings.mlr.press/v15/ross11a.html .
[37]Corby Rosset, Ching-An Cheng, Arindam Mitra, Michael Santacroce, Ahmed Awadallah, and
Tengyang Xie. Direct nash optimization: Teaching language models to self-improve with general
preferences. arXiv preprint arXiv:2404.03715 , 2024.
[38]Swarnadeep Saha, Omer Levy, Asli Celikyilmaz, Mohit Bansal, Jason Weston, and Xian Li.
Branch-solve-merge improves large language model evaluation and generation. arXiv preprint
arXiv:2310.15123 , 2023.
[39]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer,
Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use
tools.arXiv preprint arXiv:2302.04761 , 2023.
[40]Noah Shinn, Beck Labash, and Ashwin Gopinath. Reflexion: an autonomous agent with dynamic
memory and self-reflection. arXiv preprint arXiv:2303.11366 , 2023.
[41]Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, and Sergey Levine. Offline rl for natural
language generation with implicit language q learning. arXiv preprint arXiv:2206.11871 , 2022.
[42]JaschaSohl-Dickstein,EricA.Weiss,NiruMaheswaranathan,andSuryaGanguli. Deepunsupervised
learning using nonequilibrium thermodynamics, 2015. URL https://arxiv.org/abs/1503.
03585.
[43]Yang Song and Diederik P. Kingma. How to train your energy-based models, 2021. URL https:
//arxiv.org/abs/2101.03288 .
[44]Liting Sun, Cheng Peng, Wei Zhan, and Masayoshi Tomizuka. A fast integrated planning and
control framework for autonomous driving via imitation learning. In Dynamic Systems and Control
Conference , volume 51913, page V003T37A012. American Society of Mechanical Engineers, 2018.
19
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[45]Gokul Swamy, Sanjiban Choudhury, J. Andrew Bagnell, and Zhiwei Steven Wu. Inverse reinforce-
ment learning without reinforcement learning, 2024. URL https://arxiv.org/abs/2303.
14623.
[46]Shubham Toshniwal, Ivan Moshkov, Sean Narenthiran, Daria Gitman, Fei Jia, and Igor Gitman.
Openmathinstruct-1: A1.8millionmathinstructiontuningdataset. arXivpreprintarXiv:2402.10176 ,
2024.
[47]Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia
Creswell, Geoffrey Irving, and Irina Higgins. Solving math word problems with process-and
outcome-based feedback. arXiv preprint arXiv:2211.14275 , 2022.
[48]Boshi Wang, Sewon Min, Xiang Deng, Jiaming Shen, You Wu, Luke Zettlemoyer, and Huan Sun.
Towards understanding chain-of-thought prompting: An empirical study of what matters. arXiv
preprint arXiv:2212.10001 , 2022.
[49]Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and
Anima Anandkumar. Voyager: An open-ended embodied agent with large language models. arXiv
preprint arXiv: Arxiv-2305.16291 , 2023.
[50]Peiyi Wang, Lei Li, Zhihong Shao, RX Xu, Damai Dai, Yifei Li, Deli Chen, Y Wu, and Zhifang
Sui. Math-shepherd: Verify and reinforce llms step-by-step without human annotations. CoRR,
abs/2312.08935 , 2023.
[51]XuezhiWang,JasonWei,DaleSchuurmans,QuocLe,EdChi,SharanNarang,AakankshaChowdhery,
and Denny Zhou. Self-consistency improves chain of thought reasoning in language models. arXiv
preprint arXiv:2203.11171 , 2022.
[52]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny
Zhou, et al. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS ,
2022.
[53]Sean Welleck, Ximing Lu, Peter West, Faeze Brahman, Tianxiao Shen, Daniel Khashabi, and Yejin
Choi. Generating sequences by learning to self-correct. In The Eleventh International Conference on
Learning Representations , 2023. URL https://openreview.net/forum?id=hH36JeQZDaO .
[54]Hui Yang, Sifu Yue, and Yunzhong He. Auto-gpt for online decision making: Benchmarks and
additional opinions. arXiv preprint arXiv:2306.02224 , 2023.
[55]Kaiyu Yang, Aidan M Swope, Alex Gu, Rahul Chalamala, Peiyang Song, Shixing Yu, Saad Godil,
Ryan Prenger, and Anima Anandkumar. LeanDojo: Theorem Proving with Retrieval-Augmented
Language Models. arXiv preprint arXiv:2306.15626 , 2023.
[56]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao.
React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629 ,
2022.
[57]LonghuiYu, WeisenJiang, HanShi, JinchengYu, ZhengyingLiu, YuZhang, JamesTKwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. Metamath: Bootstrap your own mathematical questions for
large language models. arXiv preprint arXiv:2309.12284 , 2023.
20
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[58]Lifan Yuan, Ganqu Cui, Hanbin Wang, Ning Ding, Xingyao Wang, Jia Deng, Boji Shan, Huimin
Chen, Ruobing Xie, Yankai Lin, et al. Advancing llm reasoning generalists with preference trees.
arXiv preprint arXiv:2404.02078 , 2024.
[59] Weizhe Yuan, Richard Yuanzhe Pang, Kyunghyun Cho, Sainbayar Sukhbaatar, Jing Xu, and Jason
Weston. Self-rewarding language models. arXiv preprint arXiv:2401.10020 , 2024.
[60]Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wenhao Huang, Huan Sun, Yu Su, and Wenhu Chen.
Mammoth: Building math generalist models through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 , 2023.
[61]Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Goodman. Star: Bootstrapping reasoning with
reasoning. Advances in Neural Information Processing Systems , 35:15476–15488, 2022.
[62]Aohan Zeng, Mingdao Liu, Rui Lu, Bowen Wang, Xiao Liu, Yuxiao Dong, and Jie Tang. Agenttuning:
Enabling generalized agent abilities for llms. arXiv preprint arXiv:2310.12823 , 2023.
[63]Tianjun Zhang, Xuezhi Wang, Denny Zhou, Dale Schuurmans, and Joseph E Gonzalez. Tempera:
Test-time prompting via reinforcement learning. arXiv preprint arXiv:2211.11890 , 2022.
[64]Tianjun Zhang, Aman Madaan, Luyu Gao, Steven Zheng, Swaroop Mishra, Yiming Yang, Niket
Tandon, and Uri Alon. In-context principle learning from mistakes. arXiv preprint arXiv:2402.05403 ,
2024.
[65]Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang, and Yu-Xiong Wang. Lan-
guage agent tree search unifies reasoning acting and planning in language models. arXiv preprint
arXiv:2310.04406 , 2023.
[66]Yifei Zhou, Andrea Zanette, Jiayi Pan, Sergey Levine, and Aviral Kumar. Archer: Training language
model agents via hierarchical multi-turn rl. arXiv preprint arXiv:2402.19446 , 2024.
21
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Appendices
A. Additional Ablations on Data Composition and Weak-to-Strong Generalization
A.1. Inclusion of Correct-to-Correct Data
Intuitively, self-improvement over turns is largely only possible when the model can learn to verify the
correctness of its previous response and decide to appropriately modify its response toward correctness.
Thus far, the RISE has only trained on data that showed how to convert incorrect responses to correct
responses but never illustrated how the model could act on correct responses. To understand if perfor-
mance can be boosted by also illustrating examples of how the model could act on correct responses, we
ran a number of ablations. We took the RISE data generated during Iteration 1 of training on GSM8K
with Llama2-7B and modified the multi-turn rollouts to create several cases. First, we duplicated the
correct response appearing at the end of every successful multi-turn rollout and trained for one extra turn.
This should teach the model that correct responses should not be modified, unlike incorrect responses
appearing in previous turns in the rollout. Second, we also ran a variant in which the correct response
appearing at the end of every successful rollout is followed by a different correct response. This variant
should teach the model that if it chooses to modify a correct response, it must still produce another
correct response.
As shown in Table 4, all methods improved performance over the base model, though only appending
with a successful rollout with a novel correct response leads to best performance. The default design of
RISE in the main paper attains a close second position, and repeating a correct response at the end of a
successful rollout largely reduces performance. We suspect that the poor performance of repeating the
same correct response is largely a result of inducing spurious correlations due to data duplication.
RISE (Llama2)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0)
+RISE (default) 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+Repeating a correct response 34.2 48.9 (+14.6) 46.2(+12.6) 57.7(+23.5)
+Appending a different correct response 33.1 49.3 (+16.2) 51.1(+18.0) 64.9(+31.8)
Table 4: Comparison of model performance on GSM8K with different mechanisms of adding correct-to-correct data in
RISE.Values in parentheses indicate improvement over m1@t1, note that appending a successful rollout with a a novel correct
response leads to the highest performance gains.
To further investigate self-improvement capabilities, we analyzed the percentage of correct responses
changing to incorrect responses in consecutive turns (T 𝑖to T𝑖+ 1), as illustrated in Figure 10. Generally, a
decreasing trend suggests better self-improvement, while lower absolute values indicate better resistance
to noisy feedback. The results reveal unexpected patterns across configurations. The Boost configuration
shows the poorest performance, with the highest overall percentages and an increase from turn 4 to
5, suggesting that it struggles to consistently maintain correct responses. Repeating a correct response
shows the lowest initial percentage (6.3%) but increases from turn 3 onward, indicating potential issues
in extended interactions. Both Default RISE and appending a different correct response demonstrate a
favorable trend, steadily decreasing from 12.3% to 3.9% and from 9.8% to 3.3%, respectively, suggesting
a good balance between maintaining correct responses and allowing improvements. These findings
provide nuanced insights into the stability and self-improvement capabilities of RISE and align with our
earlier observation of its superior performance in overall accuracy.
22
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure10:Percentage of correct responses in turn T 𝑖that change to being incorrect in turn T 𝑖+1.This figure illustrates
the percentage of correct responses that change to incorrect responses across consecutive turns (T 𝑖to T𝑖+1) for different model
configurations. A continuously decreasing trend suggests better self-improvement performance.
A.2. Weak-to-Strong Generalization: RISE on Weak Model Data Improves Strong Models
In this section, we compare the performance of Llama2 and Mistral-7B with RISE in the weak-to-strong
setting[ 3]. Concretely,weareinterestedinusingdatageneratedviaRISEwithaweakmodel(Llama2-7B)
to train a strong model (Mistral-7B). Our analysis reveals intriguing insights into the transferability of
RISE-generated data across models of different capabilities.
RISEw/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Llama2-7B 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4)
+ Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+ Iteration 1 (Mistral-7B) 27.1 40.1 (+13.0) 45.2(+18.1) 59.1(+32.0)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3)
+ Iteration 1 (Llama2-7B) 38.2 55.4 (+17.2) 62.7(+24.5) 73.5(+35.3)
Table 5: Weak-to-strong generalization on GSM8K. Comparing performance of RISE when training on rollouts generated
by Llama2-7B vs Mistral-7B. Note that training the Mistral-7B model on rollouts generated by the weaker Llama2-7B with
RISE improves performance compared to using data generated by the Mistral-7B model itself. However, the reverse is not true:
training the Llama2 model on Mistral’s mistakes leads to worse performance, likely because errors from the Mistral-7B model
are harder to comprehend for a worse base model. All values are in % accuracy, and values in parentheses indicate improvement
over m1@t1.
As shown in Table 5, we find that Mistral-7B + Iteration 1 data generated from Llama2 outperforms
training the Llama2-7B model itself on these data (i.e., Llama2-7B + Iteration1) on all the metrics
reported with particularly significant improvements in multi-turn reasoning (m1@t5). In fact, training
on multi-turn rollouts from Llama2-7B also outperforms training on on-policy Mistral-7B rollouts as well.
Interestingly, we observed that training Llama2-7B on multi-turn rollouts from Mistral-7B performs worse
than training on on-policy Llama2-7B rollouts, suggesting that Llama2-7B, despite its lower absolute
performance, demonstrates more informative mistakes that can be leveraged to better boost the self-
improvement capability. This phenomenon underscores the importance of the quality and nature of
errors in the training data, rather than just the overall performance of the model that generates them.
These findings collectively suggest that the data generated from a weaker Llama2 model can still be used
to induce a self-improvement capability in a stronger model, although the reverse is not true (as is also
evident from the fact that using GPT-3.5 rollouts in the boosting phase for training does not improve
performance for any model in Table 1). We suspect that this is becaue the reverse poses a much harder
23
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
learning problem since a weak model need to internalize the mistakes of a stronger model, resulting in
hallucinations and memorization [ 24]. Note that training on these data does not degrade single-turn
performance either. This hints at an added benefit of training with RISE: weak-to-strong generalization,
which can be quite useful in practice when rolling out stronger models is expensive.
B. Additional Results
B.1. Complete Comparisons and Discussion: Extended Version of Table 1
We provide an extended version of Table 1, with a clear explanation of how we implement baselines and
a discussion of comparisons.
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(+0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3) 6.7 9.5 (+2.8) 18.4(+11.1) 29.7(+22.4)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
Baselines
GPT-3.5 66.4 80.6 (+14.2) 71.0(+4.6) 74.7(+8.3) 39.7 47.8 (+8.1) 45.1(+5.4) 54.3(+14.6)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
Eurus-7b-SFT 36.3 66.3 (+30.0) 47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5) 16.3(+4.0) 22.9(+10.6)
Self-Refine →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0) 5.5 6.5 (+1.0) 2.9(-2.6) 7.2(+1.7)
+Iteration1 35.6 49.5 (+13.9) 31.7(-3.9) 43.7(+8.1) 6.3 8.7 (+2.4) 5.9(-0.4) 9.9(+3.6)
+Iteration2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7b-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) N/A
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
V-STaR →m64@t1
+STaR 28.0 46.1 (+18.1)
+Verification 28.0 56.2 (+28.2) N/A
+V-STaR 28.0 63.2 (+35.2)
Table 6: Comparing RISE with other approaches (Self-Refine, GLoRE, and V-STaR) and other baseline approaches.
Observe that RISE attains the biggest performance improvements between 1-turn and 5-turn performance without the use of
an oracle on both GSM8K and MATH. This performance gap is even larger when oracle early termination is allowed (5-turn
w/ oracle). Self-Refine largely degrades performance across the board. GLoRE trains a separate refinement model, but still
performs worse than RISE.
24
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Comparison with Self-Refine [ 31].To build a self-refine baseline [ 31] evaluation, we slightly modified
our evaluation pipeline following the self-refine approach. In this setup (Figure 11), the model generates
an initial response, and then the environment prompts the model to locate errors in the generated
solution and refine its answer based on the initial response and the identified error.
Self-Refine
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 17 >
User:<Query >
Agent:<Initial Answer >
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent:<Critic >
User: Now, rewrite the solution in the required format:
Agent:<Refined Answer >
Figure11:Prompt for Self-Refine : We follow the standard pipeline of the original paper, prompt the
LLM to refine and correct its previous mistakes.
However, our experiments show that without any oracle hint from the environment or human feedback,
the self-refine approach leads to a degradation in performance across all models. Only when oracle
feedback is available to assist with early termination does the self-refine approach provide a slight
performance boost. This highlights the limitation of the self-refine structure in effectively improving
model performance without external guidance, which is also observed in [22].
In contrast, the model trained with RISE can attain consistent performance improvements without relying
on an oracle. By training the model to iteratively refine its responses, our method enables the model to
self-correct and improve its performance over multiple turns. This showcases the effectiveness of our
approach incomparison to the self-refine baseline, as it allows for more robust and consistent performance
gains without the need for the oracle assistance.
Comparison with GLoRE [ 17].GLoRE is a multi-model system that relies on a student model to
propose drafts, an Outcome-based Reward Model (ORM) or Step-wise ORM to locate errors at different
granularity levels, and a Global or Local Refinement Model for adjusting these errors. Since no code
was openly available for this approach, in our experiments, we compared to the numbers from the main
paper Havrilla et al. [17]. While the comparison against GLoRE is already apples-to-oranges since our
25
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
method only trains a single end-to-end model, while GLoRE trains multiple models. Performance-wise,
GLoRE’s global and local refinement models show little to no improvement in overall accuracy without an
oracle, and even exhibit decreasing accuracy in some cases. However, when an oracle is used to guide the
refinement process, GLoRE demonstrates a 10% improvement on the 7B model in the GSM8K dataset.
As anticipated, since we run RISE from a less advanced base model (Llama2 7B), we observe a slightly
lower absolute performance compared to GLoRE. However, RISE demonstrates its effectiveness in self-
improvement by sequentially enhancing its performance by an impressive 13.4% within just 3 turns
without an oracle feedback, and by a remarkable 23.4% with an oracle on GSM8K. This showcase of
RISE’s capabilities is particularly noteworthy considering that GLoRE utilizes 3 independent models -
one for generating candidate solutions, one reward model for locating errors, and one refinement model
for refinement.
Comparison with V-STaR [ 19].V-STaR requires training an additional verifier model to rank candidate
answers generated by the targeted model, but it does not make any sequential revisions or improvements
to a response. While comparing RISE to using a verifier for re-ranking the top 5 responses at the first
turn (as a base comparison) would have been informative, we were unable to find this specific result
in the original V-STaR paper. The results presented in the official table 6 for V-STaR correspond to
running 64 samples, which improves the base model’s performance by 35.2% for each prompt during
evaluation. In contrast, our method, RISE, after the same amount of finetuning iterations (3 iterations)
and using only 5 samples, improves upon the base model by 44.5% (calculated as 55.0% - 10.5% =
44.5%). This comparison highlights RISE’s efficiency in achieving significant improvements with fewer
samples and iterations compared to V-STaR’s approach of using a large number of samples without
sequential refinement.
Moreover, V-STaR’s performance is inherently bounded by the candidate generator’s performance. As
discussed in Section 5, if there is no correct response among the generated candidates, the problem
remains unsolved. In contrast, we show in Figure 6 that RISE can also solve problems that were not
solved by majority voting with a much higher budget in the first turn. Furthermore, we believe that
combining V-STaR with RISE could lead to even better performance, as RISE can generate better models
and a verifier can be complementarily used for filtering.
Comparison with other base models. Mistral-7B [ 23] and Eurus-7B-SFT [ 58] are models that exhibit
comparable performance to our method in terms of the absolute maj@5 performance. However, it
is crucial to note that these base models are fine-tuned using a vast amount of data, including data
specifically tuned for math reasoning performance [ 58], while our model is fine-tuned on a single domain.
That said, we do show that fine-tuning with RISE can still enhance the performance of Mistral-7B models.
To summarize, our method offers several advantages over GLoRE and V-STaR, such as end-to-end
error correction with a single model, superior performance with fewer samples, and the ability to solve
problems that cannot be solved by random sampling in the first turn. Although our maj@1 performance
is lower than GLoRE’s base model EI, which is an apples-to-oranges comparison our ultimate 5-turn
performance surpasses their best absolute performance in both oracle and non-oracle scenarios.
Compared to other base models like Mistral-7B and Eurus-7B-SFT, our method achieves comparable
performance while being fine-tuned on a single domain, and it can be generalized to better base models.
26
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
B.2. Qualitative Examples from RISE
In this section, we provide some qualitative examples showing the nature of edits made by RISE on
various datasets that we train on. We utilize the model from iteration 2 of RISE.
27
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Small Edits)
Query: Mike plays ping pong for 40 minutes. In the first 20 minutes, he scores 4 points. In the
second 20 minutes, he scores 25% more points. How many total points did he score?
Turn-1 Response :
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
So,Mikescores4+4=8pointsinthesecond20minutes.
Step 3: To find the total points, we need to add the points scored in the first and second 20 minutes.
total_points = 4 + 8 = 12.
Answer: 12✗
Turn-2 Response :
I apologize for the mistake. Let’s solve the problem step by step.
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
Thismeanshescores4+4*25%=4+1=5pointsinthesecond20minutes.
Step 3: To find the total points, we add the points scored in the first and second 20 minutes: 4 + 5
= 9 points.
Answer: 9✓
RISE Example (Big Edits)
Query: In a candy machine, there are 22 more than four times the number of pink gumballs as
there are blue gumballs. If there are 12 blue gumballs how many pink ones are there?
Turn-1 Response :
Step 1: Let’s assume the number of blue gumballs as x. Step 2: According to the given information,
there are 22 more than four times the number of pink gumballs as there are blue gumballs. So, the
number of pink gumballs can be expressed as 4x + 22. Step3:Wearegiventhatthereare12blue
gumballs,solet’ssubstitutexwith12intheequation.
Answer: 54✗
Turn-2 Response :
Let’s solve the problem step by step: Step 1: Let’s denote the number of blue gumballs as x. Step
2: We are given that the number of pink gumballs is 22 more than four times the number of blue
gumballs. So, the number of pink gumballs can be expressed as 4x + 22. Step3:Wearealsogiven
thatthereare12bluegumballs,sowecansubstitutex=12intotheexpressionforthenumberof
pinkgumballs:4*12+22=48+22=70Therefore,thereare
boxed70 pinkgumballs.
Answer: 70✓
Figure12:Examples of RISE correct its previous behavior in different modes. Some only make changes to a small part (small
edits), some may directly rewrite most of its previous answers (big edits) because the first step in the previous answer is wrong.
The mistaken steps of different turns are highlighted in red, and the correct are highlighted in green. This demonstrates shows
how RISE can correct its previous answers and finally get to a correct answer.
28
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Noise Tolerance)
Query: Ryan plants 2 flowers a day in his garden. After 15 days, how many flowers does he have if 5 did not grow?
Turn-1 Response :
Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15 days = 30 flowers in his garden.
Step 2: However, 5 flowers did not grow, so we need to subtract these non-growing flowers from the total count. Step 3:
Calculate the number of flowers that actually grew in Ryan’s garden. flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-2 Response :
Apologies for the mistake. Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total
of 2 flowers/day * 15 days = 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these
non-growing flowers from the total count. Step 3: Calculate the number of flowers that actually grew in Ryan’s garden.
flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-3 Response :
Let’s reevaluate the solution. Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15
days = 30 flowers in his garden. Step 2: However, 5 flowers did not grow, so we need to add these flowers to the total
count, as they were planted but did not grow. Step3:CalculatethetotalnumberofflowersinRyan’sgarden.total_flowers
=30flowers+5flowers=35flowers.
Answer: 35✗
Turn-4 Response
Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total of 2 flowers/day * 15 days
= 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these non-growing flowers from the
total count. Step 3: Calculate the total number of flowers in Ryan’s garden after subtracting the non-growing flowers.
total_flowers = total_planted_flowers - non_growing_flowers = 30 flowers - 5 flowers=
boxed25 flowers.
Answer: 25✓
Turn-5 Response
Let’s reevaluate the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, which is 2 flowers/day * 15 days = 30
flowers in total. Step 2: However, 5 flowers did not grow, so we have to subtract these 5 flowers from the total. Step 3:
Therefore, the total number of flowers Ryan has is 30 flowers (total planted) - 5 flowers (did not grow) =
boxed25 flowers.
Answer: 25✓
Figure13:Examples of RISE’s tolerance of noisy feedback . In the evaluation where there is no oracle, we use a verifier
that always tells the model, "The answer is incorrect. Please try again. Here’s the question: <Query >". We observe that from
turn 2 to turn 5, the model is still able to output the correct answer in 3 out of 4 turns. In the response at turn 4, the model
performs half of the solution correctly, and only the last step is wrong. In addition, in the turns where the model still outputs
the correct answer, it doesn’t directly copy the answer from the previous turn but instead comes up with a new paraphrase. This
demonstrates that RISE provides the model with tolerance to noisy feedback and does not randomly change its behavior upon
receiving a revisiting request. The mistaken steps of different turns are highlighted in red
29
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Error Localization)
Query: Josh decides to try flipping a house. He buys a house for $80,000 and then puts in $50,000 in repairs. This
increased the value of the house by 150%. How much profit did he make?
Turn-1 Response :
Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, which increases the value of the house by
150%. Step 3: To calculate the increase in value, we multiply the cost of the house by 150% and add it to the cost of the
house. increase_in_value = $80,000 * 150% = $120,000. Step4:Tocalculatetheprofit,wesubtractthecostofthe
housefromitsnewvalue.profit=increase_in_value -$80,000 =$120,000 -$80,000 =$40,000.
Answer: 40,000✗
Turn-2 Response :
Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, and
this increases the value of the house by 150%. Step 3: The percentage increase in value is 150% of $80,000, which is
$120,000 (80,000 * 1.5 = $120,000). Step4:Tofindtheactualamount thatwouldbeaddedtothehouse’svalueafter
repairs,weneedtosubtracttheamount hespentonrepairsfromtheincreased value,whichis$120,000 -$50,000 =
$70,000. Step5:TheprofitJoshwouldmakeisthedifferencebetweenthecostofbuyingthehouseandtheincreased
valueafterrepairs,whichis$70,000 -$80,000 =-$10,000 ($10,000 lessthantheinitialcost).
Answer: 0✗
Turn-3 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: This increases the value of the house by 150%. Step 4: To find the increase in value, we calculate 150%
of the original price of the house: 150% of $80,000 = $120,000. Step5:Theincreaseinvalueafterrepairsistheoriginal
priceplus150%oftheoriginalprice:$80,000 +$120,000 =$200,000. Step6:Joshsellsthehousefor$200,000 and
madeaprofitof$200,000 -$80,000 =$120,000.
Answer: 120,000✗
Turn-4 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in
$50,000 in repairs, increasing the value of the house by 150%. Step 3: The increase in value is 150% of $80,000, which
is $120,000 (80,000 * 1.5 = $120,000). Step4:Thetotalamount spent,includingthepurchaseofthehouseandthe
repairs,is$80,000 +$50,000 =$130,000. Step5:TheprofitJoshmadeistheincreaseinvalueafterrepairsminusthe
totalamount spent,whichis$120,000 -$130,000 =-$10,000. Therefore,Joshmadea
boxed0 profit.
Answer: 0✗
Turn-5 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: The repairs increase the value of the house by 150%. Step 4: The increase in value is $50,000, which is
150% of $33,333 (50,000 / 1.5 = $33,333). Step 5: The repairs cost $50,000, and the increase in value is $33,333. Step
6: Therefore, Josh’s profit is $33,333 - $50,000 = -$16,667. Therefore, Josh made a 16676 profit.
Answer: 16676 ✗
Figure14:ExamplesofRISEnotbeingabletocorrectitserrorwithin5stepsbutdemonstratingmeaningful errorlocalization
behavior . Even in turn 2, it has already solved the problem at step 4 but mistakenly takes another step and reaches the wrong
answer. The following turns are unable to correct this small error. Though this problem remains unsolved, we observe that (1)
the model is able to stick to the correct steps, where all responses reach an intermediate step of 12000 correctly, except for the
last response, where the model tries to modify the answer from one step ahead; (2) the model doesn’t repeat its responses,
which is a behavior we notice when evaluating some off-the-shelf models; and (3) the model is making meaningful changes to
the incorrect steps. In | future work. In this self-distillation setting, we could also divide the
computation between sequential and parallel sampling strategies to get the best results at the end of five
turns. Nonetheless, this result shows that even by training on self-generated samples, RISE can actually
amplify the sequential sampling performance of the base model.
6.2. Does the Performance of RISE Improve with Iterative Training?
Next, we attempt to understand if RISE improves with multiple rounds of training on on-policy data. As
shown in Tables 1 and 2, the performance of RISE improves from iteration to iteration constantly. The
5-turn performance of RISE, both with and without an oracle, exhibits a clear improvement with more
rounds. This implies that iterative self-training procedures of the form of STaR [ 61] can also be combined
with RISE to train models for self-improvement. This also perhaps serves as a strong hint towards the
potential utility of full online reinforcement learning (RL) techniques.
6.3. Does RISE Also Improve Sequential Performance on Out-of-Distribution Prompts?
In Table 3, our aim is to evaluate the robustness of the strategy induced by RISE on new, unseen prompts.
Specifically, we compare the performance of the RISE model trained with a dataset on evaluation prompts
12
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
from another dataset. Note in Table 3, these datasets include MATH, GSM8K, and SVAMP. Generally,
we observe that the model trained on one dataset is still able to improve the base model’s performance
on another dataset over the course of sequential five turns. More concretely, while the base Llama2
model largely degrades its turn 1 performance over turn 5 performance, model’s trained with RISE
enable a positive performance improvement on these out-of-distribution prompts. This means that even
though these models have not seen queries similar to the evaluation dataset, simply training with RISE
onsomekind of mathematical prompts still boosts the efficacy of the self-improvement strategy on a new
distribution of test prompts. This finding suggests that RISE is capable of instilling self-improvement
procedures that can generalize beyond the distribution of prompts in the fine-tuning data.
6.4. What Data Compositions and Data Quantity are Crucial for RISE?
We now study how different data compositions affect the performance of RISE with the goal of answering
questions such as should we collect on-policy error correction data like DAgger [ 36] or should we bias
towards high-quality off-policy data? . To understand the utility of different data compositions, we enlist
the three aspects RISE: (a)the use of multi-turn rollout data for fine-tuning, (b)the use of unsuccessful /
suboptimal rollouts via weighted supervised fine-tuning compared to naïve supervised learning, which
only utilizes successful rollouts for fine-tuning; and (c)the use of on-policy rollouts and self-generated
or oracle data. We will now perform controlled experiments to understand the effect of each of these
factors on the overall performance of RISE.
Figure7:Left: The importance of multi-turn interaction history and weighted objectives for training RISE. Note that
training with multi-turn data leads to better self-improvement performance at the end of 5 turns, than one-turn data obtained
from the original dataset with oracle answers from another model; also observe that using a weighted objective performs better.
Right: The importance of using all rollouts for learning , instead of only successful rollouts or only successful responses in the
data. Using all data performs best in our results.
(a) Data composition for fine-tuning. We first study the necessity of using the interaction of error
correction history for training RISE in Figure 7 (Left). We compare two approaches: model trained with
oracle answers shown right after the query (“1-turn”) and oracle answers shown after intermediate failed
attempts (“Multi-turn”) in Figure 7 (Left). Even though the latter trains on intermediate responses that
may not always be correct, it attains a higher performance than simply training on the correct response
for a given prompt. This highlights the importance of training on contexts that include a multi-turn
interaction history depicting mistakes from the learner to improve self-improvement capabilities.
(b) Weighted supervised learning vs unweighted supervised learning. Next, we investigate the effect
of reward-weighted RL on multi-turn data in RISE as opposed to simply imitating filtered successful data.
13
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
We find that using all the data leads to improved performance over simply filtering good datain Figure 7
(Right), which reduces sample size. In Figure 7 (Left), we find that reward-weighted training improves
performance on later turns, allowing us to better leverage all the sub-optimal data.
(c) On-policy vs off-policy data; self-generated vs. expert data. RISE runs on-policy rollouts and seeks
improvements on responses that the learner produces. As shown in Figure 8 (Left), a “DAgger [ 36]”-style
approach that seeks improvements on responses appearing in on-policy rollouts improves performance
(green/orange) compared to using expert data alone (blue/pink). Conceptually, this addresses the
train-test mismatch between the distribution of context tokens, enabling imitation learning methods to
now target the correct distribution. In addition, recent work [ 24] has shown that LLMs often memorize
“unfamiliar” examples generated by oracle models; by training on on-policy rollouts, we should be able to
eliminate any such potential issues. Thus, while the model trained via offline imitation is able to reduce
loss, these improvements do not generalize to new problems.
Figure8:Left: The importance of data sources used for training. We study the performance of the iteration 1 of RISE on
GSM8K with different data sources. “Expert” refers to the use of an oracle model, “On-policy” corresponds to sampling from the
learner, and “Best-of-N” means using the best sample out of 𝑁from the learner (here 𝑁= 16).Right: Comparing RISE with
oracle error feedback (pass@1 @ turn k; solid lines) to parallel sampling of 5 responses at turn 1 (pass@k @ turn 1;
dashed lines) over number of turns 𝑘on the x-axis on GSM8K. Observe that sequential sampling with Iteration 1 and Iteration
2 RISE models consistently outperforms parallel sampling for all values of turn 𝑘; and the gap grows as the number of iterations
increases. In contrast, this trend is absent for base and SFT models.
6.5. Pass@K vs Sequential Sampling via RISE
We now study the performance of sequential sampling with oracle feedback in GSM8K, unlike relying on
majority voting as in Table 1. Specifically, we compare the performance of RISE with early termination of
evaluation rollouts against pass@5 (not maj@5) performance of the RISE model at the first turn (which
makes an equal number of queries to the ground-truth correctness indicator). Access to ground-truth
correctness indicator is expected to improve performance for both parallel and sequential sampling
unsurprisingly, but we see in Figure 8 (Right) that RISE is able to improve performance more beyond
simply sampling more samples at the first turn and computing pass@K, despite this strong assumption of
access to an oracle final answer verifier made by the parallel sampling approach.
We would expect parallel sampling via pass@K to be most performant when provided access to oracle
answer checking as the model can choose to simply sample 𝐾independent responses, if the base model
accuracy on this task is reasonable. Pass@K @ turn 1 also upper bounds the first turn accuracy of any
procedure that does not query the oracle (e.g., with verifiers, with majority voting, etc.). Hence, access
to oracle answer checking for each individual response presents the strongest result one couldexpect out
14
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
of parallel sampling, in one turn. On the other hand, sequential sampling produces correlated samples
and hence should, in principle, not be able to improve over parallel sampling, unlessthe model is unable
to use the additional tokens and computation provided by the feedback self-improvement prompt to
meaningfully correct itself. Since the sequential performance of the model is larger than the parallel
performance above, this means that RISE indeed does this successfully.
6.6. Error Analysis of RISE over Turns
Following the protocol of Huang et al. [21], in this section, we perform an error analysis of the improve-
ment performed by RISE (without any oracle feedback) to understand how the fraction of incorrect and
correct responses changes over turns, when no oracle is used for early termination. We demonstrate this
in the form of Venn diagrams in Figure 9. First note that there is a consistent increase in the portion
of problems that stay correct and a consistent decrease in the portion of problems that stay incorrect,
which means that the model is able to answer more and more problems as we increase the number
of turns. Second, there is a consistent decrease in the number of problems that change from being
correct to incorrect, which is often also not the case for strong proprietary LLMs such as GPT in Huang
et al.[21]. We also note that there is a decrease in the total number of incorrect problems that become
correct in the subsequent turn, but this is a direct consequence of a shrinkage in the size of the incorrect
response set as more problems become correct over turns. This indicates that one can induce “intrinsic”
self-improvement (per the terminology of Huang et al. [21]) via fine-tuning with RISE, even though no
external environment input is provided during evaluation.
Figure9:Change in the fraction of responses that transition their correctness values over the course of multi-turn
rollouts from RISE, w/o oracle. Observe that in general, the fraction of Correct →Correct responses increases; Incorrect →
Incorrect responses decreases; and the fraction of Correct →Incorrect responses also decreases, indicating that RISE (w/o any
oracle) is able to iteratively improve its responses.
Qualitative examples. We also inspect several examples from the GSM8K test set to qualitatively
understand the behavior of RISE over turns and observe different behavior patterns, that we show in
Appendix B.2. For instance, the trained model may choose to completely rewrite its previous response if
it is totally incorrect in order to get to the correct answer or make small edits if the previous response is
mostly correct. Another interesting pattern we note is that the model implicitly has the ability to locate
errors in previous responses and only refine the erroneous steps. Additionally, the model is tolerant of
noisy environmental feedback when there is no oracle-assisted early termination.
7. Discussion, Future Directions, and Limitations
We presented RISE, an approach for fine-tuning LLMs to be able to improve their own responses over
multiple turns sequentially. RISE prescribes an iterative RL recipe on top of on-policy rollout data, with
15
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
expert or self-generated supervision to steer self-improvement. RISE significantly improves the self-
improvement abilities of 7B models on reasoning tasks (GSM8K and MATH), attaining an improvement
over turns that previous work [ 21] has not observed in strong proprietary models. In addition, RISE
outperforms prior approaches that attempt to tackle similar problems of refinement and correction, while
being simpler in that it does not require running multiple models and works well with just one model.
Despite these good results, there are still many open questions and limitations. Due to computational
constraints, we were not able to perform more than two iterations of training with RISE, and no more
than one iteration when the supervision comes from the learner itself. Improving with self-generated
supervision will likely require more computation and more iterations, since it will be slower than when
using an off-the-shelf expert model. RISE requires running manual iterations and hence, a more “online”
variant of RISE is likely the solution in the long run, especially when we wish to scale on-policy learning
in a data-efficient manner. Additionally, while our work fine-tunes models on one task at a time, it will
be certainly interesting to include data from the protocols specified by RISE into general instruction
tuning and post-training pipelines. Given the results that fine-tuning on data prescribed by RISE does not
hurt the first-turn performance of any model we trained, we hypothesize that adding this sort of data in
generalinstruction-tuningpipelinesshouldnothurteither,whileenablingthesequentialself-improvement
capability that is largely absent from models today.
Acknowledgements
This work was done at CMU. We thank Fahim Tajwar, Abitha Thankaraj, Amrith Setlur, and Charlie Snell
for their feedback and informative discussions. This work was supported by ONR under N000142412206,
OpenAI superalignment fast grants, and used the Delta system and JetStream2 [ 16] at the National
Center for Supercomputing Applications through CIS240249 and CIS230278, supported by the National
Science Foundation. We thank OpenAI for providing GPT-4 credits for academic use.
References
[1]Rishabh Agarwal, Nino Vieillard, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Gkd: Generalized knowledge distillation for auto-regressive sequence models. arXiv preprint
arXiv:2306.13649 , 2023.
[2]Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna
Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. Constitutional ai: Harmlessness
from ai feedback. arXiv preprint arXiv:2212.08073 , 2022.
[3]Collin Burns, Pavel Izmailov, Jan Hendrik Kirchner, Bowen Baker, Leo Gao, Leopold Aschenbrenner,
Yining Chen, Adrien Ecoffet, Manas Joglekar, Jan Leike, Ilya Sutskever, and Jeff Wu. Weak-to-
strong generalization: Eliciting strong capabilities with weak supervision, 2023. URL https:
//arxiv.org/abs/2312.09390 .
[4]Jonathan D Chang, Wenhao Shan, Owen Oertell, Kianté Brantley, Dipendra Misra, Jason D Lee,
and Wen Sun. Dataset reset policy optimization for rlhf. arXiv preprint arXiv:2404.08495 , 2024.
[5]Yiannis Charalambous, Norbert Tihanyi, Ridhi Jain, Youcheng Sun, Mohamed Amine Ferrag, and
Lucas C Cordeiro. A new era in software security: Towards self-healing software via large language
models and formal verification. arXiv preprint arXiv:2305.14752 , 2023.
16
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[6]Baian Chen, Chang Shu, Ehsan Shareghi, Nigel Collier, Karthik Narasimhan, and Shunyu Yao.
Fireact: Toward language agent fine-tuning, 2023.
[7]Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models
to self-debug. arXiv preprint arXiv:2304.05128 , 2023.
[8]Zixiang Chen, Yihe Deng, Huizhuo Yuan, Kaixuan Ji, and Quanquan Gu. Self-play fine-tuning
converts weak language models to strong language models. arXiv preprint arXiv:2401.01335 , 2024.
[9]Yew Ken Chia, Guizhen Chen, Luu Anh Tuan, Soujanya Poria, and Lidong Bing. Contrastive
chain-of-thought prompting. arXiv preprint arXiv:2311.09277 , 2023.
[10]KarlCobbe, ChristopherHesse, JacobHilton, andJohnSchulman. Leveragingproceduralgeneration
to benchmark reinforcement learning. arXiv preprint arXiv:1912.01588 , 2019.
[11]KarlCobbe,VineetKosaraju,MohammadBavarian,MarkChen,HeewooJun,LukaszKaiser,Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman.
Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168 , 2021.
[12]Yilun Du, Shuang Li, Antonio Torralba, Joshua B Tenenbaum, and Igor Mordatch. Improving factual-
ity and reasoning in language models through multiagent debate. arXiv preprint arXiv:2305.14325 ,
2023.
[13]Kanishk Gandhi, Denise Lee, Gabriel Grand, Muxin Liu, Winson Cheng, Archit Sharma, and Noah D
Goodman. Stream of search (sos): Learning to search in language. arXiv preprint arXiv:2404.03683 ,
2024.
[14]Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and
Graham Neubig. Pal: Program-aided language models. In International Conference on Machine
Learning , pages 10764–10799. PMLR, 2023.
[15]Zhibin Gou, Zhihong Shao, Yeyun Gong, Yelong Shen, Yujiu Yang, Nan Duan, and Weizhu Chen.
Critic: Large Language Models can Self-Correct with Tool-Interactive Critiquing. arXiv preprint
arXiv:2305.11738 , 2023.
[16]David Y. Hancock, Jeremy Fischer, John Michael Lowe, Winona Snapp-Childs, Marlon Pierce,
Suresh Marru, J. Eric Coulter, Matthew Vaughn, Brian Beck, Nirav Merchant, Edwin Skidmore,
and Gwen Jacobs. Jetstream2: Accelerating cloud computing via jetstream. In Practice and
Experience in Advanced Research Computing , PEARC ’21, New York, NY, USA, 2021. Association
for Computing Machinery. ISBN 9781450382922. doi: 10.1145/3437359.3465565. URL https:
//doi.org/10.1145/3437359.3465565 .
[17]Alex Havrilla, Sharath Raparthy, Christoforus Nalmpantis, Jane Dwivedi-Yu, Maksym Zhuravinskyi,
Eric Hambro, and Roberta Railneau. Glore: When, where, and how to improve llm reasoning via
global and local refinements. arXiv preprint arXiv:2402.10963 , 2024.
[18]Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song,
and Jacob Steinhardt. Measuring mathematical problem solving with the math dataset. NeurIPS ,
2021.
17
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[19]Arian Hosseini, Xingdi Yuan, Nikolay Malkin, Aaron Courville, Alessandro Sordoni, and Rishabh
Agarwal. V-star: Training verifiers for self-taught reasoners. arXiv preprint arXiv:2402.06457 , 2024.
[20]Dong Huang, Qingwen Bu, Jie M Zhang, Michael Luck, and Heming Cui. Agentcoder: Multi-agent-
based code generation with iterative testing and optimisation. arXiv preprint arXiv:2312.13010 ,
2023.
[21]Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Wei Yu, Xinying Song,
and Denny Zhou. Large language models cannot self-correct reasoning yet. arXiv preprint
arXiv:2310.01798 , 2023.
[22]Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot
planners: Extracting actionable knowledge for embodied agents. In International Conference on
Machine Learning , pages 9118–9147. PMLR, 2022.
[23]Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot,
Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, et al.
Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[24]Katie Kang, Eric Wallace, Claire Tomlin, Aviral Kumar, and Sergey Levine. Unfamiliar finetuning
examples control how language models hallucinate, 2024.
[25]Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2022. URL https://
arxiv.org/abs/1312.6114 .
[26]Lucas Lehnert, Sainbayar Sukhbaatar, Paul Mcvay, Michael Rabbat, and Yuandong Tian. Be-
yond a*: Better planning with transformers via search dynamics bootstrapping. arXiv preprint
arXiv:2402.14083 , 2024.
[27]Chen Li, Weiqi Wang, Jingcheng Hu, Yixuan Wei, Nanning Zheng, Han Hu, Zheng Zhang, and
HouwenPeng. Common7blanguagemodelsalreadypossessstrongmathcapabilities. arXivpreprint
arXiv:2403.04706 , 2024.
[28]Hunter Lightman, Vineet Kosaraju, Yura Burda, Harri Edwards, Bowen Baker, Teddy Lee, Jan
Leike, John Schulman, Ilya Sutskever, and Karl Cobbe. Let’s verify step by step. arXiv preprint
arXiv:2305.20050 , 2023.
[29]XiaoLiu, HaoYu, HanchenZhang, YifanXu, XuanyuLei, HanyuLai, YuGu, HangliangDing, Kaiwen
Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688 ,
2023.
[30]HaipengLuo,QingfengSun,CanXu,PuZhao,JianguangLou,ChongyangTao,XiuboGeng,Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. Wizardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct. arXiv preprint arXiv:2308.09583 , 2023.
[31]Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri
Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with
self-feedback. arXiv preprint arXiv:2303.17651 , 2023.
18
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[32]Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and
Caiming Xiong. CodeGen: An Open Large Language Model for Code with Multi-Turn Program
Synthesis. ICLR, 2023.
[33]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David
Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. Show your work:
Scratchpads for intermediate computation with language models. arXiv preprint arXiv:2112.00114 ,
2021.
[34]Xue Bin Peng, Aviral Kumar, Grace Zhang, and Sergey Levine. Advantage-weighted regression:
Simple and scalable off-policy reinforcement learning. arXiv preprint arXiv:1910.00177 , 2019.
[35]JanPetersandStefanSchaal. Reinforcementlearningbyreward-weightedregressionforoperational
spacecontrol. In Proceedingsofthe24thinternationalconferenceonMachinelearning ,pages745–750.
ACM, 2007.
[36]StephaneRoss,GeoffreyGordon,andDrewBagnell. Areductionofimitationlearningandstructured
prediction to no-regret online learning. In Geoffrey Gordon, David Dunson, and Miroslav Dudík,
editors, Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics ,
volume 15 of Proceedings of Machine Learning Research , pages 627–635, Fort Lauderdale, FL, USA,
11–13 Apr 2011. PMLR. URL http://proceedings.mlr.press/v15/ross11a.html .
[37]Corby Rosset, Ching-An Cheng, Arindam Mitra, Michael Santacroce, Ahmed Awadallah, and
Tengyang Xie. Direct nash optimization: Teaching language models to self-improve with general
preferences. arXiv preprint arXiv:2404.03715 , 2024.
[38]Swarnadeep Saha, Omer Levy, Asli Celikyilmaz, Mohit Bansal, Jason Weston, and Xian Li.
Branch-solve-merge improves large language model evaluation and generation. arXiv preprint
arXiv:2310.15123 , 2023.
[39]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer,
Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use
tools.arXiv preprint arXiv:2302.04761 , 2023.
[40]Noah Shinn, Beck Labash, and Ashwin Gopinath. Reflexion: an autonomous agent with dynamic
memory and self-reflection. arXiv preprint arXiv:2303.11366 , 2023.
[41]Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, and Sergey Levine. Offline rl for natural
language generation with implicit language q learning. arXiv preprint arXiv:2206.11871 , 2022.
[42]JaschaSohl-Dickstein,EricA.Weiss,NiruMaheswaranathan,andSuryaGanguli. Deepunsupervised
learning using nonequilibrium thermodynamics, 2015. URL https://arxiv.org/abs/1503.
03585.
[43]Yang Song and Diederik P. Kingma. How to train your energy-based models, 2021. URL https:
//arxiv.org/abs/2101.03288 .
[44]Liting Sun, Cheng Peng, Wei Zhan, and Masayoshi Tomizuka. A fast integrated planning and
control framework for autonomous driving via imitation learning. In Dynamic Systems and Control
Conference , volume 51913, page V003T37A012. American Society of Mechanical Engineers, 2018.
19
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[45]Gokul Swamy, Sanjiban Choudhury, J. Andrew Bagnell, and Zhiwei Steven Wu. Inverse reinforce-
ment learning without reinforcement learning, 2024. URL https://arxiv.org/abs/2303.
14623.
[46]Shubham Toshniwal, Ivan Moshkov, Sean Narenthiran, Daria Gitman, Fei Jia, and Igor Gitman.
Openmathinstruct-1: A1.8millionmathinstructiontuningdataset. arXivpreprintarXiv:2402.10176 ,
2024.
[47]Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia
Creswell, Geoffrey Irving, and Irina Higgins. Solving math word problems with process-and
outcome-based feedback. arXiv preprint arXiv:2211.14275 , 2022.
[48]Boshi Wang, Sewon Min, Xiang Deng, Jiaming Shen, You Wu, Luke Zettlemoyer, and Huan Sun.
Towards understanding chain-of-thought prompting: An empirical study of what matters. arXiv
preprint arXiv:2212.10001 , 2022.
[49]Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and
Anima Anandkumar. Voyager: An open-ended embodied agent with large language models. arXiv
preprint arXiv: Arxiv-2305.16291 , 2023.
[50]Peiyi Wang, Lei Li, Zhihong Shao, RX Xu, Damai Dai, Yifei Li, Deli Chen, Y Wu, and Zhifang
Sui. Math-shepherd: Verify and reinforce llms step-by-step without human annotations. CoRR,
abs/2312.08935 , 2023.
[51]XuezhiWang,JasonWei,DaleSchuurmans,QuocLe,EdChi,SharanNarang,AakankshaChowdhery,
and Denny Zhou. Self-consistency improves chain of thought reasoning in language models. arXiv
preprint arXiv:2203.11171 , 2022.
[52]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny
Zhou, et al. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS ,
2022.
[53]Sean Welleck, Ximing Lu, Peter West, Faeze Brahman, Tianxiao Shen, Daniel Khashabi, and Yejin
Choi. Generating sequences by learning to self-correct. In The Eleventh International Conference on
Learning Representations , 2023. URL https://openreview.net/forum?id=hH36JeQZDaO .
[54]Hui Yang, Sifu Yue, and Yunzhong He. Auto-gpt for online decision making: Benchmarks and
additional opinions. arXiv preprint arXiv:2306.02224 , 2023.
[55]Kaiyu Yang, Aidan M Swope, Alex Gu, Rahul Chalamala, Peiyang Song, Shixing Yu, Saad Godil,
Ryan Prenger, and Anima Anandkumar. LeanDojo: Theorem Proving with Retrieval-Augmented
Language Models. arXiv preprint arXiv:2306.15626 , 2023.
[56]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao.
React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629 ,
2022.
[57]LonghuiYu, WeisenJiang, HanShi, JinchengYu, ZhengyingLiu, YuZhang, JamesTKwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. Metamath: Bootstrap your own mathematical questions for
large language models. arXiv preprint arXiv:2309.12284 , 2023.
20
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[58]Lifan Yuan, Ganqu Cui, Hanbin Wang, Ning Ding, Xingyao Wang, Jia Deng, Boji Shan, Huimin
Chen, Ruobing Xie, Yankai Lin, et al. Advancing llm reasoning generalists with preference trees.
arXiv preprint arXiv:2404.02078 , 2024.
[59] Weizhe Yuan, Richard Yuanzhe Pang, Kyunghyun Cho, Sainbayar Sukhbaatar, Jing Xu, and Jason
Weston. Self-rewarding language models. arXiv preprint arXiv:2401.10020 , 2024.
[60]Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wenhao Huang, Huan Sun, Yu Su, and Wenhu Chen.
Mammoth: Building math generalist models through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 , 2023.
[61]Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Goodman. Star: Bootstrapping reasoning with
reasoning. Advances in Neural Information Processing Systems , 35:15476–15488, 2022.
[62]Aohan Zeng, Mingdao Liu, Rui Lu, Bowen Wang, Xiao Liu, Yuxiao Dong, and Jie Tang. Agenttuning:
Enabling generalized agent abilities for llms. arXiv preprint arXiv:2310.12823 , 2023.
[63]Tianjun Zhang, Xuezhi Wang, Denny Zhou, Dale Schuurmans, and Joseph E Gonzalez. Tempera:
Test-time prompting via reinforcement learning. arXiv preprint arXiv:2211.11890 , 2022.
[64]Tianjun Zhang, Aman Madaan, Luyu Gao, Steven Zheng, Swaroop Mishra, Yiming Yang, Niket
Tandon, and Uri Alon. In-context principle learning from mistakes. arXiv preprint arXiv:2402.05403 ,
2024.
[65]Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang, and Yu-Xiong Wang. Lan-
guage agent tree search unifies reasoning acting and planning in language models. arXiv preprint
arXiv:2310.04406 , 2023.
[66]Yifei Zhou, Andrea Zanette, Jiayi Pan, Sergey Levine, and Aviral Kumar. Archer: Training language
model agents via hierarchical multi-turn rl. arXiv preprint arXiv:2402.19446 , 2024.
21
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Appendices
A. Additional Ablations on Data Composition and Weak-to-Strong Generalization
A.1. Inclusion of Correct-to-Correct Data
Intuitively, self-improvement over turns is largely only possible when the model can learn to verify the
correctness of its previous response and decide to appropriately modify its response toward correctness.
Thus far, the RISE has only trained on data that showed how to convert incorrect responses to correct
responses but never illustrated how the model could act on correct responses. To understand if perfor-
mance can be boosted by also illustrating examples of how the model could act on correct responses, we
ran a number of ablations. We took the RISE data generated during Iteration 1 of training on GSM8K
with Llama2-7B and modified the multi-turn rollouts to create several cases. First, we duplicated the
correct response appearing at the end of every successful multi-turn rollout and trained for one extra turn.
This should teach the model that correct responses should not be modified, unlike incorrect responses
appearing in previous turns in the rollout. Second, we also ran a variant in which the correct response
appearing at the end of every successful rollout is followed by a different correct response. This variant
should teach the model that if it chooses to modify a correct response, it must still produce another
correct response.
As shown in Table 4, all methods improved performance over the base model, though only appending
with a successful rollout with a novel correct response leads to best performance. The default design of
RISE in the main paper attains a close second position, and repeating a correct response at the end of a
successful rollout largely reduces performance. We suspect that the poor performance of repeating the
same correct response is largely a result of inducing spurious correlations due to data duplication.
RISE (Llama2)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0)
+RISE (default) 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+Repeating a correct response 34.2 48.9 (+14.6) 46.2(+12.6) 57.7(+23.5)
+Appending a different correct response 33.1 49.3 (+16.2) 51.1(+18.0) 64.9(+31.8)
Table 4: Comparison of model performance on GSM8K with different mechanisms of adding correct-to-correct data in
RISE.Values in parentheses indicate improvement over m1@t1, note that appending a successful rollout with a a novel correct
response leads to the highest performance gains.
To further investigate self-improvement capabilities, we analyzed the percentage of correct responses
changing to incorrect responses in consecutive turns (T 𝑖to T𝑖+ 1), as illustrated in Figure 10. Generally, a
decreasing trend suggests better self-improvement, while lower absolute values indicate better resistance
to noisy feedback. The results reveal unexpected patterns across configurations. The Boost configuration
shows the poorest performance, with the highest overall percentages and an increase from turn 4 to
5, suggesting that it struggles to consistently maintain correct responses. Repeating a correct response
shows the lowest initial percentage (6.3%) but increases from turn 3 onward, indicating potential issues
in extended interactions. Both Default RISE and appending a different correct response demonstrate a
favorable trend, steadily decreasing from 12.3% to 3.9% and from 9.8% to 3.3%, respectively, suggesting
a good balance between maintaining correct responses and allowing improvements. These findings
provide nuanced insights into the stability and self-improvement capabilities of RISE and align with our
earlier observation of its superior performance in overall accuracy.
22
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure10:Percentage of correct responses in turn T 𝑖that change to being incorrect in turn T 𝑖+1.This figure illustrates
the percentage of correct responses that change to incorrect responses across consecutive turns (T 𝑖to T𝑖+1) for different model
configurations. A continuously decreasing trend suggests better self-improvement performance.
A.2. Weak-to-Strong Generalization: RISE on Weak Model Data Improves Strong Models
In this section, we compare the performance of Llama2 and Mistral-7B with RISE in the weak-to-strong
setting[ 3]. Concretely,weareinterestedinusingdatageneratedviaRISEwithaweakmodel(Llama2-7B)
to train a strong model (Mistral-7B). Our analysis reveals intriguing insights into the transferability of
RISE-generated data across models of different capabilities.
RISEw/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Llama2-7B 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4)
+ Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+ Iteration 1 (Mistral-7B) 27.1 40.1 (+13.0) 45.2(+18.1) 59.1(+32.0)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3)
+ Iteration 1 (Llama2-7B) 38.2 55.4 (+17.2) 62.7(+24.5) 73.5(+35.3)
Table 5: Weak-to-strong generalization on GSM8K. Comparing performance of RISE when training on rollouts generated
by Llama2-7B vs Mistral-7B. Note that training the Mistral-7B model on rollouts generated by the weaker Llama2-7B with
RISE improves performance compared to using data generated by the Mistral-7B model itself. However, the reverse is not true:
training the Llama2 model on Mistral’s mistakes leads to worse performance, likely because errors from the Mistral-7B model
are harder to comprehend for a worse base model. All values are in % accuracy, and values in parentheses indicate improvement
over m1@t1.
As shown in Table 5, we find that Mistral-7B + Iteration 1 data generated from Llama2 outperforms
training the Llama2-7B model itself on these data (i.e., Llama2-7B + Iteration1) on all the metrics
reported with particularly significant improvements in multi-turn reasoning (m1@t5). In fact, training
on multi-turn rollouts from Llama2-7B also outperforms training on on-policy Mistral-7B rollouts as well.
Interestingly, we observed that training Llama2-7B on multi-turn rollouts from Mistral-7B performs worse
than training on on-policy Llama2-7B rollouts, suggesting that Llama2-7B, despite its lower absolute
performance, demonstrates more informative mistakes that can be leveraged to better boost the self-
improvement capability. This phenomenon underscores the importance of the quality and nature of
errors in the training data, rather than just the overall performance of the model that generates them.
These findings collectively suggest that the data generated from a weaker Llama2 model can still be used
to induce a self-improvement capability in a stronger model, although the reverse is not true (as is also
evident from the fact that using GPT-3.5 rollouts in the boosting phase for training does not improve
performance for any model in Table 1). We suspect that this is becaue the reverse poses a much harder
23
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
learning problem since a weak model need to internalize the mistakes of a stronger model, resulting in
hallucinations and memorization [ 24]. Note that training on these data does not degrade single-turn
performance either. This hints at an added benefit of training with RISE: weak-to-strong generalization,
which can be quite useful in practice when rolling out stronger models is expensive.
B. Additional Results
B.1. Complete Comparisons and Discussion: Extended Version of Table 1
We provide an extended version of Table 1, with a clear explanation of how we implement baselines and
a discussion of comparisons.
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(+0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3) 6.7 9.5 (+2.8) 18.4(+11.1) 29.7(+22.4)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
Baselines
GPT-3.5 66.4 80.6 (+14.2) 71.0(+4.6) 74.7(+8.3) 39.7 47.8 (+8.1) 45.1(+5.4) 54.3(+14.6)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
Eurus-7b-SFT 36.3 66.3 (+30.0) 47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5) 16.3(+4.0) 22.9(+10.6)
Self-Refine →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0) 5.5 6.5 (+1.0) 2.9(-2.6) 7.2(+1.7)
+Iteration1 35.6 49.5 (+13.9) 31.7(-3.9) 43.7(+8.1) 6.3 8.7 (+2.4) 5.9(-0.4) 9.9(+3.6)
+Iteration2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7b-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) N/A
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
V-STaR →m64@t1
+STaR 28.0 46.1 (+18.1)
+Verification 28.0 56.2 (+28.2) N/A
+V-STaR 28.0 63.2 (+35.2)
Table 6: Comparing RISE with other approaches (Self-Refine, GLoRE, and V-STaR) and other baseline approaches.
Observe that RISE attains the biggest performance improvements between 1-turn and 5-turn performance without the use of
an oracle on both GSM8K and MATH. This performance gap is even larger when oracle early termination is allowed (5-turn
w/ oracle). Self-Refine largely degrades performance across the board. GLoRE trains a separate refinement model, but still
performs worse than RISE.
24
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Comparison with Self-Refine [ 31].To build a self-refine baseline [ 31] evaluation, we slightly modified
our evaluation pipeline following the self-refine approach. In this setup (Figure 11), the model generates
an initial response, and then the environment prompts the model to locate errors in the generated
solution and refine its answer based on the initial response and the identified error.
Self-Refine
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 17 >
User:<Query >
Agent:<Initial Answer >
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent:<Critic >
User: Now, rewrite the solution in the required format:
Agent:<Refined Answer >
Figure11:Prompt for Self-Refine : We follow the standard pipeline of the original paper, prompt the
LLM to refine and correct its previous mistakes.
However, our experiments show that without any oracle hint from the environment or human feedback,
the self-refine approach leads to a degradation in performance across all models. Only when oracle
feedback is available to assist with early termination does the self-refine approach provide a slight
performance boost. This highlights the limitation of the self-refine structure in effectively improving
model performance without external guidance, which is also observed in [22].
In contrast, the model trained with RISE can attain consistent performance improvements without relying
on an oracle. By training the model to iteratively refine its responses, our method enables the model to
self-correct and improve its performance over multiple turns. This showcases the effectiveness of our
approach incomparison to the self-refine baseline, as it allows for more robust and consistent performance
gains without the need for the oracle assistance.
Comparison with GLoRE [ 17].GLoRE is a multi-model system that relies on a student model to
propose drafts, an Outcome-based Reward Model (ORM) or Step-wise ORM to locate errors at different
granularity levels, and a Global or Local Refinement Model for adjusting these errors. Since no code
was openly available for this approach, in our experiments, we compared to the numbers from the main
paper Havrilla et al. [17]. While the comparison against GLoRE is already apples-to-oranges since our
25
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
method only trains a single end-to-end model, while GLoRE trains multiple models. Performance-wise,
GLoRE’s global and local refinement models show little to no improvement in overall accuracy without an
oracle, and even exhibit decreasing accuracy in some cases. However, when an oracle is used to guide the
refinement process, GLoRE demonstrates a 10% improvement on the 7B model in the GSM8K dataset.
As anticipated, since we run RISE from a less advanced base model (Llama2 7B), we observe a slightly
lower absolute performance compared to GLoRE. However, RISE demonstrates its effectiveness in self-
improvement by sequentially enhancing its performance by an impressive 13.4% within just 3 turns
without an oracle feedback, and by a remarkable 23.4% with an oracle on GSM8K. This showcase of
RISE’s capabilities is particularly noteworthy considering that GLoRE utilizes 3 independent models -
one for generating candidate solutions, one reward model for locating errors, and one refinement model
for refinement.
Comparison with V-STaR [ 19].V-STaR requires training an additional verifier model to rank candidate
answers generated by the targeted model, but it does not make any sequential revisions or improvements
to a response. While comparing RISE to using a verifier for re-ranking the top 5 responses at the first
turn (as a base comparison) would have been informative, we were unable to find this specific result
in the original V-STaR paper. The results presented in the official table 6 for V-STaR correspond to
running 64 samples, which improves the base model’s performance by 35.2% for each prompt during
evaluation. In contrast, our method, RISE, after the same amount of finetuning iterations (3 iterations)
and using only 5 samples, improves upon the base model by 44.5% (calculated as 55.0% - 10.5% =
44.5%). This comparison highlights RISE’s efficiency in achieving significant improvements with fewer
samples and iterations compared to V-STaR’s approach of using a large number of samples without
sequential refinement.
Moreover, V-STaR’s performance is inherently bounded by the candidate generator’s performance. As
discussed in Section 5, if there is no correct response among the generated candidates, the problem
remains unsolved. In contrast, we show in Figure 6 that RISE can also solve problems that were not
solved by majority voting with a much higher budget in the first turn. Furthermore, we believe that
combining V-STaR with RISE could lead to even better performance, as RISE can generate better models
and a verifier can be complementarily used for filtering.
Comparison with other base models. Mistral-7B [ 23] and Eurus-7B-SFT [ 58] are models that exhibit
comparable performance to our method in terms of the absolute maj@5 performance. However, it
is crucial to note that these base models are fine-tuned using a vast amount of data, including data
specifically tuned for math reasoning performance [ 58], while our model is fine-tuned on a single domain.
That said, we do show that fine-tuning with RISE can still enhance the performance of Mistral-7B models.
To summarize, our method offers several advantages over GLoRE and V-STaR, such as end-to-end
error correction with a single model, superior performance with fewer samples, and the ability to solve
problems that cannot be solved by random sampling in the first turn. Although our maj@1 performance
is lower than GLoRE’s base model EI, which is an apples-to-oranges comparison our ultimate 5-turn
performance surpasses their best absolute performance in both oracle and non-oracle scenarios.
Compared to other base models like Mistral-7B and Eurus-7B-SFT, our method achieves comparable
performance while being fine-tuned on a single domain, and it can be generalized to better base models.
26
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
B.2. Qualitative Examples from RISE
In this section, we provide some qualitative examples showing the nature of edits made by RISE on
various datasets that we train on. We utilize the model from iteration 2 of RISE.
27
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Small Edits)
Query: Mike plays ping pong for 40 minutes. In the first 20 minutes, he scores 4 points. In the
second 20 minutes, he scores 25% more points. How many total points did he score?
Turn-1 Response :
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
So,Mikescores4+4=8pointsinthesecond20minutes.
Step 3: To find the total points, we need to add the points scored in the first and second 20 minutes.
total_points = 4 + 8 = 12.
Answer: 12✗
Turn-2 Response :
I apologize for the mistake. Let’s solve the problem step by step.
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
Thismeanshescores4+4*25%=4+1=5pointsinthesecond20minutes.
Step 3: To find the total points, we add the points scored in the first and second 20 minutes: 4 + 5
= 9 points.
Answer: 9✓
RISE Example (Big Edits)
Query: In a candy machine, there are 22 more than four times the number of pink gumballs as
there are blue gumballs. If there are 12 blue gumballs how many pink ones are there?
Turn-1 Response :
Step 1: Let’s assume the number of blue gumballs as x. Step 2: According to the given information,
there are 22 more than four times the number of pink gumballs as there are blue gumballs. So, the
number of pink gumballs can be expressed as 4x + 22. Step3:Wearegiventhatthereare12blue
gumballs,solet’ssubstitutexwith12intheequation.
Answer: 54✗
Turn-2 Response :
Let’s solve the problem step by step: Step 1: Let’s denote the number of blue gumballs as x. Step
2: We are given that the number of pink gumballs is 22 more than four times the number of blue
gumballs. So, the number of pink gumballs can be expressed as 4x + 22. Step3:Wearealsogiven
thatthereare12bluegumballs,sowecansubstitutex=12intotheexpressionforthenumberof
pinkgumballs:4*12+22=48+22=70Therefore,thereare
boxed70 pinkgumballs.
Answer: 70✓
Figure12:Examples of RISE correct its previous behavior in different modes. Some only make changes to a small part (small
edits), some may directly rewrite most of its previous answers (big edits) because the first step in the previous answer is wrong.
The mistaken steps of different turns are highlighted in red, and the correct are highlighted in green. This demonstrates shows
how RISE can correct its previous answers and finally get to a correct answer.
28
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Noise Tolerance)
Query: Ryan plants 2 flowers a day in his garden. After 15 days, how many flowers does he have if 5 did not grow?
Turn-1 Response :
Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15 days = 30 flowers in his garden.
Step 2: However, 5 flowers did not grow, so we need to subtract these non-growing flowers from the total count. Step 3:
Calculate the number of flowers that actually grew in Ryan’s garden. flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-2 Response :
Apologies for the mistake. Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total
of 2 flowers/day * 15 days = 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these
non-growing flowers from the total count. Step 3: Calculate the number of flowers that actually grew in Ryan’s garden.
flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-3 Response :
Let’s reevaluate the solution. Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15
days = 30 flowers in his garden. Step 2: However, 5 flowers did not grow, so we need to add these flowers to the total
count, as they were planted but did not grow. Step3:CalculatethetotalnumberofflowersinRyan’sgarden.total_flowers
=30flowers+5flowers=35flowers.
Answer: 35✗
Turn-4 Response
Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total of 2 flowers/day * 15 days
= 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these non-growing flowers from the
total count. Step 3: Calculate the total number of flowers in Ryan’s garden after subtracting the non-growing flowers.
total_flowers = total_planted_flowers - non_growing_flowers = 30 flowers - 5 flowers=
boxed25 flowers.
Answer: 25✓
Turn-5 Response
Let’s reevaluate the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, which is 2 flowers/day * 15 days = 30
flowers in total. Step 2: However, 5 flowers did not grow, so we have to subtract these 5 flowers from the total. Step 3:
Therefore, the total number of flowers Ryan has is 30 flowers (total planted) - 5 flowers (did not grow) =
boxed25 flowers.
Answer: 25✓
Figure13:Examples of RISE’s tolerance of noisy feedback . In the evaluation where there is no oracle, we use a verifier
that always tells the model, "The answer is incorrect. Please try again. Here’s the question: <Query >". We observe that from
turn 2 to turn 5, the model is still able to output the correct answer in 3 out of 4 turns. In the response at turn 4, the model
performs half of the solution correctly, and only the last step is wrong. In addition, in the turns where the model still outputs
the correct answer, it doesn’t directly copy the answer from the previous turn but instead comes up with a new paraphrase. This
demonstrates that RISE provides the model with tolerance to noisy feedback and does not randomly change its behavior upon
receiving a revisiting request. The mistaken steps of different turns are highlighted in red
29
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Error Localization)
Query: Josh decides to try flipping a house. He buys a house for $80,000 and then puts in $50,000 in repairs. This
increased the value of the house by 150%. How much profit did he make?
Turn-1 Response :
Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, which increases the value of the house by
150%. Step 3: To calculate the increase in value, we multiply the cost of the house by 150% and add it to the cost of the
house. increase_in_value = $80,000 * 150% = $120,000. Step4:Tocalculatetheprofit,wesubtractthecostofthe
housefromitsnewvalue.profit=increase_in_value -$80,000 =$120,000 -$80,000 =$40,000.
Answer: 40,000✗
Turn-2 Response :
Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, and
this increases the value of the house by 150%. Step 3: The percentage increase in value is 150% of $80,000, which is
$120,000 (80,000 * 1.5 = $120,000). Step4:Tofindtheactualamount thatwouldbeaddedtothehouse’svalueafter
repairs,weneedtosubtracttheamount hespentonrepairsfromtheincreased value,whichis$120,000 -$50,000 =
$70,000. Step5:TheprofitJoshwouldmakeisthedifferencebetweenthecostofbuyingthehouseandtheincreased
valueafterrepairs,whichis$70,000 -$80,000 =-$10,000 ($10,000 lessthantheinitialcost).
Answer: 0✗
Turn-3 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: This increases the value of the house by 150%. Step 4: To find the increase in value, we calculate 150%
of the original price of the house: 150% of $80,000 = $120,000. Step5:Theincreaseinvalueafterrepairsistheoriginal
priceplus150%oftheoriginalprice:$80,000 +$120,000 =$200,000. Step6:Joshsellsthehousefor$200,000 and
madeaprofitof$200,000 -$80,000 =$120,000.
Answer: 120,000✗
Turn-4 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in
$50,000 in repairs, increasing the value of the house by 150%. Step 3: The increase in value is 150% of $80,000, which
is $120,000 (80,000 * 1.5 = $120,000). Step4:Thetotalamount spent,includingthepurchaseofthehouseandthe
repairs,is$80,000 +$50,000 =$130,000. Step5:TheprofitJoshmadeistheincreaseinvalueafterrepairsminusthe
totalamount spent,whichis$120,000 -$130,000 =-$10,000. Therefore,Joshmadea
boxed0 profit.
Answer: 0✗
Turn-5 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: The repairs increase the value of the house by 150%. Step 4: The increase in value is $50,000, which is
150% of $33,333 (50,000 / 1.5 = $33,333). Step 5: The repairs cost $50,000, and the increase in value is $33,333. Step
6: Therefore, Josh’s profit is $33,333 - $50,000 = -$16,667. Therefore, Josh made a 16676 profit.
Answer: 16676 ✗
Figure14:ExamplesofRISEnotbeingabletocorrectitserrorwithin5stepsbutdemonstratingmeaningful errorlocalization
behavior . Even in turn 2, it has already solved the problem at step 4 but mistakenly takes another step and reaches the wrong
answer. The following turns are unable to correct this small error. Though this problem remains unsolved, we observe that (1)
the model is able to stick to the correct steps, where all responses reach an intermediate step of 12000 correctly, except for the
last response, where the model tries to modify the answer from one step ahead; (2) the model doesn’t repeat its responses,
which is a behavior we notice when evaluating some off-the-shelf models; and (3) the model is making meaningful changes to
the incorrect steps. In | Section not found | summary, although the final answer is still incorrect, we observe that through RISE, the model is able to
locate the error and perform local computation correctly. The mistaken steps of different turns are highlighted in red, and the
correct steps in turn 2 is highlighted in green.
30
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
C. Pseudocode
Algorithm 1 Data Collection at Iteration 𝑇
1:𝒟′
𝑇←𝒟′
𝑇−1
2:forindex 𝑖in{1, . . . ,|𝒟|}do
3: 𝑠1←𝑥𝑖
4:forstep𝑇′in{1, . . . , 𝑇−1}do
5: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇−1(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
6: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
7: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
8: if𝑟𝑖
𝑇′= 1then
9: break
10: end if
11:end for
12:if𝑟𝑖
𝑇′̸= 1then
13: 𝑇′←𝑇′+ 1
14: 𝑦𝑖
𝑇′←arg max ˜ 𝜋(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
15: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
16:end if
17:𝒟′
𝑇←𝒟′
𝑇∪{︀(︀
𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖
𝑡,𝑟𝑖
𝑡)︀}︀𝑇′
𝑡=1
18:end for
Algorithm 2 Inference at iteration 𝑇
1:forindex 𝑖in{1, . . . ,|𝒟|}do
2: 𝑠1←𝑥𝑖
3:forstep𝑇′in{1, . . . , 𝑁}do
4: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=max{1,𝑇′−𝑇}+𝑠𝑇′)
5: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
6: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
7:end for
8:forstep𝑇′in{1, . . . , 𝑁}do
9: ˜𝑦𝑖
𝑇′←majority voting{𝑦𝑖
𝑡}𝑇′
𝑡=1
10:end for
11:end for
31
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D. Experimental Details
D.1. Hyperparameters for Fine-Tuning with RISE
For finetuning, we utilize the FastChat codebase, but we customize the loss function to be weighted
by reward. The base models are directly loaded from Hugging Face: hrefhttps://huggingface.co/meta-
llama/Llama-2-7b-hfLlama-2-7b-chat-hf and Mistral-7B-Instruct-v0.2. The hyperparameters used for
finetuning are specified in Table 7.
Hyperparameter Values
bf16 True
epochs 2
per device train batch size 1
gpus 4xA40
gradient accumulation steps 16
learning rate 1e-5
weighted decay 0
warmup ratio 0.04
learning rate scheduler trype cosince
tf32 True
model max length 2048
Table 7: Hyperparameters used for RISE
D.2. Inference Hyperparameters
For API-based models, such as GPT-3.5, we directly query the official web API provided by OpenAI. In the
case of open-source models, we utilize FastChat to serve the model as a web API and interact with the
environment through API calls. Serving a 7B model requires a single A100 or A40 GPU. To control the
randomness and length of answers generated by the LLMs, we employ the hyperparameters specified in
Table 8.
Hyperparameters/Description Open-source GPT
temperature 1.0 0.7
top_p 1.0 1
max_new_tokens 1000 512
Table 8: The hyperparameter settings used for generating responses from open-source and the GPT
models.
D.3. Datasets
The GSM8K dataset consists of 7,473 problems in the training portion and 1,319 problems in the testing
portion. Similarly, the MATH dataset is divided into 7,500 problems for training and 1,000 problems
32
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
for testing. The training portions of both datasets are used to generate trajectories in each iteration of
the RISE method, while the testing portions are held out for evaluating the performance of the models.
Additionally, the SVAMP dataset, containing 1,000 problems, is used solely for evaluation purposes to
demonstrate the generalizability of our method.
For generating training trajectories, at iteration 𝑖, the current model is rolled out for a maximum of 𝑖
steps. Subsequently, an expert model, such as GPT-3.5, is employed to take the conversation history
between the current model and the environment and sample 5 responses. Among these responses, the
one with the highest reward is chosen, with arbitrary tie-breaking in case of multiple responses with the
same highest reward.
D.4. Prompts used for seeding RISE on the GSM8K and MATH tasks
Here we show the prompt we used for data generation and model evaluation:
RISE
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 16 >
User:<Query >
Agent:<Answer >
User: The answer is incorrect. Please try again. Here’s the question: <Query >
Agent:<Answer >
···
Figure15:Prompt for RISE : We follow the standard pipeline of math problem solving, prompt the LLM
to solve the problem and retry untill exceeds the maximum number of turns
33
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D.5. One-shot Example
RISE One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we subtract the total
number of students taking only math, only physics, and both from the total number of students in
the drama club. This gives us $60 - 16 - 7 - 20 = ∖boxed{17}$ students taking neither.
Answer:∖boxed{17}
Figure16:One-shot Example : Demonstrates how to solve a math problem step-by-step and the expected
answer format.
34
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Self-Refine One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we add the number
of students taking only math and only physics, then subtract this sum from the total number of
students in the drama club. This gives us $60 - (16 + 7) = ∖boxed{37}$ students taking neither.
Answer:∖boxed{37}
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent: Step 1: Correct. We need to find the number of students taking neither math nor physics.
Step 2: Correct. The given information is accurately stated.
Step 3: Correct. The calculation of students taking only math is correct.
Step 4: Correct. The calculation of students taking only physics is correct.
Step 5: Incorrect. The solution adds the number of students taking only math and only physics,
but this does not account for the students taking both subjects. By subtracting this sum from
thetotalnumberofstudents,thesolutiondouble-countsthestudentswhotakebothmathandphysics.
User: Now, rewrite the solution in the required format:
Agent:<Same as 16 >
Figure17:One-shot Example : Demonstrates the process of self-critique and error correction based on
the self-critique.
35 | Section not found | References
[1]Rishabh Agarwal, Nino Vieillard, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Gkd: Generalized knowledge distillation for auto-regressive sequence models. arXiv preprint
arXiv:2306.13649 , 2023.
[2]Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna
Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. Constitutional ai: Harmlessness
from ai feedback. arXiv preprint arXiv:2212.08073 , 2022.
[3]Collin Burns, Pavel Izmailov, Jan Hendrik Kirchner, Bowen Baker, Leo Gao, Leopold Aschenbrenner,
Yining Chen, Adrien Ecoffet, Manas Joglekar, Jan Leike, Ilya Sutskever, and Jeff Wu. Weak-to-
strong generalization: Eliciting strong capabilities with weak supervision, 2023. URL https:
//arxiv.org/abs/2312.09390 .
[4]Jonathan D Chang, Wenhao Shan, Owen Oertell, Kianté Brantley, Dipendra Misra, Jason D Lee,
and Wen Sun. Dataset reset policy optimization for rlhf. arXiv preprint arXiv:2404.08495 , 2024.
[5]Yiannis Charalambous, Norbert Tihanyi, Ridhi Jain, Youcheng Sun, Mohamed Amine Ferrag, and
Lucas C Cordeiro. A new era in software security: Towards self-healing software via large language
models and formal verification. arXiv preprint arXiv:2305.14752 , 2023.
16
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[6]Baian Chen, Chang Shu, Ehsan Shareghi, Nigel Collier, Karthik Narasimhan, and Shunyu Yao.
Fireact: Toward language agent fine-tuning, 2023.
[7]Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models
to self-debug. arXiv preprint arXiv:2304.05128 , 2023.
[8]Zixiang Chen, Yihe Deng, Huizhuo Yuan, Kaixuan Ji, and Quanquan Gu. Self-play fine-tuning
converts weak language models to strong language models. arXiv preprint arXiv:2401.01335 , 2024.
[9]Yew Ken Chia, Guizhen Chen, Luu Anh Tuan, Soujanya Poria, and Lidong Bing. Contrastive
chain-of-thought prompting. arXiv preprint arXiv:2311.09277 , 2023.
[10]KarlCobbe, ChristopherHesse, JacobHilton, andJohnSchulman. Leveragingproceduralgeneration
to benchmark reinforcement learning. arXiv preprint arXiv:1912.01588 , 2019.
[11]KarlCobbe,VineetKosaraju,MohammadBavarian,MarkChen,HeewooJun,LukaszKaiser,Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman.
Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168 , 2021.
[12]Yilun Du, Shuang Li, Antonio Torralba, Joshua B Tenenbaum, and Igor Mordatch. Improving factual-
ity and reasoning in language models through multiagent debate. arXiv preprint arXiv:2305.14325 ,
2023.
[13]Kanishk Gandhi, Denise Lee, Gabriel Grand, Muxin Liu, Winson Cheng, Archit Sharma, and Noah D
Goodman. Stream of search (sos): Learning to search in language. arXiv preprint arXiv:2404.03683 ,
2024.
[14]Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and
Graham Neubig. Pal: Program-aided language models. In International Conference on Machine
Learning , pages 10764–10799. PMLR, 2023.
[15]Zhibin Gou, Zhihong Shao, Yeyun Gong, Yelong Shen, Yujiu Yang, Nan Duan, and Weizhu Chen.
Critic: Large Language Models can Self-Correct with Tool-Interactive Critiquing. arXiv preprint
arXiv:2305.11738 , 2023.
[16]David Y. Hancock, Jeremy Fischer, John Michael Lowe, Winona Snapp-Childs, Marlon Pierce,
Suresh Marru, J. Eric Coulter, Matthew Vaughn, Brian Beck, Nirav Merchant, Edwin Skidmore,
and Gwen Jacobs. Jetstream2: Accelerating cloud computing via jetstream. In Practice and
Experience in Advanced Research Computing , PEARC ’21, New York, NY, USA, 2021. Association
for Computing Machinery. ISBN 9781450382922. doi: 10.1145/3437359.3465565. URL https:
//doi.org/10.1145/3437359.3465565 .
[17]Alex Havrilla, Sharath Raparthy, Christoforus Nalmpantis, Jane Dwivedi-Yu, Maksym Zhuravinskyi,
Eric Hambro, and Roberta Railneau. Glore: When, where, and how to improve llm reasoning via
global and local refinements. arXiv preprint arXiv:2402.10963 , 2024.
[18]Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song,
and Jacob Steinhardt. Measuring mathematical problem solving with the math dataset. NeurIPS ,
2021.
17
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[19]Arian Hosseini, Xingdi Yuan, Nikolay Malkin, Aaron Courville, Alessandro Sordoni, and Rishabh
Agarwal. V-star: Training verifiers for self-taught reasoners. arXiv preprint arXiv:2402.06457 , 2024.
[20]Dong Huang, Qingwen Bu, Jie M Zhang, Michael Luck, and Heming Cui. Agentcoder: Multi-agent-
based code generation with iterative testing and optimisation. arXiv preprint arXiv:2312.13010 ,
2023.
[21]Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Wei Yu, Xinying Song,
and Denny Zhou. Large language models cannot self-correct reasoning yet. arXiv preprint
arXiv:2310.01798 , 2023.
[22]Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot
planners: Extracting actionable knowledge for embodied agents. In International Conference on
Machine Learning , pages 9118–9147. PMLR, 2022.
[23]Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot,
Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, et al.
Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[24]Katie Kang, Eric Wallace, Claire Tomlin, Aviral Kumar, and Sergey Levine. Unfamiliar finetuning
examples control how language models hallucinate, 2024.
[25]Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2022. URL https://
arxiv.org/abs/1312.6114 .
[26]Lucas Lehnert, Sainbayar Sukhbaatar, Paul Mcvay, Michael Rabbat, and Yuandong Tian. Be-
yond a*: Better planning with transformers via search dynamics bootstrapping. arXiv preprint
arXiv:2402.14083 , 2024.
[27]Chen Li, Weiqi Wang, Jingcheng Hu, Yixuan Wei, Nanning Zheng, Han Hu, Zheng Zhang, and
HouwenPeng. Common7blanguagemodelsalreadypossessstrongmathcapabilities. arXivpreprint
arXiv:2403.04706 , 2024.
[28]Hunter Lightman, Vineet Kosaraju, Yura Burda, Harri Edwards, Bowen Baker, Teddy Lee, Jan
Leike, John Schulman, Ilya Sutskever, and Karl Cobbe. Let’s verify step by step. arXiv preprint
arXiv:2305.20050 , 2023.
[29]XiaoLiu, HaoYu, HanchenZhang, YifanXu, XuanyuLei, HanyuLai, YuGu, HangliangDing, Kaiwen
Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688 ,
2023.
[30]HaipengLuo,QingfengSun,CanXu,PuZhao,JianguangLou,ChongyangTao,XiuboGeng,Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. Wizardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct. arXiv preprint arXiv:2308.09583 , 2023.
[31]Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri
Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with
self-feedback. arXiv preprint arXiv:2303.17651 , 2023.
18
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[32]Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and
Caiming Xiong. CodeGen: An Open Large Language Model for Code with Multi-Turn Program
Synthesis. ICLR, 2023.
[33]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David
Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. Show your work:
Scratchpads for intermediate computation with language models. arXiv preprint arXiv:2112.00114 ,
2021.
[34]Xue Bin Peng, Aviral Kumar, Grace Zhang, and Sergey Levine. Advantage-weighted regression:
Simple and scalable off-policy reinforcement learning. arXiv preprint arXiv:1910.00177 , 2019.
[35]JanPetersandStefanSchaal. Reinforcementlearningbyreward-weightedregressionforoperational
spacecontrol. In Proceedingsofthe24thinternationalconferenceonMachinelearning ,pages745–750.
ACM, 2007.
[36]StephaneRoss,GeoffreyGordon,andDrewBagnell. Areductionofimitationlearningandstructured
prediction to no-regret online learning. In Geoffrey Gordon, David Dunson, and Miroslav Dudík,
editors, Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics ,
volume 15 of Proceedings of Machine Learning Research , pages 627–635, Fort Lauderdale, FL, USA,
11–13 Apr 2011. PMLR. URL http://proceedings.mlr.press/v15/ross11a.html .
[37]Corby Rosset, Ching-An Cheng, Arindam Mitra, Michael Santacroce, Ahmed Awadallah, and
Tengyang Xie. Direct nash optimization: Teaching language models to self-improve with general
preferences. arXiv preprint arXiv:2404.03715 , 2024.
[38]Swarnadeep Saha, Omer Levy, Asli Celikyilmaz, Mohit Bansal, Jason Weston, and Xian Li.
Branch-solve-merge improves large language model evaluation and generation. arXiv preprint
arXiv:2310.15123 , 2023.
[39]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer,
Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use
tools.arXiv preprint arXiv:2302.04761 , 2023.
[40]Noah Shinn, Beck Labash, and Ashwin Gopinath. Reflexion: an autonomous agent with dynamic
memory and self-reflection. arXiv preprint arXiv:2303.11366 , 2023.
[41]Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, and Sergey Levine. Offline rl for natural
language generation with implicit language q learning. arXiv preprint arXiv:2206.11871 , 2022.
[42]JaschaSohl-Dickstein,EricA.Weiss,NiruMaheswaranathan,andSuryaGanguli. Deepunsupervised
learning using nonequilibrium thermodynamics, 2015. URL https://arxiv.org/abs/1503.
03585.
[43]Yang Song and Diederik P. Kingma. How to train your energy-based models, 2021. URL https:
//arxiv.org/abs/2101.03288 .
[44]Liting Sun, Cheng Peng, Wei Zhan, and Masayoshi Tomizuka. A fast integrated planning and
control framework for autonomous driving via imitation learning. In Dynamic Systems and Control
Conference , volume 51913, page V003T37A012. American Society of Mechanical Engineers, 2018.
19
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[45]Gokul Swamy, Sanjiban Choudhury, J. Andrew Bagnell, and Zhiwei Steven Wu. Inverse reinforce-
ment learning without reinforcement learning, 2024. URL https://arxiv.org/abs/2303.
14623.
[46]Shubham Toshniwal, Ivan Moshkov, Sean Narenthiran, Daria Gitman, Fei Jia, and Igor Gitman.
Openmathinstruct-1: A1.8millionmathinstructiontuningdataset. arXivpreprintarXiv:2402.10176 ,
2024.
[47]Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia
Creswell, Geoffrey Irving, and Irina Higgins. Solving math word problems with process-and
outcome-based feedback. arXiv preprint arXiv:2211.14275 , 2022.
[48]Boshi Wang, Sewon Min, Xiang Deng, Jiaming Shen, You Wu, Luke Zettlemoyer, and Huan Sun.
Towards understanding chain-of-thought prompting: An empirical study of what matters. arXiv
preprint arXiv:2212.10001 , 2022.
[49]Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and
Anima Anandkumar. Voyager: An open-ended embodied agent with large language models. arXiv
preprint arXiv: Arxiv-2305.16291 , 2023.
[50]Peiyi Wang, Lei Li, Zhihong Shao, RX Xu, Damai Dai, Yifei Li, Deli Chen, Y Wu, and Zhifang
Sui. Math-shepherd: Verify and reinforce llms step-by-step without human annotations. CoRR,
abs/2312.08935 , 2023.
[51]XuezhiWang,JasonWei,DaleSchuurmans,QuocLe,EdChi,SharanNarang,AakankshaChowdhery,
and Denny Zhou. Self-consistency improves chain of thought reasoning in language models. arXiv
preprint arXiv:2203.11171 , 2022.
[52]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny
Zhou, et al. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS ,
2022.
[53]Sean Welleck, Ximing Lu, Peter West, Faeze Brahman, Tianxiao Shen, Daniel Khashabi, and Yejin
Choi. Generating sequences by learning to self-correct. In The Eleventh International Conference on
Learning Representations , 2023. URL https://openreview.net/forum?id=hH36JeQZDaO .
[54]Hui Yang, Sifu Yue, and Yunzhong He. Auto-gpt for online decision making: Benchmarks and
additional opinions. arXiv preprint arXiv:2306.02224 , 2023.
[55]Kaiyu Yang, Aidan M Swope, Alex Gu, Rahul Chalamala, Peiyang Song, Shixing Yu, Saad Godil,
Ryan Prenger, and Anima Anandkumar. LeanDojo: Theorem Proving with Retrieval-Augmented
Language Models. arXiv preprint arXiv:2306.15626 , 2023.
[56]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao.
React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629 ,
2022.
[57]LonghuiYu, WeisenJiang, HanShi, JinchengYu, ZhengyingLiu, YuZhang, JamesTKwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. Metamath: Bootstrap your own mathematical questions for
large language models. arXiv preprint arXiv:2309.12284 , 2023.
20
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[58]Lifan Yuan, Ganqu Cui, Hanbin Wang, Ning Ding, Xingyao Wang, Jia Deng, Boji Shan, Huimin
Chen, Ruobing Xie, Yankai Lin, et al. Advancing llm reasoning generalists with preference trees.
arXiv preprint arXiv:2404.02078 , 2024.
[59] Weizhe Yuan, Richard Yuanzhe Pang, Kyunghyun Cho, Sainbayar Sukhbaatar, Jing Xu, and Jason
Weston. Self-rewarding language models. arXiv preprint arXiv:2401.10020 , 2024.
[60]Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wenhao Huang, Huan Sun, Yu Su, and Wenhu Chen.
Mammoth: Building math generalist models through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 , 2023.
[61]Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Goodman. Star: Bootstrapping reasoning with
reasoning. Advances in Neural Information Processing Systems , 35:15476–15488, 2022.
[62]Aohan Zeng, Mingdao Liu, Rui Lu, Bowen Wang, Xiao Liu, Yuxiao Dong, and Jie Tang. Agenttuning:
Enabling generalized agent abilities for llms. arXiv preprint arXiv:2310.12823 , 2023.
[63]Tianjun Zhang, Xuezhi Wang, Denny Zhou, Dale Schuurmans, and Joseph E Gonzalez. Tempera:
Test-time prompting via reinforcement learning. arXiv preprint arXiv:2211.11890 , 2022.
[64]Tianjun Zhang, Aman Madaan, Luyu Gao, Steven Zheng, Swaroop Mishra, Yiming Yang, Niket
Tandon, and Uri Alon. In-context principle learning from mistakes. arXiv preprint arXiv:2402.05403 ,
2024.
[65]Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang, and Yu-Xiong Wang. Lan-
guage agent tree search unifies reasoning acting and planning in language models. arXiv preprint
arXiv:2310.04406 , 2023.
[66]Yifei Zhou, Andrea Zanette, Jiayi Pan, Sergey Levine, and Aviral Kumar. Archer: Training language
model agents via hierarchical multi-turn rl. arXiv preprint arXiv:2402.19446 , 2024.
21
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Appendices
A. Additional Ablations on Data Composition and Weak-to-Strong Generalization
A.1. Inclusion of Correct-to-Correct Data
Intuitively, self-improvement over turns is largely only possible when the model can learn to verify the
correctness of its previous response and decide to appropriately modify its response toward correctness.
Thus far, the RISE has only trained on data that showed how to convert incorrect responses to correct
responses but never illustrated how the model could act on correct responses. To understand if perfor-
mance can be boosted by also illustrating examples of how the model could act on correct responses, we
ran a number of ablations. We took the RISE data generated during Iteration 1 of training on GSM8K
with Llama2-7B and modified the multi-turn rollouts to create several cases. First, we duplicated the
correct response appearing at the end of every successful multi-turn rollout and trained for one extra turn.
This should teach the model that correct responses should not be modified, unlike incorrect responses
appearing in previous turns in the rollout. Second, we also ran a variant in which the correct response
appearing at the end of every successful rollout is followed by a different correct response. This variant
should teach the model that if it chooses to modify a correct response, it must still produce another
correct response.
As shown in Table 4, all methods improved performance over the base model, though only appending
with a successful rollout with a novel correct response leads to best performance. The default design of
RISE in the main paper attains a close second position, and repeating a correct response at the end of a
successful rollout largely reduces performance. We suspect that the poor performance of repeating the
same correct response is largely a result of inducing spurious correlations due to data duplication.
RISE (Llama2)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0)
+RISE (default) 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+Repeating a correct response 34.2 48.9 (+14.6) 46.2(+12.6) 57.7(+23.5)
+Appending a different correct response 33.1 49.3 (+16.2) 51.1(+18.0) 64.9(+31.8)
Table 4: Comparison of model performance on GSM8K with different mechanisms of adding correct-to-correct data in
RISE.Values in parentheses indicate improvement over m1@t1, note that appending a successful rollout with a a novel correct
response leads to the highest performance gains.
To further investigate self-improvement capabilities, we analyzed the percentage of correct responses
changing to incorrect responses in consecutive turns (T 𝑖to T𝑖+ 1), as illustrated in Figure 10. Generally, a
decreasing trend suggests better self-improvement, while lower absolute values indicate better resistance
to noisy feedback. The results reveal unexpected patterns across configurations. The Boost configuration
shows the poorest performance, with the highest overall percentages and an increase from turn 4 to
5, suggesting that it struggles to consistently maintain correct responses. Repeating a correct response
shows the lowest initial percentage (6.3%) but increases from turn 3 onward, indicating potential issues
in extended interactions. Both Default RISE and appending a different correct response demonstrate a
favorable trend, steadily decreasing from 12.3% to 3.9% and from 9.8% to 3.3%, respectively, suggesting
a good balance between maintaining correct responses and allowing improvements. These findings
provide nuanced insights into the stability and self-improvement capabilities of RISE and align with our
earlier observation of its superior performance in overall accuracy.
22
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure10:Percentage of correct responses in turn T 𝑖that change to being incorrect in turn T 𝑖+1.This figure illustrates
the percentage of correct responses that change to incorrect responses across consecutive turns (T 𝑖to T𝑖+1) for different model
configurations. A continuously decreasing trend suggests better self-improvement performance.
A.2. Weak-to-Strong Generalization: RISE on Weak Model Data Improves Strong Models
In this section, we compare the performance of Llama2 and Mistral-7B with RISE in the weak-to-strong
setting[ 3]. Concretely,weareinterestedinusingdatageneratedviaRISEwithaweakmodel(Llama2-7B)
to train a strong model (Mistral-7B). Our analysis reveals intriguing insights into the transferability of
RISE-generated data across models of different capabilities.
RISEw/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Llama2-7B 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4)
+ Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+ Iteration 1 (Mistral-7B) 27.1 40.1 (+13.0) 45.2(+18.1) 59.1(+32.0)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3)
+ Iteration 1 (Llama2-7B) 38.2 55.4 (+17.2) 62.7(+24.5) 73.5(+35.3)
Table 5: Weak-to-strong generalization on GSM8K. Comparing performance of RISE when training on rollouts generated
by Llama2-7B vs Mistral-7B. Note that training the Mistral-7B model on rollouts generated by the weaker Llama2-7B with
RISE improves performance compared to using data generated by the Mistral-7B model itself. However, the reverse is not true:
training the Llama2 model on Mistral’s mistakes leads to worse performance, likely because errors from the Mistral-7B model
are harder to comprehend for a worse base model. All values are in % accuracy, and values in parentheses indicate improvement
over m1@t1.
As shown in Table 5, we find that Mistral-7B + Iteration 1 data generated from Llama2 outperforms
training the Llama2-7B model itself on these data (i.e., Llama2-7B + Iteration1) on all the metrics
reported with particularly significant improvements in multi-turn reasoning (m1@t5). In fact, training
on multi-turn rollouts from Llama2-7B also outperforms training on on-policy Mistral-7B rollouts as well.
Interestingly, we observed that training Llama2-7B on multi-turn rollouts from Mistral-7B performs worse
than training on on-policy Llama2-7B rollouts, suggesting that Llama2-7B, despite its lower absolute
performance, demonstrates more informative mistakes that can be leveraged to better boost the self-
improvement capability. This phenomenon underscores the importance of the quality and nature of
errors in the training data, rather than just the overall performance of the model that generates them.
These findings collectively suggest that the data generated from a weaker Llama2 model can still be used
to induce a self-improvement capability in a stronger model, although the reverse is not true (as is also
evident from the fact that using GPT-3.5 rollouts in the boosting phase for training does not improve
performance for any model in Table 1). We suspect that this is becaue the reverse poses a much harder
23
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
learning problem since a weak model need to internalize the mistakes of a stronger model, resulting in
hallucinations and memorization [ 24]. Note that training on these data does not degrade single-turn
performance either. This hints at an added benefit of training with RISE: weak-to-strong generalization,
which can be quite useful in practice when rolling out stronger models is expensive.
B. Additional Results
B.1. Complete Comparisons and Discussion: Extended Version of Table 1
We provide an extended version of Table 1, with a clear explanation of how we implement baselines and
a discussion of comparisons.
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(+0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3) 6.7 9.5 (+2.8) 18.4(+11.1) 29.7(+22.4)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
Baselines
GPT-3.5 66.4 80.6 (+14.2) 71.0(+4.6) 74.7(+8.3) 39.7 47.8 (+8.1) 45.1(+5.4) 54.3(+14.6)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
Eurus-7b-SFT 36.3 66.3 (+30.0) 47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5) 16.3(+4.0) 22.9(+10.6)
Self-Refine →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0) 5.5 6.5 (+1.0) 2.9(-2.6) 7.2(+1.7)
+Iteration1 35.6 49.5 (+13.9) 31.7(-3.9) 43.7(+8.1) 6.3 8.7 (+2.4) 5.9(-0.4) 9.9(+3.6)
+Iteration2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7b-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) N/A
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
V-STaR →m64@t1
+STaR 28.0 46.1 (+18.1)
+Verification 28.0 56.2 (+28.2) N/A
+V-STaR 28.0 63.2 (+35.2)
Table 6: Comparing RISE with other approaches (Self-Refine, GLoRE, and V-STaR) and other baseline approaches.
Observe that RISE attains the biggest performance improvements between 1-turn and 5-turn performance without the use of
an oracle on both GSM8K and MATH. This performance gap is even larger when oracle early termination is allowed (5-turn
w/ oracle). Self-Refine largely degrades performance across the board. GLoRE trains a separate refinement model, but still
performs worse than RISE.
24
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Comparison with Self-Refine [ 31].To build a self-refine baseline [ 31] evaluation, we slightly modified
our evaluation pipeline following the self-refine approach. In this setup (Figure 11), the model generates
an initial response, and then the environment prompts the model to locate errors in the generated
solution and refine its answer based on the initial response and the identified error.
Self-Refine
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 17 >
User:<Query >
Agent:<Initial Answer >
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent:<Critic >
User: Now, rewrite the solution in the required format:
Agent:<Refined Answer >
Figure11:Prompt for Self-Refine : We follow the standard pipeline of the original paper, prompt the
LLM to refine and correct its previous mistakes.
However, our experiments show that without any oracle hint from the environment or human feedback,
the self-refine approach leads to a degradation in performance across all models. Only when oracle
feedback is available to assist with early termination does the self-refine approach provide a slight
performance boost. This highlights the limitation of the self-refine structure in effectively improving
model performance without external guidance, which is also observed in [22].
In contrast, the model trained with RISE can attain consistent performance improvements without relying
on an oracle. By training the model to iteratively refine its responses, our method enables the model to
self-correct and improve its performance over multiple turns. This showcases the effectiveness of our
approach incomparison to the self-refine baseline, as it allows for more robust and consistent performance
gains without the need for the oracle assistance.
Comparison with GLoRE [ 17].GLoRE is a multi-model system that relies on a student model to
propose drafts, an Outcome-based Reward Model (ORM) or Step-wise ORM to locate errors at different
granularity levels, and a Global or Local Refinement Model for adjusting these errors. Since no code
was openly available for this approach, in our experiments, we compared to the numbers from the main
paper Havrilla et al. [17]. While the comparison against GLoRE is already apples-to-oranges since our
25
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
method only trains a single end-to-end model, while GLoRE trains multiple models. Performance-wise,
GLoRE’s global and local refinement models show little to no improvement in overall accuracy without an
oracle, and even exhibit decreasing accuracy in some cases. However, when an oracle is used to guide the
refinement process, GLoRE demonstrates a 10% improvement on the 7B model in the GSM8K dataset.
As anticipated, since we run RISE from a less advanced base model (Llama2 7B), we observe a slightly
lower absolute performance compared to GLoRE. However, RISE demonstrates its effectiveness in self-
improvement by sequentially enhancing its performance by an impressive 13.4% within just 3 turns
without an oracle feedback, and by a remarkable 23.4% with an oracle on GSM8K. This showcase of
RISE’s capabilities is particularly noteworthy considering that GLoRE utilizes 3 independent models -
one for generating candidate solutions, one reward model for locating errors, and one refinement model
for refinement.
Comparison with V-STaR [ 19].V-STaR requires training an additional verifier model to rank candidate
answers generated by the targeted model, but it does not make any sequential revisions or improvements
to a response. While comparing RISE to using a verifier for re-ranking the top 5 responses at the first
turn (as a base comparison) would have been informative, we were unable to find this specific result
in the original V-STaR paper. The results presented in the official table 6 for V-STaR correspond to
running 64 samples, which improves the base model’s performance by 35.2% for each prompt during
evaluation. In contrast, our method, RISE, after the same amount of finetuning iterations (3 iterations)
and using only 5 samples, improves upon the base model by 44.5% (calculated as 55.0% - 10.5% =
44.5%). This comparison highlights RISE’s efficiency in achieving significant improvements with fewer
samples and iterations compared to V-STaR’s approach of using a large number of samples without
sequential refinement.
Moreover, V-STaR’s performance is inherently bounded by the candidate generator’s performance. As
discussed in Section 5, if there is no correct response among the generated candidates, the problem
remains unsolved. In contrast, we show in Figure 6 that RISE can also solve problems that were not
solved by majority voting with a much higher budget in the first turn. Furthermore, we believe that
combining V-STaR with RISE could lead to even better performance, as RISE can generate better models
and a verifier can be complementarily used for filtering.
Comparison with other base models. Mistral-7B [ 23] and Eurus-7B-SFT [ 58] are models that exhibit
comparable performance to our method in terms of the absolute maj@5 performance. However, it
is crucial to note that these base models are fine-tuned using a vast amount of data, including data
specifically tuned for math reasoning performance [ 58], while our model is fine-tuned on a single domain.
That said, we do show that fine-tuning with RISE can still enhance the performance of Mistral-7B models.
To summarize, our method offers several advantages over GLoRE and V-STaR, such as end-to-end
error correction with a single model, superior performance with fewer samples, and the ability to solve
problems that cannot be solved by random sampling in the first turn. Although our maj@1 performance
is lower than GLoRE’s base model EI, which is an apples-to-oranges comparison our ultimate 5-turn
performance surpasses their best absolute performance in both oracle and non-oracle scenarios.
Compared to other base models like Mistral-7B and Eurus-7B-SFT, our method achieves comparable
performance while being fine-tuned on a single domain, and it can be generalized to better base models.
26
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
B.2. Qualitative Examples from RISE
In this section, we provide some qualitative examples showing the nature of edits made by RISE on
various datasets that we train on. We utilize the model from iteration 2 of RISE.
27
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Small Edits)
Query: Mike plays ping pong for 40 minutes. In the first 20 minutes, he scores 4 points. In the
second 20 minutes, he scores 25% more points. How many total points did he score?
Turn-1 Response :
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
So,Mikescores4+4=8pointsinthesecond20minutes.
Step 3: To find the total points, we need to add the points scored in the first and second 20 minutes.
total_points = 4 + 8 = 12.
Answer: 12✗
Turn-2 Response :
I apologize for the mistake. Let’s solve the problem step by step.
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
Thismeanshescores4+4*25%=4+1=5pointsinthesecond20minutes.
Step 3: To find the total points, we add the points scored in the first and second 20 minutes: 4 + 5
= 9 points.
Answer: 9✓
RISE Example (Big Edits)
Query: In a candy machine, there are 22 more than four times the number of pink gumballs as
there are blue gumballs. If there are 12 blue gumballs how many pink ones are there?
Turn-1 Response :
Step 1: Let’s assume the number of blue gumballs as x. Step 2: According to the given information,
there are 22 more than four times the number of pink gumballs as there are blue gumballs. So, the
number of pink gumballs can be expressed as 4x + 22. Step3:Wearegiventhatthereare12blue
gumballs,solet’ssubstitutexwith12intheequation.
Answer: 54✗
Turn-2 Response :
Let’s solve the problem step by step: Step 1: Let’s denote the number of blue gumballs as x. Step
2: We are given that the number of pink gumballs is 22 more than four times the number of blue
gumballs. So, the number of pink gumballs can be expressed as 4x + 22. Step3:Wearealsogiven
thatthereare12bluegumballs,sowecansubstitutex=12intotheexpressionforthenumberof
pinkgumballs:4*12+22=48+22=70Therefore,thereare
boxed70 pinkgumballs.
Answer: 70✓
Figure12:Examples of RISE correct its previous behavior in different modes. Some only make changes to a small part (small
edits), some may directly rewrite most of its previous answers (big edits) because the first step in the previous answer is wrong.
The mistaken steps of different turns are highlighted in red, and the correct are highlighted in green. This demonstrates shows
how RISE can correct its previous answers and finally get to a correct answer.
28
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Noise Tolerance)
Query: Ryan plants 2 flowers a day in his garden. After 15 days, how many flowers does he have if 5 did not grow?
Turn-1 Response :
Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15 days = 30 flowers in his garden.
Step 2: However, 5 flowers did not grow, so we need to subtract these non-growing flowers from the total count. Step 3:
Calculate the number of flowers that actually grew in Ryan’s garden. flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-2 Response :
Apologies for the mistake. Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total
of 2 flowers/day * 15 days = 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these
non-growing flowers from the total count. Step 3: Calculate the number of flowers that actually grew in Ryan’s garden.
flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-3 Response :
Let’s reevaluate the solution. Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15
days = 30 flowers in his garden. Step 2: However, 5 flowers did not grow, so we need to add these flowers to the total
count, as they were planted but did not grow. Step3:CalculatethetotalnumberofflowersinRyan’sgarden.total_flowers
=30flowers+5flowers=35flowers.
Answer: 35✗
Turn-4 Response
Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total of 2 flowers/day * 15 days
= 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these non-growing flowers from the
total count. Step 3: Calculate the total number of flowers in Ryan’s garden after subtracting the non-growing flowers.
total_flowers = total_planted_flowers - non_growing_flowers = 30 flowers - 5 flowers=
boxed25 flowers.
Answer: 25✓
Turn-5 Response
Let’s reevaluate the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, which is 2 flowers/day * 15 days = 30
flowers in total. Step 2: However, 5 flowers did not grow, so we have to subtract these 5 flowers from the total. Step 3:
Therefore, the total number of flowers Ryan has is 30 flowers (total planted) - 5 flowers (did not grow) =
boxed25 flowers.
Answer: 25✓
Figure13:Examples of RISE’s tolerance of noisy feedback . In the evaluation where there is no oracle, we use a verifier
that always tells the model, "The answer is incorrect. Please try again. Here’s the question: <Query >". We observe that from
turn 2 to turn 5, the model is still able to output the correct answer in 3 out of 4 turns. In the response at turn 4, the model
performs half of the solution correctly, and only the last step is wrong. In addition, in the turns where the model still outputs
the correct answer, it doesn’t directly copy the answer from the previous turn but instead comes up with a new paraphrase. This
demonstrates that RISE provides the model with tolerance to noisy feedback and does not randomly change its behavior upon
receiving a revisiting request. The mistaken steps of different turns are highlighted in red
29
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Error Localization)
Query: Josh decides to try flipping a house. He buys a house for $80,000 and then puts in $50,000 in repairs. This
increased the value of the house by 150%. How much profit did he make?
Turn-1 Response :
Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, which increases the value of the house by
150%. Step 3: To calculate the increase in value, we multiply the cost of the house by 150% and add it to the cost of the
house. increase_in_value = $80,000 * 150% = $120,000. Step4:Tocalculatetheprofit,wesubtractthecostofthe
housefromitsnewvalue.profit=increase_in_value -$80,000 =$120,000 -$80,000 =$40,000.
Answer: 40,000✗
Turn-2 Response :
Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, and
this increases the value of the house by 150%. Step 3: The percentage increase in value is 150% of $80,000, which is
$120,000 (80,000 * 1.5 = $120,000). Step4:Tofindtheactualamount thatwouldbeaddedtothehouse’svalueafter
repairs,weneedtosubtracttheamount hespentonrepairsfromtheincreased value,whichis$120,000 -$50,000 =
$70,000. Step5:TheprofitJoshwouldmakeisthedifferencebetweenthecostofbuyingthehouseandtheincreased
valueafterrepairs,whichis$70,000 -$80,000 =-$10,000 ($10,000 lessthantheinitialcost).
Answer: 0✗
Turn-3 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: This increases the value of the house by 150%. Step 4: To find the increase in value, we calculate 150%
of the original price of the house: 150% of $80,000 = $120,000. Step5:Theincreaseinvalueafterrepairsistheoriginal
priceplus150%oftheoriginalprice:$80,000 +$120,000 =$200,000. Step6:Joshsellsthehousefor$200,000 and
madeaprofitof$200,000 -$80,000 =$120,000.
Answer: 120,000✗
Turn-4 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in
$50,000 in repairs, increasing the value of the house by 150%. Step 3: The increase in value is 150% of $80,000, which
is $120,000 (80,000 * 1.5 = $120,000). Step4:Thetotalamount spent,includingthepurchaseofthehouseandthe
repairs,is$80,000 +$50,000 =$130,000. Step5:TheprofitJoshmadeistheincreaseinvalueafterrepairsminusthe
totalamount spent,whichis$120,000 -$130,000 =-$10,000. Therefore,Joshmadea
boxed0 profit.
Answer: 0✗
Turn-5 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: The repairs increase the value of the house by 150%. Step 4: The increase in value is $50,000, which is
150% of $33,333 (50,000 / 1.5 = $33,333). Step 5: The repairs cost $50,000, and the increase in value is $33,333. Step
6: Therefore, Josh’s profit is $33,333 - $50,000 = -$16,667. Therefore, Josh made a 16676 profit.
Answer: 16676 ✗
Figure14:ExamplesofRISEnotbeingabletocorrectitserrorwithin5stepsbutdemonstratingmeaningful errorlocalization
behavior . Even in turn 2, it has already solved the problem at step 4 but mistakenly takes another step and reaches the wrong
answer. The following turns are unable to correct this small error. Though this problem remains unsolved, we observe that (1)
the model is able to stick to the correct steps, where all responses reach an intermediate step of 12000 correctly, except for the
last response, where the model tries to modify the answer from one step ahead; (2) the model doesn’t repeat its responses,
which is a behavior we notice when evaluating some off-the-shelf models; and (3) the model is making meaningful changes to
the incorrect steps. In summary, although the final answer is still incorrect, we observe that through RISE, the model is able to
locate the error and perform local computation correctly. The mistaken steps of different turns are highlighted in red, and the
correct steps in turn 2 is highlighted in green.
30
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
C. Pseudocode
Algorithm 1 Data Collection at Iteration 𝑇
1:𝒟′
𝑇←𝒟′
𝑇−1
2:forindex 𝑖in{1, . . . ,|𝒟|}do
3: 𝑠1←𝑥𝑖
4:forstep𝑇′in{1, . . . , 𝑇−1}do
5: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇−1(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
6: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
7: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
8: if𝑟𝑖
𝑇′= 1then
9: break
10: end if
11:end for
12:if𝑟𝑖
𝑇′̸= 1then
13: 𝑇′←𝑇′+ 1
14: 𝑦𝑖
𝑇′←arg max ˜ 𝜋(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
15: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
16:end if
17:𝒟′
𝑇←𝒟′
𝑇∪{︀(︀
𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖
𝑡,𝑟𝑖
𝑡)︀}︀𝑇′
𝑡=1
18:end for
Algorithm 2 Inference at iteration 𝑇
1:forindex 𝑖in{1, . . . ,|𝒟|}do
2: 𝑠1←𝑥𝑖
3:forstep𝑇′in{1, . . . , 𝑁}do
4: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=max{1,𝑇′−𝑇}+𝑠𝑇′)
5: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
6: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
7:end for
8:forstep𝑇′in{1, . . . , 𝑁}do
9: ˜𝑦𝑖
𝑇′←majority voting{𝑦𝑖
𝑡}𝑇′
𝑡=1
10:end for
11:end for
31
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D. Experimental Details
D.1. Hyperparameters for Fine-Tuning with RISE
For finetuning, we utilize the FastChat codebase, but we customize the loss function to be weighted
by reward. The base models are directly loaded from Hugging Face: hrefhttps://huggingface.co/meta-
llama/Llama-2-7b-hfLlama-2-7b-chat-hf and Mistral-7B-Instruct-v0.2. The hyperparameters used for
finetuning are specified in Table 7.
Hyperparameter Values
bf16 True
epochs 2
per device train batch size 1
gpus 4xA40
gradient accumulation steps 16
learning rate 1e-5
weighted decay 0
warmup ratio 0.04
learning rate scheduler trype cosince
tf32 True
model max length 2048
Table 7: Hyperparameters used for RISE
D.2. Inference Hyperparameters
For API-based models, such as GPT-3.5, we directly query the official web API provided by OpenAI. In the
case of open-source models, we utilize FastChat to serve the model as a web API and interact with the
environment through API calls. Serving a 7B model requires a single A100 or A40 GPU. To control the
randomness and length of answers generated by the LLMs, we employ the hyperparameters specified in
Table 8.
Hyperparameters/Description Open-source GPT
temperature 1.0 0.7
top_p 1.0 1
max_new_tokens 1000 512
Table 8: The hyperparameter settings used for generating responses from open-source and the GPT
models.
D.3. Datasets
The GSM8K dataset consists of 7,473 problems in the training portion and 1,319 problems in the testing
portion. Similarly, the MATH dataset is divided into 7,500 problems for training and 1,000 problems
32
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
for testing. The training portions of both datasets are used to generate trajectories in each iteration of
the RISE method, while the testing portions are held out for evaluating the performance of the models.
Additionally, the SVAMP dataset, containing 1,000 problems, is used solely for evaluation purposes to
demonstrate the generalizability of our method.
For generating training trajectories, at iteration 𝑖, the current model is rolled out for a maximum of 𝑖
steps. Subsequently, an expert model, such as GPT-3.5, is employed to take the conversation history
between the current model and the environment and sample 5 responses. Among these responses, the
one with the highest reward is chosen, with arbitrary tie-breaking in case of multiple responses with the
same highest reward.
D.4. Prompts used for seeding RISE on the GSM8K and MATH tasks
Here we show the prompt we used for data generation and model evaluation:
RISE
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 16 >
User:<Query >
Agent:<Answer >
User: The answer is incorrect. Please try again. Here’s the question: <Query >
Agent:<Answer >
···
Figure15:Prompt for RISE : We follow the standard pipeline of math problem solving, prompt the LLM
to solve the problem and retry untill exceeds the maximum number of turns
33
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D.5. One-shot Example
RISE One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we subtract the total
number of students taking only math, only physics, and both from the total number of students in
the drama club. This gives us $60 - 16 - 7 - 20 = ∖boxed{17}$ students taking neither.
Answer:∖boxed{17}
Figure16:One-shot Example : Demonstrates how to solve a math problem step-by-step and the expected
answer format.
34
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Self-Refine One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we add the number
of students taking only math and only physics, then subtract this sum from the total number of
students in the drama club. This gives us $60 - (16 + 7) = ∖boxed{37}$ students taking neither.
Answer:∖boxed{37}
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent: Step 1: Correct. We need to find the number of students taking neither math nor physics.
Step 2: Correct. The given information is accurately stated.
Step 3: Correct. The calculation of students taking only math is correct.
Step 4: Correct. The calculation of students taking only physics is correct.
Step 5: Incorrect. The solution adds the number of students taking only math and only physics,
but this does not account for the students taking both subjects. By subtracting this sum from
thetotalnumberofstudents,thesolutiondouble-countsthestudentswhotakebothmathandphysics.
User: Now, rewrite the solution in the required format:
Agent:<Same as 16 >
Figure17:One-shot Example : Demonstrates the process of self-critique and error correction based on
the self-critique.
35 | Appendix D.4). The reward function is a sparse binary indicator of answer
correctness at a given state 𝑠,𝑟([𝑥𝑖,···],𝑎) = 1if and only if 𝑎=𝑦*
𝑖and is obtained from an answer
checking function. This construction from dataset 𝒟to MDPℳis shown below:
𝒟={(𝑥𝑖,𝑦*
𝑖)} → ℳ :𝜌(𝑠0) =Unif(𝑥1,𝑥2,···,𝑥𝑁) (4.1)
𝑃(𝑠′|𝑠,𝑎) =𝛿(︀
𝑠′=concat [𝑠,𝑎,𝑓])︀
(4.2)
𝑟(𝑠,𝑎) =1(𝑎=𝑦*
𝑖if𝑥𝑖∈𝑠). (4.3)
4.2. Learning in the Multi-Turn MDP
With the MDP construction in place, the next step involves training a model to improve itself over the
course of a rollout. We subscribe to an offline approach to learning that we describe in the following.
Step 1: Data collection for self-improvement. To ensure that rollout data from this multi-turn MDP is
useful for teaching the model how to self-improve, it must satisfy a few desiderata: (1)it must illustrate
the mistakes that the learner is likely to make and showcase how to improve upon them in the next
attempt, (2)the data must illustrate responses that are relevant to the model given the problem and
previous attempts in context, and (3)it must not contain any rollout that degrades in a subsequent turn.
Our data collection strategy (Figure 2, Right) satisfies these desiderata.
In a given round 𝑘, for a given problem 𝑥𝑖, we unroll the currentmodel 𝜋𝜃𝑘(·|·)to produce multiple
sequential attempts, denoted by 𝑦𝑖
𝑡∼𝜋𝜃𝑘(·|𝑠𝑖
𝑡). In problems, where external input (e.g., compiler
feedback) is available, we also observe a variable-length, natural language external input, 𝑓𝑖
𝑡(e.g., in
mathproblemsweaskthemodeltocorrectitself). Wealsoobserveascalarrewardvalue 𝑟(𝑠𝑖
𝑡,𝑦𝑖
𝑡),denoted
as𝑟𝑖
𝑡in short. Let us denote this dataset of “on-policy” model rollouts as 𝒟on-policy :={(𝑠𝑖
𝑡,𝑦𝑖
𝑡, 𝑓𝑖
𝑡, 𝑟𝑖
𝑡)𝑇
𝑡=1}.
For each time-step, we construct an improved version of the response 𝑦𝑖
𝑡that we will denote by ˜𝑦𝑖
𝑡. We
also record the reward score associated with this improved response as 𝑟(𝑠𝑖
𝑡,˜𝑦𝑖
𝑡), or˜𝑟𝑖
𝑡in short. To obtain
an improved version of a response 𝑦𝑖
𝑡, we can employ several strategies. Perhaps the most straightforward
approach is to query an off-the-shelf more capable model to provide a correct response given the prompt
𝑥𝑖, the previous response 𝑦𝑖
𝑡, and an optional external feedback 𝑓𝑖
𝑡. We refer to this as the distillation
variant of our approach, since it uses a strong “teacher” model to guide self-improvement (note that
this is different from the classic notion of knowledge distillation, and we will in fact show results in
Section 6.1 that will help understand the differences).
˜𝒟on-policy + distill :={︁{︀(︀
𝑠𝑖
𝑡,˜𝑦𝑖
𝑡, 𝑓𝑖
𝑡,˜𝑟𝑖
𝑡)︀}︀𝑇
𝑡=1}︁|𝒟|
𝑖=1. (4.4)
5
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
The second variant of our approach, which alleviates the need for a teacher model, involves constructing
an improved response by sampling multiple times from the learner itself. We refer to this approach as the
self-distillation variant. Concretely, for each state in the dataset, 𝑠𝑖
𝑡∈𝒟on-policy, we sample 𝑁responses
˜𝑦𝑖
𝑡[0],˜𝑦𝑖
𝑡[1],···,˜𝑦𝑖
𝑡[𝑁]∼𝜋𝜃(·|𝑠𝑖
𝑡), and use the best response from these 𝑁candidates (as measured by
the associated reward values ˜𝑟𝑖
𝑡[0],···,˜𝑟𝑖
𝑡[𝑁]) to relabel the model response at the next step 𝑡+ 1in an
improvement trajectory. Formally, say ˜𝑦𝑖
𝑡[𝑚] = arg max 𝑗∈[𝑁]𝑟(𝑠𝑖,˜𝑦𝑖
𝑡[𝑗]), then we label the responses in
the dataset𝒟on-policyat step 𝑡+ 1with the improved response and its associated reward value ˜𝑟𝑖
𝑡[𝑚]:
˜𝒟on-policy + self-distillation :={︁{︀(︀
𝑠𝑖
𝑡+1,˜𝑦𝑖
𝑡[𝑚], 𝑓𝑖
𝑡+1,˜𝑟𝑖
𝑡[𝑚])︀}︀𝑇−1
𝑡=0}︁|𝒟|
𝑖=1. (4.5)
Step 2: Policy improvement. With the aforementioned data construction schemes, we can now train a
model on these datasets. While in general, any offline RL approach can be used to train on these data,
in our experiments we adopt an approach based on weighted supervised learning [ 35] due to ease of
experimentation and its simplicity. In particular, we perform a weighted supervised regression, where
the weights are given by the exponential transformation of the reward values in ˜𝒟.
Reward-weighted RL: max
𝜃E𝑥𝑖∼˜𝒟[︃𝑇∑︁
𝑡=1log𝜋𝜃(˜𝑦𝑖
𝑡|𝑠𝑖
𝑡)·exp(𝑟𝑡
𝑖/𝜏)]︃
, (4.6)
where 𝜏is a temperature parameter to further expand or narrow the difference between good and bad
actions. In our preliminary experiments, we found that Equation 4.6 can often induce a bias towards
increasing log likelihoods of responses where rewards are high, prioritizing updates on easy problems
where rewards are already high. To address this issue, we apply a slight modification to Equation 4.6
and center the exponentiated rewards around the mean value averaged across all attempts on a given
prompt, akin to advantage-weighted regression [ 34]. We find that the use of advantages in place of
rewards helps us avoid the “rich-gets-richer” phenomenon with easy problems.
4.3. Inference at Deployment Time
RISE can be run in two modes at inference time. Perhaps the most straightforward way to run the
policy 𝜋𝜃(·|·)trained by RISE is within a multi-turn rollout, where the model samples a new response
conditioned on the past context (i.e., state in the multi-turn MDP). This past context consists of the
external feedback 𝑝test
𝑖concerning the response 𝑦test
𝑖and the rollout terminates as soon as the current
response is judged to be correct according to the environment’s answer verification function. Put in other
words, we terminate the rollout as soon as the reward is equal to the reward for the oracle response:
𝑟(𝑥,𝑦test
𝑖) =𝑟(𝑥,𝑦*). This protocol invokes queries to the reward function after each turn in the rollout.
Since several reward function queries are performed, we refer to this approach as “with oracle” .
RISE can also be run in a mode that avoids the need to query the answer checker or the reward function
within a rollout. In this case, we run full-length rollouts by forcing the model to retry, ignoring the
correctness of the response. We then utilize a self-consistency mechanism [ 51] based on majority voting
to decide the candidate response at the end of each turn. Concretely, at the end of each turn 𝑗, we
identify the response by running a majority vote over all response candidates from the previous turns
(maj(︁
𝑦test
0,𝑦test
1,···,𝑦test
𝑗)︁
), including turn 𝑗. We call this “without oracle” . A schematic illustration of
these approach is shown in Figure 3. Most of our evaluations use no oracle.
6
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure3:RISE Inference. There are two ways to query the model trained via RISE upon inference: (1) with oracle ( Left):
each time the model improves its response, it is allowed to check its answer against an environment and terminate early as soon
as a correct answer is found; or (2) without oracle ( Right): we ask the model to sequentially revise its own responses k times,
and perform majority voting on all candidate outputs from different turns to obtain the final response.
4.4. Practical Algorithm and | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Implementation Details
A complete algorithmic pseudocode for each approach is shown in Appendix C. We trained 7B models via
RISE and found that these models often could not adhere to response style and instructions for improving
their responses when generating on-policy data. As a result, before running on-policy data collection, we
find it often useful to run an initial phase of supervised fine-tuning on in-domain, multi-turn rollouts
generated from a capable model to provide style and instruction-following information to the learner.
We call this the “knowledge boosting” stage. We then run on-policy rollouts starting from a boosted
model. In each iteration, we generate 1 trajectory for each unique problem. We then run fine-tuning,
with hyperparameters and details in Appendix D. For iterative fine-tuning, we find that starting from the
basemodel but training on data from all iterations thus far is more beneficial than continued fine-tuning
from the checkpoint obtained in the previous iteration.
5. When and Why is Self-Improvement Over Turns Possible?
A natural question to ask is why self-improvement with RISEeven possible. One might surmise that the
model may simply not have enough knowledge to correct its ownmistakes if it is unable to correctly
answer the problem in the first turn. Then, why is it possible to teach the model to correct its own
mistakes? In this section, we provide the reason why this kind of self-improvement is possible, supported
with empirical evidence to justify our hypotheses.
Iteratively teaching a model how to make updates on a given response can be crucial when representing
the target distribution 𝑝*(𝑦|𝑥)requires more capacity than what the model 𝜋𝜃affords by conditioning
on only the input prompt tokens. When the target distribution requires greater capacity, learning a
sequence of conditionals, 𝜋𝜃(𝑦𝑖+1|𝑥,𝑦0:𝑖)followed by marginalization is expected to induce a more
flexible marginal distribution over 𝑦𝑇given 𝑥. This hypothesis is akin to the difference between diffusion
models [ 42] and variational autoencoders (VAEs) [ 25] in image generation: iteratively fitting a sequence
of generative distributions over intermediate noisy inputs in a diffusion model gives rise to a more flexible
distribution [ 43] than monolithic variational auto-encoding, even though diffusion models still utilize
7
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure4:The probability of the true answer given the
prompt. Observe that model trained with RISE has higher
probability for the true answer.
Figure5:The training perplexity (loss) of fitting only
the oracle answer or a sequence of answers. Observe that
fitting a sequence of answers (RISE) reduces the loss more
than fitting only the oracle answer (Classic).
an evidence lower-bound objective(ELBO). While the diffusion process utilizes hand-designed noise
schedules, RISE utilizes the base model itself to induce iterative improvements.
To verify if this hypothesis is true, we tracked the training un-weighted, negative log-likelihood loss (NLL)
values for the oracle response 𝑦*given the input prompt 𝑥marginalized over intermediate steps in a
multi-turn rollout, and compared it against the NLL values −log𝑝𝜃(𝑦*|𝑥)attained by directly attempting
to predict the final response in Figure 4 (labeled as “Classic”). Concretely, we sampled 256 prompts 𝑥
and their oracle responses 𝑦*and computed the average −log𝑝𝜃(𝑦*|𝑥)across all 𝑥, along with a 95%
confidence interval for different checkpoints during training. We find that for any given number of epochs
(including fractional number of epochs on the x-axis), the NLL value is lower when conditioning on
multi-turn data that RISE generates in comparison with oracle responses to the prompts obtained from
an expert. This suggests that RISE is able to utilize the computation of tokens from previous turns to
model the target distribution. We also measure the average NLL loss on all samples through training,
sampled i.i.d. from the training dataset for RISE and classic fine-tuning and observe a similar trend: RISE
is able to reduce loss more than the standard approach, attaining lower perplexity values (Figure 5).
Of course, in problems that require “knowledge-based” question answering, it is not possible for the
model to produce any meaningful improvements because learning 𝑝*(𝑦|𝑥)is not bounded by insufficient
capacity of 𝜋𝜃(𝑦|𝑥), but is rather unable to match 𝑝*due to the absence of features that are critical
to learn the correct mapping from 𝑥to𝑦. We expect that training with RISE would only incentivize
hallucinations in this case [ 24], since more input tokens appearing from previous attempts would only
provide easier ways to pick up on spurious correlations. However, this is not the failure mode on reasoning
problems [ 27], where maj@K rates at turn 1 tend to be higher than pass@1 as we find in our experiments
(indicating that performance can be improved by sampling the model itself). In fact, in Figure 6 we also
show that the sequential procedure learned by RISE can even solve a significant fraction of problems that
were unsolved by pass@B for much larger 𝐵in the first turn, indicating that it learns to index into the
pre-trained knowledge of the model in a different manner as opposed to simply translating the pass@K
performance into the pass@1 performance of the model, that majority of single-turn approaches are
believed to be doing.
8
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure6:Fraction of problems unsolved by pass@B at the first turn that sequential 5-turn sampling from RISE solves,
where 𝐵= 5×𝑘(𝑘is the x-axis). RISE can solve several challenging problems that sampling at the first turn with much larger
budgets cannot solve.
6. Experimental Evaluation
The goal of our experiments is to demonstrate the efficacy of RISE in instilling language models with the
ability to self-improve their responses over turns. Our experiments answer the following questions: (1)
How effectively can RISE improve performance over multiple sequential attempts (i.e., turns) at a given
prompt?; (2)Does the performance of RISE improve with more rounds of iterative training?; (3)Does
the self-improvement strategy induced by RISE generalize to novel problems that are out of the training
domain? and finally; (4)What is the best data composition for training RISE? To this end, we compare
RISE to other prior and baseline approaches, and perform ablations on GSM8K [11] and MATH [18].
Baselines, comparisons, and evaluation. We compare RISE to several prior methods that attempt
to induce similar self-improvement capabilities: (a) self-refine [21,31] that prompts a base model to
critique and revise its mistakes; (b) GloRE [17], which trains a separate reward model to locate errors
and a refinement model to improve responses of a base LLM; and (c) self-consistency [51], which runs
majority voting on multiple responses from the first turn as a baseline to compare to our sequential
strategy. We tried to construct fair comparisons between RISE and these methods by using a similar-sized
model [ 23,58], but differences in the base model, training data, and evaluation setups still prohibits
us from performing an apples-to-apples comparison in some cases. Nonetheless, we can still hope to
understand the ballpark of improvement by contextualizing our results with these prior works. We also
compare to V-STaR [19], but since this is not an fair comparison, we defer it to Appendix B.
We evaluate RISE in both modes at inference time: with and without an oracle (Section 4.3) at the end
of five turns. Concretely, these metrics are defined as follows:
•with oracle, “p1@t5” : this run terminates the rollout as soon as the response is correct. In other
words, this metric allows queries to the final answer verifier at the end of each turn.
•withoutoracle,“m1@t5” : thisrundoesnotterminatetherolloutbeforefiveturns,andwecompute
the maj@1 performance on the candidates produced in each turn as detailed in Section 4.3.
We also compare maj@K performance at the first turn for all the models we train (“m1@t1”, “m5@t1”).
9
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9)68.6(+33.3)6.7 9.5 (+2.8) 18.4(+11.1)29.7(+22.4)
7B SoTA [58]
Eurus-7B-SFT 36.3 66.3 (+30.0)47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5)16.3(+4.0) 22.9(+10.6)
Self-Refine [31] →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Iteration 2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7B-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE [17] →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) Not studied in [17]
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
Table 1: RISE vs. other approaches (Self-Refine, GLoRE) and baselines. Observe that RISE attains the biggest performance
improvement (in brown) between 1-turn (m5@t1) and 5-turn (m1@t5) performance w/o an oracle on both GSM8K and MATH.
This performance gap is even larger when oracle early termination is allowed (p1@t5 w/ oracle). Self-Refine [ 31] degrades
performance across the board when used without an oracle, and attains minor performance improvements when used with an
oracle. GLoRE trains a separate refinement model, but still performs worse than RISE; more details about it are in Appendix B.
Using RISE on top of a better base model (Mistral-7B) is also effective (positive improvements with multiple turns), and note
the m1@t5 performance of Mistral-7B exceeds even state-of-the-art math models such as Eurus-7B-SFT [ 58]. Simply running
single-turn SFT on data utilized by RISE is not effective at inducing a self-improvement capability, implying that the algorithmic
design choices in RISE are crucial for performance. Color coding indicates numbers that can be compared to each other.
6.1. Does RISE improve performance over multiple turns compared to other approaches?
Main results. We present the comparisons in Table 1. First, note that RISE (“Iteration 1” and “Iteration
2”) boosts up the LLama2 base model’s five-turn performance by 15.1% and 17.7% respectively with
each iteration on GSM8K and 3.4% and 4.6% on MATH, w/o any oracle. Interestingly, we found using
prompting-only self-refine [ 31] largely degrades performance across the board, even with a strong
proprietary model, GPT-3.5. The strongest 7B base models, Mistral-7B and Eurus-7B-SFT [ 58], when
coupled with standard prompting, are only able to improve their performance, but only by 5.3% / 11.6%
and 0.9% / 4.0% respectively on GSM8K and MATH, which is significantly lower than our approach.
The performance of GLoRE improves only by 3.4% on GSM8K (over two turns), but this is still lower
than our approach, which improves by 6.3% in two turns and 13.4% in three turns (see Appendix B.1).
This indicates that RISE is effective in teaching models how to improve their own errors. To summarize,
training with RISE gives the largest performance improvement gains compared to other approaches both
with and without the use of an oracle, and these gains are transferred to other base models.
One might also hypothesize that the performance gains with RISE here are largely a result of utilizing
10
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE (Self)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 36.8 44.4 (+7.6) 39.5(+6.6) 48.7(+15.9)
Llama-3-8B 45.3 69.7 (+24.4) 52.5(+7.2) 61.0(+15.7)
+ Iteration 1 65.6 80.7 (+15.1) 73.8(+8.2) 81.2(+15.6)
Table 2: RISE with self-distillation on GSM8K. RISE is able to improve 5-turn maj@1 performance of the model with entirely
self-generated data and supervision, despite the fact that the base Mistral-7B model does not produce correct answers for
several problems.
queries to an off-the-shelf more capable model for providing supervision and not the algorithmic approach
for data collection and training. To address this hypothesis, we store all the data generated by RISE from
more capable models and train on this data via standard single-turn SFT (“ SFTonoracledata ). Since not
all of this data are guaranteed to be correct, we also run this experiment on only the correct responses in
these oracle data. Observe in Table 1 that this procedure does not still instill self-improvement capabilities,
largely preserving or degrading sequential (“ maj@1@turn5 ”) performance compared to simply sampling
one response in the first turn. This means that the algorithmic design of RISE is critical in enabling it to
learn self-improvement capabilities, as opposed to simply the use of expert supervision.
6.1.1. Can RISE Effectively Make Use of Mistakes and Correct Them?
One concern that arises from prior results on self-refinement or self-correction is whether the model
can truly correct itself over turns or whether the improvement comes from the effect of sampling more
answers and picking the best one. In Table 1, we see that sequentially improving responses via RISE
(“maj@1@turn5 ”) outperforms sampling 5 responses in parallel at the first turn and applying a majority
vote on them (“ maj@5@turn1 ”). Please note that this comparison utilizes an equal number of samples,
with the only difference being that these samples are drawn in parallel at the first turn in one case and
sequentially at the end of five turns in the other. Comparing maj@5 performance at the end of 1 turn
and 5 turns, we observe a consistent 4% to 8% improvement on GSM8K and an 6.5% improvement
on MATH (with Mistral-7B model). This means that RISE can imbue models with a self-improvement
ability, while running parallel sampling alone on any model cannot endow the same ability. Even the
maj@5@turn1 performance of standard single-turn SFT on the data used by RISE is substantially worse
than the sequential maj@1@turn5 performance of RISE, implying that the algorithmic protocol of RISE
plays a critical underlying role. Finally, we also remark that in Figure 6, we showed that the sequential
procedure learned by RISE over five turns could solve a significant fraction of problems that were unsolved
by pass@B for much larger values of 𝐵≫5in the first turn, implying that sequential RISE can actually
tackle prompts that were not solvable by simply sampling more responses in the first turn.
One might also speculate if these improvements in sequential improvement ability largely come at a cost
of reduced improvements in first turn performance. In addition, we also observe that running multiple
iterations of RISE still preserves the first turn performance while improving the 5-turn performance.
6.1.2. How Does the Base Model Affect RISE?
The performance of RISE with Llama2-7B on an absolute scale is lower than the best models specifically
fine-tuned on math data (e.g., Eurus-7B-SFT or Mistral-7B). However, we find that RISE is still effective
on top of Mistral-7B base model. In fact, our performance at the end of five turns outperforms one of the
best 7B SFT models, customized to math reasoning . Compare the m1@t5 performance of Eurus-7B-SFT
and Mistral-7B in RISE (ours), to find that Mistral-7B + RISE outperforms Eurus-7B-SFT.
11
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISEw/o oracle w/ oracle
m1@t1→m1@t5 p1@t5
GSM8K
Llama2 Base 10.5 11.1 (+0.6) 13.9(+3.4)
Iteration 1 RISE Model trained on MATH 19.3 32.6 (+13.3) 48.4(+29.1)
MATH
Llama2 Base 1.9 1.4 (-0.5) 2.3(+0.4)
Iteration 1 RISE Model trained on GSM8K 4.3 4.4 (+0.1) 12.1(+7.8)
SVAMP
Llama2 Base 29.2 30.5 (+1.3) 34.0(+4.8)
Iteration 1 RISE Model trained on MATH 30.1 31.4 (+1.2) 45.9(+15.8)
Iteration 1 RISE Model trained on GSM8K 42.2 50.0 (+7.8) 63.6(+21.4)
Table 3: Out-of-distribution generalization of RISE. We evaluate model fine-tuned on MATH on the GSM8K test set; model
fine-tuned GSM8K on MATH; and the model fine-tuned on a mixture of GSM8K and MATH on the SVAMP data. Observe even
though we train on OOD prompts, RISE can still improve sequential performance.
6.1.3. Self-Distillation Version of RISE
We also compare the performance of RISE with entirely self-generated data and supervision (Equation 4.4,
𝑁= 16) after one iteration directly on top of more capable models: Mistral-7B and Llama-3-8B on
GSM8K in Table 2, without any knowledge boosting phase. We find that this variant also improves the
5-turn performance of the base model compared to the first turn: compare “m1@t5” vs “m1@t1” for both
the models Llama-3-8B and Mistral-7B, where RISE boosts the sequential self-improvement performance
by more than 1% compared to turn 1 performance w/o any oracle.
Of course, we also note that this version of RISE does not outperform the “m5@t1” performance of the
fine-tuned model. We expect this to be largely a function of one single iteration of training. Since the
self-distillation version of RISE utilizes best-of-N sampling against the same model to produce supervision
for self-improvement, RISE would first have to match the performance of best-of-N sampling before it can
start to improve over it via reward maximization. Due to the significant gap between the base model’s
m5@t1 and m1@t5 performance, we expect that this will take quite a few iterations or a fully online
RL algorithm. We did not have computational resources and infrastructure to run multiple iterations,
but this is an interesting avenue for future work. In this self-distillation setting, we could also divide the
computation between sequential and parallel sampling strategies to get the best results at the end of five
turns. Nonetheless, this result shows that even by training on self-generated samples, RISE can actually
amplify the sequential sampling performance of the base model.
6.2. Does the Performance of RISE Improve with Iterative Training?
Next, we attempt to understand if RISE improves with multiple rounds of training on on-policy data. As
shown in Tables 1 and 2, the performance of RISE improves from iteration to iteration constantly. The
5-turn performance of RISE, both with and without an oracle, exhibits a clear improvement with more
rounds. This implies that iterative self-training procedures of the form of STaR [ 61] can also be combined
with RISE to train models for self-improvement. This also perhaps serves as a strong hint towards the
potential utility of full online reinforcement learning (RL) techniques.
6.3. Does RISE Also Improve Sequential Performance on Out-of-Distribution Prompts?
In Table 3, our aim is to evaluate the robustness of the strategy induced by RISE on new, unseen prompts.
Specifically, we compare the performance of the RISE model trained with a dataset on evaluation prompts
12
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
from another dataset. Note in Table 3, these datasets include MATH, GSM8K, and SVAMP. Generally,
we observe that the model trained on one dataset is still able to improve the base model’s performance
on another dataset over the course of sequential five turns. More concretely, while the base Llama2
model largely degrades its turn 1 performance over turn 5 performance, model’s trained with RISE
enable a positive performance improvement on these out-of-distribution prompts. This means that even
though these models have not seen queries similar to the evaluation dataset, simply training with RISE
onsomekind of mathematical prompts still boosts the efficacy of the self-improvement strategy on a new
distribution of test prompts. This finding suggests that RISE is capable of instilling self-improvement
procedures that can generalize beyond the distribution of prompts in the fine-tuning data.
6.4. What Data Compositions and Data Quantity are Crucial for RISE?
We now study how different data compositions affect the performance of RISE with the goal of answering
questions such as should we collect on-policy error correction data like DAgger [ 36] or should we bias
towards high-quality off-policy data? . To understand the utility of different data compositions, we enlist
the three aspects RISE: (a)the use of multi-turn rollout data for fine-tuning, (b)the use of unsuccessful /
suboptimal rollouts via weighted supervised fine-tuning compared to naïve supervised learning, which
only utilizes successful rollouts for fine-tuning; and (c)the use of on-policy rollouts and self-generated
or oracle data. We will now perform controlled experiments to understand the effect of each of these
factors on the overall performance of RISE.
Figure7:Left: The importance of multi-turn interaction history and weighted objectives for training RISE. Note that
training with multi-turn data leads to better self-improvement performance at the end of 5 turns, than one-turn data obtained
from the original dataset with oracle answers from another model; also observe that using a weighted objective performs better.
Right: The importance of using all rollouts for learning , instead of only successful rollouts or only successful responses in the
data. Using all data performs best in our results.
(a) Data composition for fine-tuning. We first study the necessity of using the interaction of error
correction history for training RISE in Figure 7 (Left). We compare two approaches: model trained with
oracle answers shown right after the query (“1-turn”) and oracle answers shown after intermediate failed
attempts (“Multi-turn”) in Figure 7 (Left). Even though the latter trains on intermediate responses that
may not always be correct, it attains a higher performance than simply training on the correct response
for a given prompt. This highlights the importance of training on contexts that include a multi-turn
interaction history depicting mistakes from the learner to improve self-improvement capabilities.
(b) Weighted supervised learning vs unweighted supervised learning. Next, we investigate the effect
of reward-weighted RL on multi-turn data in RISE as opposed to simply imitating filtered successful data.
13
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
We find that using all the data leads to improved performance over simply filtering good datain Figure 7
(Right), which reduces sample size. In Figure 7 (Left), we find that reward-weighted training improves
performance on later turns, allowing us to better leverage all the sub-optimal data.
(c) On-policy vs off-policy data; self-generated vs. expert data. RISE runs on-policy rollouts and seeks
improvements on responses that the learner produces. As shown in Figure 8 (Left), a “DAgger [ 36]”-style
approach that seeks improvements on responses appearing in on-policy rollouts improves performance
(green/orange) compared to using expert data alone (blue/pink). Conceptually, this addresses the
train-test mismatch between the distribution of context tokens, enabling imitation learning methods to
now target the correct distribution. In addition, recent work [ 24] has shown that LLMs often memorize
“unfamiliar” examples generated by oracle models; by training on on-policy rollouts, we should be able to
eliminate any such potential issues. Thus, while the model trained via offline imitation is able to reduce
loss, these improvements do not generalize to new problems.
Figure8:Left: The importance of data sources used for training. We study the performance of the iteration 1 of RISE on
GSM8K with different data sources. “Expert” refers to the use of an oracle model, “On-policy” corresponds to sampling from the
learner, and “Best-of-N” means using the best sample out of 𝑁from the learner (here 𝑁= 16).Right: Comparing RISE with
oracle error feedback (pass@1 @ turn k; solid lines) to parallel sampling of 5 responses at turn 1 (pass@k @ turn 1;
dashed lines) over number of turns 𝑘on the x-axis on GSM8K. Observe that sequential sampling with Iteration 1 and Iteration
2 RISE models consistently outperforms parallel sampling for all values of turn 𝑘; and the gap grows as the number of iterations
increases. In contrast, this trend is absent for base and SFT models.
6.5. Pass@K vs Sequential Sampling via RISE
We now study the performance of sequential sampling with oracle feedback in GSM8K, unlike relying on
majority voting as in Table 1. Specifically, we compare the performance of RISE with early termination of
evaluation rollouts against pass@5 (not maj@5) performance of the RISE model at the first turn (which
makes an equal number of queries to the ground-truth correctness indicator). Access to ground-truth
correctness indicator is expected to improve performance for both parallel and sequential sampling
unsurprisingly, but we see in Figure 8 (Right) that RISE is able to improve performance more beyond
simply sampling more samples at the first turn and computing pass@K, despite this strong assumption of
access to an oracle final answer verifier made by the parallel sampling approach.
We would expect parallel sampling via pass@K to be most performant when provided access to oracle
answer checking as the model can choose to simply sample 𝐾independent responses, if the base model
accuracy on this task is reasonable. Pass@K @ turn 1 also upper bounds the first turn accuracy of any
procedure that does not query the oracle (e.g., with verifiers, with majority voting, etc.). Hence, access
to oracle answer checking for each individual response presents the strongest result one couldexpect out
14
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
of parallel sampling, in one turn. On the other hand, sequential sampling produces correlated samples
and hence should, in principle, not be able to improve over parallel sampling, unlessthe model is unable
to use the additional tokens and computation provided by the feedback self-improvement prompt to
meaningfully correct itself. Since the sequential performance of the model is larger than the parallel
performance above, this means that RISE indeed does this successfully.
6.6. Error Analysis of RISE over Turns
Following the protocol of Huang et al. [21], in this section, we perform an error analysis of the improve-
ment performed by RISE (without any oracle feedback) to understand how the fraction of incorrect and
correct responses changes over turns, when no oracle is used for early termination. We demonstrate this
in the form of Venn diagrams in Figure 9. First note that there is a consistent increase in the portion
of problems that stay correct and a consistent decrease in the portion of problems that stay incorrect,
which means that the model is able to answer more and more problems as we increase the number
of turns. Second, there is a consistent decrease in the number of problems that change from being
correct to incorrect, which is often also not the case for strong proprietary LLMs such as GPT in Huang
et al.[21]. We also note that there is a decrease in the total number of incorrect problems that become
correct in the subsequent turn, but this is a direct consequence of a shrinkage in the size of the incorrect
response set as more problems become correct over turns. This indicates that one can induce “intrinsic”
self-improvement (per the terminology of Huang et al. [21]) via fine-tuning with RISE, even though no
external environment input is provided during evaluation.
Figure9:Change in the fraction of responses that transition their correctness values over the course of multi-turn
rollouts from RISE, w/o oracle. Observe that in general, the fraction of Correct →Correct responses increases; Incorrect →
Incorrect responses decreases; and the fraction of Correct →Incorrect responses also decreases, indicating that RISE (w/o any
oracle) is able to iteratively improve its responses.
Qualitative examples. We also inspect several examples from the GSM8K test set to qualitatively
understand the behavior of RISE over turns and observe different behavior patterns, that we show in
Appendix B.2. For instance, the trained model may choose to completely rewrite its previous response if
it is totally incorrect in order to get to the correct answer or make small edits if the previous response is
mostly correct. Another interesting pattern we note is that the model implicitly has the ability to locate
errors in previous responses and only refine the erroneous steps. Additionally, the model is tolerant of
noisy environmental feedback when there is no oracle-assisted early termination.
7. Discussion, Future Directions, and Limitations
We presented RISE, an approach for fine-tuning LLMs to be able to improve their own responses over
multiple turns sequentially. RISE prescribes an iterative RL recipe on top of on-policy rollout data, with
15
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
expert or self-generated supervision to steer self-improvement. RISE significantly improves the self-
improvement abilities of 7B models on reasoning tasks (GSM8K and MATH), attaining an improvement
over turns that previous work [ 21] has not observed in strong proprietary models. In addition, RISE
outperforms prior approaches that attempt to tackle similar problems of refinement and correction, while
being simpler in that it does not require running multiple models and works well with just one model.
Despite these good results, there are still many open questions and limitations. Due to computational
constraints, we were not able to perform more than two iterations of training with RISE, and no more
than one iteration when the supervision comes from the learner itself. Improving with self-generated
supervision will likely require more computation and more iterations, since it will be slower than when
using an off-the-shelf expert model. RISE requires running manual iterations and hence, a more “online”
variant of RISE is likely the solution in the long run, especially when we wish to scale on-policy learning
in a data-efficient manner. Additionally, while our work fine-tunes models on one task at a time, it will
be certainly interesting to include data from the protocols specified by RISE into general instruction
tuning and post-training pipelines. Given the results that fine-tuning on data prescribed by RISE does not
hurt the first-turn performance of any model we trained, we hypothesize that adding this sort of data in
generalinstruction-tuningpipelinesshouldnothurteither,whileenablingthesequentialself-improvement
capability that is largely absent from models today.
Acknowledgements
This work was done at CMU. We thank Fahim Tajwar, Abitha Thankaraj, Amrith Setlur, and Charlie Snell
for their feedback and informative discussions. This work was supported by ONR under N000142412206,
OpenAI superalignment fast grants, and used the Delta system and JetStream2 [ 16] at the National
Center for Supercomputing Applications through CIS240249 and CIS230278, supported by the National
Science Foundation. We thank OpenAI for providing GPT-4 credits for academic use.
References
[1]Rishabh Agarwal, Nino Vieillard, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
Gkd: Generalized knowledge distillation for auto-regressive sequence models. arXiv preprint
arXiv:2306.13649 , 2023.
[2]Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna
Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. Constitutional ai: Harmlessness
from ai feedback. arXiv preprint arXiv:2212.08073 , 2022.
[3]Collin Burns, Pavel Izmailov, Jan Hendrik Kirchner, Bowen Baker, Leo Gao, Leopold Aschenbrenner,
Yining Chen, Adrien Ecoffet, Manas Joglekar, Jan Leike, Ilya Sutskever, and Jeff Wu. Weak-to-
strong generalization: Eliciting strong capabilities with weak supervision, 2023. URL https:
//arxiv.org/abs/2312.09390 .
[4]Jonathan D Chang, Wenhao Shan, Owen Oertell, Kianté Brantley, Dipendra Misra, Jason D Lee,
and Wen Sun. Dataset reset policy optimization for rlhf. arXiv preprint arXiv:2404.08495 , 2024.
[5]Yiannis Charalambous, Norbert Tihanyi, Ridhi Jain, Youcheng Sun, Mohamed Amine Ferrag, and
Lucas C Cordeiro. A new era in software security: Towards self-healing software via large language
models and formal verification. arXiv preprint arXiv:2305.14752 , 2023.
16
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[6]Baian Chen, Chang Shu, Ehsan Shareghi, Nigel Collier, Karthik Narasimhan, and Shunyu Yao.
Fireact: Toward language agent fine-tuning, 2023.
[7]Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models
to self-debug. arXiv preprint arXiv:2304.05128 , 2023.
[8]Zixiang Chen, Yihe Deng, Huizhuo Yuan, Kaixuan Ji, and Quanquan Gu. Self-play fine-tuning
converts weak language models to strong language models. arXiv preprint arXiv:2401.01335 , 2024.
[9]Yew Ken Chia, Guizhen Chen, Luu Anh Tuan, Soujanya Poria, and Lidong Bing. Contrastive
chain-of-thought prompting. arXiv preprint arXiv:2311.09277 , 2023.
[10]KarlCobbe, ChristopherHesse, JacobHilton, andJohnSchulman. Leveragingproceduralgeneration
to benchmark reinforcement learning. arXiv preprint arXiv:1912.01588 , 2019.
[11]KarlCobbe,VineetKosaraju,MohammadBavarian,MarkChen,HeewooJun,LukaszKaiser,Matthias
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman.
Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168 , 2021.
[12]Yilun Du, Shuang Li, Antonio Torralba, Joshua B Tenenbaum, and Igor Mordatch. Improving factual-
ity and reasoning in language models through multiagent debate. arXiv preprint arXiv:2305.14325 ,
2023.
[13]Kanishk Gandhi, Denise Lee, Gabriel Grand, Muxin Liu, Winson Cheng, Archit Sharma, and Noah D
Goodman. Stream of search (sos): Learning to search in language. arXiv preprint arXiv:2404.03683 ,
2024.
[14]Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and
Graham Neubig. Pal: Program-aided language models. In International Conference on Machine
Learning , pages 10764–10799. PMLR, 2023.
[15]Zhibin Gou, Zhihong Shao, Yeyun Gong, Yelong Shen, Yujiu Yang, Nan Duan, and Weizhu Chen.
Critic: Large Language Models can Self-Correct with Tool-Interactive Critiquing. arXiv preprint
arXiv:2305.11738 , 2023.
[16]David Y. Hancock, Jeremy Fischer, John Michael Lowe, Winona Snapp-Childs, Marlon Pierce,
Suresh Marru, J. Eric Coulter, Matthew Vaughn, Brian Beck, Nirav Merchant, Edwin Skidmore,
and Gwen Jacobs. Jetstream2: Accelerating cloud computing via jetstream. In Practice and
Experience in Advanced Research Computing , PEARC ’21, New York, NY, USA, 2021. Association
for Computing Machinery. ISBN 9781450382922. doi: 10.1145/3437359.3465565. URL https:
//doi.org/10.1145/3437359.3465565 .
[17]Alex Havrilla, Sharath Raparthy, Christoforus Nalmpantis, Jane Dwivedi-Yu, Maksym Zhuravinskyi,
Eric Hambro, and Roberta Railneau. Glore: When, where, and how to improve llm reasoning via
global and local refinements. arXiv preprint arXiv:2402.10963 , 2024.
[18]Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song,
and Jacob Steinhardt. Measuring mathematical problem solving with the math dataset. NeurIPS ,
2021.
17
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[19]Arian Hosseini, Xingdi Yuan, Nikolay Malkin, Aaron Courville, Alessandro Sordoni, and Rishabh
Agarwal. V-star: Training verifiers for self-taught reasoners. arXiv preprint arXiv:2402.06457 , 2024.
[20]Dong Huang, Qingwen Bu, Jie M Zhang, Michael Luck, and Heming Cui. Agentcoder: Multi-agent-
based code generation with iterative testing and optimisation. arXiv preprint arXiv:2312.13010 ,
2023.
[21]Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Wei Yu, Xinying Song,
and Denny Zhou. Large language models cannot self-correct reasoning yet. arXiv preprint
arXiv:2310.01798 , 2023.
[22]Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot
planners: Extracting actionable knowledge for embodied agents. In International Conference on
Machine Learning , pages 9118–9147. PMLR, 2022.
[23]Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot,
Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, et al.
Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[24]Katie Kang, Eric Wallace, Claire Tomlin, Aviral Kumar, and Sergey Levine. Unfamiliar finetuning
examples control how language models hallucinate, 2024.
[25]Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2022. URL https://
arxiv.org/abs/1312.6114 .
[26]Lucas Lehnert, Sainbayar Sukhbaatar, Paul Mcvay, Michael Rabbat, and Yuandong Tian. Be-
yond a*: Better planning with transformers via search dynamics bootstrapping. arXiv preprint
arXiv:2402.14083 , 2024.
[27]Chen Li, Weiqi Wang, Jingcheng Hu, Yixuan Wei, Nanning Zheng, Han Hu, Zheng Zhang, and
HouwenPeng. Common7blanguagemodelsalreadypossessstrongmathcapabilities. arXivpreprint
arXiv:2403.04706 , 2024.
[28]Hunter Lightman, Vineet Kosaraju, Yura Burda, Harri Edwards, Bowen Baker, Teddy Lee, Jan
Leike, John Schulman, Ilya Sutskever, and Karl Cobbe. Let’s verify step by step. arXiv preprint
arXiv:2305.20050 , 2023.
[29]XiaoLiu, HaoYu, HanchenZhang, YifanXu, XuanyuLei, HanyuLai, YuGu, HangliangDing, Kaiwen
Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688 ,
2023.
[30]HaipengLuo,QingfengSun,CanXu,PuZhao,JianguangLou,ChongyangTao,XiuboGeng,Qingwei
Lin, Shifeng Chen, and Dongmei Zhang. Wizardmath: Empowering mathematical reasoning for
large language models via reinforced evol-instruct. arXiv preprint arXiv:2308.09583 , 2023.
[31]Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri
Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with
self-feedback. arXiv preprint arXiv:2303.17651 , 2023.
18
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[32]Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and
Caiming Xiong. CodeGen: An Open Large Language Model for Code with Multi-Turn Program
Synthesis. ICLR, 2023.
[33]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David
Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. Show your work:
Scratchpads for intermediate computation with language models. arXiv preprint arXiv:2112.00114 ,
2021.
[34]Xue Bin Peng, Aviral Kumar, Grace Zhang, and Sergey Levine. Advantage-weighted regression:
Simple and scalable off-policy reinforcement learning. arXiv preprint arXiv:1910.00177 , 2019.
[35]JanPetersandStefanSchaal. Reinforcementlearningbyreward-weightedregressionforoperational
spacecontrol. In Proceedingsofthe24thinternationalconferenceonMachinelearning ,pages745–750.
ACM, 2007.
[36]StephaneRoss,GeoffreyGordon,andDrewBagnell. Areductionofimitationlearningandstructured
prediction to no-regret online learning. In Geoffrey Gordon, David Dunson, and Miroslav Dudík,
editors, Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics ,
volume 15 of Proceedings of Machine Learning Research , pages 627–635, Fort Lauderdale, FL, USA,
11–13 Apr 2011. PMLR. URL http://proceedings.mlr.press/v15/ross11a.html .
[37]Corby Rosset, Ching-An Cheng, Arindam Mitra, Michael Santacroce, Ahmed Awadallah, and
Tengyang Xie. Direct nash optimization: Teaching language models to self-improve with general
preferences. arXiv preprint arXiv:2404.03715 , 2024.
[38]Swarnadeep Saha, Omer Levy, Asli Celikyilmaz, Mohit Bansal, Jason Weston, and Xian Li.
Branch-solve-merge improves large language model evaluation and generation. arXiv preprint
arXiv:2310.15123 , 2023.
[39]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettlemoyer,
Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use
tools.arXiv preprint arXiv:2302.04761 , 2023.
[40]Noah Shinn, Beck Labash, and Ashwin Gopinath. Reflexion: an autonomous agent with dynamic
memory and self-reflection. arXiv preprint arXiv:2303.11366 , 2023.
[41]Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, and Sergey Levine. Offline rl for natural
language generation with implicit language q learning. arXiv preprint arXiv:2206.11871 , 2022.
[42]JaschaSohl-Dickstein,EricA.Weiss,NiruMaheswaranathan,andSuryaGanguli. Deepunsupervised
learning using nonequilibrium thermodynamics, 2015. URL https://arxiv.org/abs/1503.
03585.
[43]Yang Song and Diederik P. Kingma. How to train your energy-based models, 2021. URL https:
//arxiv.org/abs/2101.03288 .
[44]Liting Sun, Cheng Peng, Wei Zhan, and Masayoshi Tomizuka. A fast integrated planning and
control framework for autonomous driving via imitation learning. In Dynamic Systems and Control
Conference , volume 51913, page V003T37A012. American Society of Mechanical Engineers, 2018.
19
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[45]Gokul Swamy, Sanjiban Choudhury, J. Andrew Bagnell, and Zhiwei Steven Wu. Inverse reinforce-
ment learning without reinforcement learning, 2024. URL https://arxiv.org/abs/2303.
14623.
[46]Shubham Toshniwal, Ivan Moshkov, Sean Narenthiran, Daria Gitman, Fei Jia, and Igor Gitman.
Openmathinstruct-1: A1.8millionmathinstructiontuningdataset. arXivpreprintarXiv:2402.10176 ,
2024.
[47]Jonathan Uesato, Nate Kushman, Ramana Kumar, Francis Song, Noah Siegel, Lisa Wang, Antonia
Creswell, Geoffrey Irving, and Irina Higgins. Solving math word problems with process-and
outcome-based feedback. arXiv preprint arXiv:2211.14275 , 2022.
[48]Boshi Wang, Sewon Min, Xiang Deng, Jiaming Shen, You Wu, Luke Zettlemoyer, and Huan Sun.
Towards understanding chain-of-thought prompting: An empirical study of what matters. arXiv
preprint arXiv:2212.10001 , 2022.
[49]Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and
Anima Anandkumar. Voyager: An open-ended embodied agent with large language models. arXiv
preprint arXiv: Arxiv-2305.16291 , 2023.
[50]Peiyi Wang, Lei Li, Zhihong Shao, RX Xu, Damai Dai, Yifei Li, Deli Chen, Y Wu, and Zhifang
Sui. Math-shepherd: Verify and reinforce llms step-by-step without human annotations. CoRR,
abs/2312.08935 , 2023.
[51]XuezhiWang,JasonWei,DaleSchuurmans,QuocLe,EdChi,SharanNarang,AakankshaChowdhery,
and Denny Zhou. Self-consistency improves chain of thought reasoning in language models. arXiv
preprint arXiv:2203.11171 , 2022.
[52]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny
Zhou, et al. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS ,
2022.
[53]Sean Welleck, Ximing Lu, Peter West, Faeze Brahman, Tianxiao Shen, Daniel Khashabi, and Yejin
Choi. Generating sequences by learning to self-correct. In The Eleventh International Conference on
Learning Representations , 2023. URL https://openreview.net/forum?id=hH36JeQZDaO .
[54]Hui Yang, Sifu Yue, and Yunzhong He. Auto-gpt for online decision making: Benchmarks and
additional opinions. arXiv preprint arXiv:2306.02224 , 2023.
[55]Kaiyu Yang, Aidan M Swope, Alex Gu, Rahul Chalamala, Peiyang Song, Shixing Yu, Saad Godil,
Ryan Prenger, and Anima Anandkumar. LeanDojo: Theorem Proving with Retrieval-Augmented
Language Models. arXiv preprint arXiv:2306.15626 , 2023.
[56]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao.
React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629 ,
2022.
[57]LonghuiYu, WeisenJiang, HanShi, JinchengYu, ZhengyingLiu, YuZhang, JamesTKwok, Zhenguo
Li, Adrian Weller, and Weiyang Liu. Metamath: Bootstrap your own mathematical questions for
large language models. arXiv preprint arXiv:2309.12284 , 2023.
20
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
[58]Lifan Yuan, Ganqu Cui, Hanbin Wang, Ning Ding, Xingyao Wang, Jia Deng, Boji Shan, Huimin
Chen, Ruobing Xie, Yankai Lin, et al. Advancing llm reasoning generalists with preference trees.
arXiv preprint arXiv:2404.02078 , 2024.
[59] Weizhe Yuan, Richard Yuanzhe Pang, Kyunghyun Cho, Sainbayar Sukhbaatar, Jing Xu, and Jason
Weston. Self-rewarding language models. arXiv preprint arXiv:2401.10020 , 2024.
[60]Xiang Yue, Xingwei Qu, Ge Zhang, Yao Fu, Wenhao Huang, Huan Sun, Yu Su, and Wenhu Chen.
Mammoth: Building math generalist models through hybrid instruction tuning. arXiv preprint
arXiv:2309.05653 , 2023.
[61]Eric Zelikman, Yuhuai Wu, Jesse Mu, and Noah Goodman. Star: Bootstrapping reasoning with
reasoning. Advances in Neural Information Processing Systems , 35:15476–15488, 2022.
[62]Aohan Zeng, Mingdao Liu, Rui Lu, Bowen Wang, Xiao Liu, Yuxiao Dong, and Jie Tang. Agenttuning:
Enabling generalized agent abilities for llms. arXiv preprint arXiv:2310.12823 , 2023.
[63]Tianjun Zhang, Xuezhi Wang, Denny Zhou, Dale Schuurmans, and Joseph E Gonzalez. Tempera:
Test-time prompting via reinforcement learning. arXiv preprint arXiv:2211.11890 , 2022.
[64]Tianjun Zhang, Aman Madaan, Luyu Gao, Steven Zheng, Swaroop Mishra, Yiming Yang, Niket
Tandon, and Uri Alon. In-context principle learning from mistakes. arXiv preprint arXiv:2402.05403 ,
2024.
[65]Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang, and Yu-Xiong Wang. Lan-
guage agent tree search unifies reasoning acting and planning in language models. arXiv preprint
arXiv:2310.04406 , 2023.
[66]Yifei Zhou, Andrea Zanette, Jiayi Pan, Sergey Levine, and Aviral Kumar. Archer: Training language
model agents via hierarchical multi-turn rl. arXiv preprint arXiv:2402.19446 , 2024.
21
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Appendices
A. Additional Ablations on Data Composition and Weak-to-Strong Generalization
A.1. Inclusion of Correct-to-Correct Data
Intuitively, self-improvement over turns is largely only possible when the model can learn to verify the
correctness of its previous response and decide to appropriately modify its response toward correctness.
Thus far, the RISE has only trained on data that showed how to convert incorrect responses to correct
responses but never illustrated how the model could act on correct responses. To understand if perfor-
mance can be boosted by also illustrating examples of how the model could act on correct responses, we
ran a number of ablations. We took the RISE data generated during Iteration 1 of training on GSM8K
with Llama2-7B and modified the multi-turn rollouts to create several cases. First, we duplicated the
correct response appearing at the end of every successful multi-turn rollout and trained for one extra turn.
This should teach the model that correct responses should not be modified, unlike incorrect responses
appearing in previous turns in the rollout. Second, we also ran a variant in which the correct response
appearing at the end of every successful rollout is followed by a different correct response. This variant
should teach the model that if it chooses to modify a correct response, it must still produce another
correct response.
As shown in Table 4, all methods improved performance over the base model, though only appending
with a successful rollout with a novel correct response leads to best performance. The default design of
RISE in the main paper attains a close second position, and repeating a correct response at the end of a
successful rollout largely reduces performance. We suspect that the poor performance of repeating the
same correct response is largely a result of inducing spurious correlations due to data duplication.
RISE (Llama2)w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0)
+RISE (default) 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+Repeating a correct response 34.2 48.9 (+14.6) 46.2(+12.6) 57.7(+23.5)
+Appending a different correct response 33.1 49.3 (+16.2) 51.1(+18.0) 64.9(+31.8)
Table 4: Comparison of model performance on GSM8K with different mechanisms of adding correct-to-correct data in
RISE.Values in parentheses indicate improvement over m1@t1, note that appending a successful rollout with a a novel correct
response leads to the highest performance gains.
To further investigate self-improvement capabilities, we analyzed the percentage of correct responses
changing to incorrect responses in consecutive turns (T 𝑖to T𝑖+ 1), as illustrated in Figure 10. Generally, a
decreasing trend suggests better self-improvement, while lower absolute values indicate better resistance
to noisy feedback. The results reveal unexpected patterns across configurations. The Boost configuration
shows the poorest performance, with the highest overall percentages and an increase from turn 4 to
5, suggesting that it struggles to consistently maintain correct responses. Repeating a correct response
shows the lowest initial percentage (6.3%) but increases from turn 3 onward, indicating potential issues
in extended interactions. Both Default RISE and appending a different correct response demonstrate a
favorable trend, steadily decreasing from 12.3% to 3.9% and from 9.8% to 3.3%, respectively, suggesting
a good balance between maintaining correct responses and allowing improvements. These findings
provide nuanced insights into the stability and self-improvement capabilities of RISE and align with our
earlier observation of its superior performance in overall accuracy.
22
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Figure10:Percentage of correct responses in turn T 𝑖that change to being incorrect in turn T 𝑖+1.This figure illustrates
the percentage of correct responses that change to incorrect responses across consecutive turns (T 𝑖to T𝑖+1) for different model
configurations. A continuously decreasing trend suggests better self-improvement performance.
A.2. Weak-to-Strong Generalization: RISE on Weak Model Data Improves Strong Models
In this section, we compare the performance of Llama2 and Mistral-7B with RISE in the weak-to-strong
setting[ 3]. Concretely,weareinterestedinusingdatageneratedviaRISEwithaweakmodel(Llama2-7B)
to train a strong model (Mistral-7B). Our analysis reveals intriguing insights into the transferability of
RISE-generated data across models of different capabilities.
RISEw/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5
Llama2-7B 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4)
+ Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3)
+ Iteration 1 (Mistral-7B) 27.1 40.1 (+13.0) 45.2(+18.1) 59.1(+32.0)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3)
+ Iteration 1 (Llama2-7B) 38.2 55.4 (+17.2) 62.7(+24.5) 73.5(+35.3)
Table 5: Weak-to-strong generalization on GSM8K. Comparing performance of RISE when training on rollouts generated
by Llama2-7B vs Mistral-7B. Note that training the Mistral-7B model on rollouts generated by the weaker Llama2-7B with
RISE improves performance compared to using data generated by the Mistral-7B model itself. However, the reverse is not true:
training the Llama2 model on Mistral’s mistakes leads to worse performance, likely because errors from the Mistral-7B model
are harder to comprehend for a worse base model. All values are in % accuracy, and values in parentheses indicate improvement
over m1@t1.
As shown in Table 5, we find that Mistral-7B + Iteration 1 data generated from Llama2 outperforms
training the Llama2-7B model itself on these data (i.e., Llama2-7B + Iteration1) on all the metrics
reported with particularly significant improvements in multi-turn reasoning (m1@t5). In fact, training
on multi-turn rollouts from Llama2-7B also outperforms training on on-policy Mistral-7B rollouts as well.
Interestingly, we observed that training Llama2-7B on multi-turn rollouts from Mistral-7B performs worse
than training on on-policy Llama2-7B rollouts, suggesting that Llama2-7B, despite its lower absolute
performance, demonstrates more informative mistakes that can be leveraged to better boost the self-
improvement capability. This phenomenon underscores the importance of the quality and nature of
errors in the training data, rather than just the overall performance of the model that generates them.
These findings collectively suggest that the data generated from a weaker Llama2 model can still be used
to induce a self-improvement capability in a stronger model, although the reverse is not true (as is also
evident from the fact that using GPT-3.5 rollouts in the boosting phase for training does not improve
performance for any model in Table 1). We suspect that this is becaue the reverse poses a much harder
23
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
learning problem since a weak model need to internalize the mistakes of a stronger model, resulting in
hallucinations and memorization [ 24]. Note that training on these data does not degrade single-turn
performance either. This hints at an added benefit of training with RISE: weak-to-strong generalization,
which can be quite useful in practice when rolling out stronger models is expensive.
B. Additional Results
B.1. Complete Comparisons and Discussion: Extended Version of Table 1
We provide an extended version of Table 1, with a clear explanation of how we implement baselines and
a discussion of comparisons.
ApproachGSM8K [10] MATH[18]
w/o oracle w/ oracle w/o oracle w/ oracle
m1@t1→m5@t1→m1@t5 p1@t5 m1@t1→m5@t1→m1@t5 p1@t5
RISE (Ours)
Llama2 Base 10.5 22.8 (+12.3) 11.1(+0.6) 13.9(+3.4) 1.9 5.1 (+3.2) 1.4(-0.5) 2.3(+0.4)
+Boost 32.9 45.4 (+12.5) 39.2(+6.3) 55.5(+22.6) 5.5 6.8 (+1.3) 5.5(+0.0) 14.6(+9.1)
+Iteration 1 35.6 49.7 (+14.1) 50.7(+15.1) 63.9(+28.3) 6.3 8.8 (+2.5) 9.7(+3.4) 19.4(+13.1)
+Iteration 2 37.3 51.0 (+13.7) 55.0(+17.7) 68.4(+31.1) 5.8 10.4 (+4.6) 10.4(+4.6) 19.8(+14.0)
RISE (Ours)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
+ Iteration 1 35.3 50.6 (+15.3) 59.2(+23.9) 68.6(+33.3) 6.7 9.5 (+2.8) 18.4(+11.1) 29.7(+22.4)
SFT on oracle data
Only correct data 27.4 42.2 (+14.9) 34.0(+6.6) 43.6(+16.2) 5.8 7.9 (+2.1) 5.5(-0.3) 12.1(+6.2)
Correct and incorrect 25.7 41.8 (+16.1) 31.2(+5.5) 41.5(+15.8) 5.0 5.2 (+0.2) 5.0(+0.0) 13.1(+8.1)
Baselines
GPT-3.5 66.4 80.6 (+14.2) 71.0(+4.6) 74.7(+8.3) 39.7 47.8 (+8.1) 45.1(+5.4) 54.3(+14.6)
Mistral-7B 33.7 49.4 (+15.7) 39.0(+5.3) 46.9(+13.2) 7.5 13.0 (+5.5) 8.4(+0.9) 13.0(+5.5)
Eurus-7b-SFT 36.3 66.3 (+30.0) 47.9(+11.6) 53.1(+16.8) 12.3 19.8 (+7.5) 16.3(+4.0) 22.9(+10.6)
Self-Refine →m1@t3→p1@t3 →m1@t3→p1@t3
Base 10.5 22.4 (+11.9) 7.1(-3.4) 13.0(+2.5) 1.9 5.1 (+3.2) 1.9(0.0) 3.1(+1.2)
+Boost 32.9 45.3 (+12.4) 26.5(-6.4) 40.9(+8.0) 5.5 6.5 (+1.0) 2.9(-2.6) 7.2(+1.7)
+Iteration1 35.6 49.5 (+13.9) 31.7(-3.9) 43.7(+8.1) 6.3 8.7 (+2.4) 5.9(-0.4) 9.9(+3.6)
+Iteration2 37.3 50.5 (+13.2) 33.3(-4.0) 44.5(+7.2) 5.8 9.4 (+3.6) 5.7(-0.1) 9.5(+3.7)
GPT-3.5 66.4 80.2 (+13.8) 61.0(-5.4) 71.6(+5.2) 39.7 46.5 (+6.8) 36.5(-3.2) 46.7(+7.0)
Mistral-7B 33.7 48.5 (+14.8) 21.2(-12.5) 37.9(+4.2) 7.5 12.3 (+4.8) 7.1(-0.4) 11.4(+3.9)
Eurus-7b-SFT 36.3 65.9 (+29.6) 26.2(-10.1) 42.8(+6.5) 12.3 19.4 (+7.1) 9.0(-3.3) 15.1(+2.8)
GloRE →m1@t3→p1@t3
+ORM 48.2 49.5 (+1.3) 57.1(+8.9)
+SORM 48.2 51.6 (+3.4) 59.7(+11.5) N/A
+Direct 48.2 47.4 (-0.8) 59.2(+11.0)
V-STaR →m64@t1
+STaR 28.0 46.1 (+18.1)
+Verification 28.0 56.2 (+28.2) N/A
+V-STaR 28.0 63.2 (+35.2)
Table 6: Comparing RISE with other approaches (Self-Refine, GLoRE, and V-STaR) and other baseline approaches.
Observe that RISE attains the biggest performance improvements between 1-turn and 5-turn performance without the use of
an oracle on both GSM8K and MATH. This performance gap is even larger when oracle early termination is allowed (5-turn
w/ oracle). Self-Refine largely degrades performance across the board. GLoRE trains a separate refinement model, but still
performs worse than RISE.
24
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Comparison with Self-Refine [ 31].To build a self-refine baseline [ 31] evaluation, we slightly modified
our evaluation pipeline following the self-refine approach. In this setup (Figure 11), the model generates
an initial response, and then the environment prompts the model to locate errors in the generated
solution and refine its answer based on the initial response and the identified error.
Self-Refine
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 17 >
User:<Query >
Agent:<Initial Answer >
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent:<Critic >
User: Now, rewrite the solution in the required format:
Agent:<Refined Answer >
Figure11:Prompt for Self-Refine : We follow the standard pipeline of the original paper, prompt the
LLM to refine and correct its previous mistakes.
However, our experiments show that without any oracle hint from the environment or human feedback,
the self-refine approach leads to a degradation in performance across all models. Only when oracle
feedback is available to assist with early termination does the self-refine approach provide a slight
performance boost. This highlights the limitation of the self-refine structure in effectively improving
model performance without external guidance, which is also observed in [22].
In contrast, the model trained with RISE can attain consistent performance improvements without relying
on an oracle. By training the model to iteratively refine its responses, our method enables the model to
self-correct and improve its performance over multiple turns. This showcases the effectiveness of our
approach incomparison to the self-refine baseline, as it allows for more robust and consistent performance
gains without the need for the oracle assistance.
Comparison with GLoRE [ 17].GLoRE is a multi-model system that relies on a student model to
propose drafts, an Outcome-based Reward Model (ORM) or Step-wise ORM to locate errors at different
granularity levels, and a Global or Local Refinement Model for adjusting these errors. Since no code
was openly available for this approach, in our experiments, we compared to the numbers from the main
paper Havrilla et al. [17]. While the comparison against GLoRE is already apples-to-oranges since our
25
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
method only trains a single end-to-end model, while GLoRE trains multiple models. Performance-wise,
GLoRE’s global and local refinement models show little to no improvement in overall accuracy without an
oracle, and even exhibit decreasing accuracy in some cases. However, when an oracle is used to guide the
refinement process, GLoRE demonstrates a 10% improvement on the 7B model in the GSM8K dataset.
As anticipated, since we run RISE from a less advanced base model (Llama2 7B), we observe a slightly
lower absolute performance compared to GLoRE. However, RISE demonstrates its effectiveness in self-
improvement by sequentially enhancing its performance by an impressive 13.4% within just 3 turns
without an oracle feedback, and by a remarkable 23.4% with an oracle on GSM8K. This showcase of
RISE’s capabilities is particularly noteworthy considering that GLoRE utilizes 3 independent models -
one for generating candidate solutions, one reward model for locating errors, and one refinement model
for refinement.
Comparison with V-STaR [ 19].V-STaR requires training an additional verifier model to rank candidate
answers generated by the targeted model, but it does not make any sequential revisions or improvements
to a response. While comparing RISE to using a verifier for re-ranking the top 5 responses at the first
turn (as a base comparison) would have been informative, we were unable to find this specific result
in the original V-STaR paper. The results presented in the official table 6 for V-STaR correspond to
running 64 samples, which improves the base model’s performance by 35.2% for each prompt during
evaluation. In contrast, our method, RISE, after the same amount of finetuning iterations (3 iterations)
and using only 5 samples, improves upon the base model by 44.5% (calculated as 55.0% - 10.5% =
44.5%). This comparison highlights RISE’s efficiency in achieving significant improvements with fewer
samples and iterations compared to V-STaR’s approach of using a large number of samples without
sequential refinement.
Moreover, V-STaR’s performance is inherently bounded by the candidate generator’s performance. As
discussed in Section 5, if there is no correct response among the generated candidates, the problem
remains unsolved. In contrast, we show in Figure 6 that RISE can also solve problems that were not
solved by majority voting with a much higher budget in the first turn. Furthermore, we believe that
combining V-STaR with RISE could lead to even better performance, as RISE can generate better models
and a verifier can be complementarily used for filtering.
Comparison with other base models. Mistral-7B [ 23] and Eurus-7B-SFT [ 58] are models that exhibit
comparable performance to our method in terms of the absolute maj@5 performance. However, it
is crucial to note that these base models are fine-tuned using a vast amount of data, including data
specifically tuned for math reasoning performance [ 58], while our model is fine-tuned on a single domain.
That said, we do show that fine-tuning with RISE can still enhance the performance of Mistral-7B models.
To summarize, our method offers several advantages over GLoRE and V-STaR, such as end-to-end
error correction with a single model, superior performance with fewer samples, and the ability to solve
problems that cannot be solved by random sampling in the first turn. Although our maj@1 performance
is lower than GLoRE’s base model EI, which is an apples-to-oranges comparison our ultimate 5-turn
performance surpasses their best absolute performance in both oracle and non-oracle scenarios.
Compared to other base models like Mistral-7B and Eurus-7B-SFT, our method achieves comparable
performance while being fine-tuned on a single domain, and it can be generalized to better base models.
26
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
B.2. Qualitative Examples from RISE
In this section, we provide some qualitative examples showing the nature of edits made by RISE on
various datasets that we train on. We utilize the model from iteration 2 of RISE.
27
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Small Edits)
Query: Mike plays ping pong for 40 minutes. In the first 20 minutes, he scores 4 points. In the
second 20 minutes, he scores 25% more points. How many total points did he score?
Turn-1 Response :
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
So,Mikescores4+4=8pointsinthesecond20minutes.
Step 3: To find the total points, we need to add the points scored in the first and second 20 minutes.
total_points = 4 + 8 = 12.
Answer: 12✗
Turn-2 Response :
I apologize for the mistake. Let’s solve the problem step by step.
Step 1: In the first 20 minutes, Mike scores 4 points.
Step 2: In the second 20 minutes, Mike scores 25% more points than he did in the first 20 minutes.
Thismeanshescores4+4*25%=4+1=5pointsinthesecond20minutes.
Step 3: To find the total points, we add the points scored in the first and second 20 minutes: 4 + 5
= 9 points.
Answer: 9✓
RISE Example (Big Edits)
Query: In a candy machine, there are 22 more than four times the number of pink gumballs as
there are blue gumballs. If there are 12 blue gumballs how many pink ones are there?
Turn-1 Response :
Step 1: Let’s assume the number of blue gumballs as x. Step 2: According to the given information,
there are 22 more than four times the number of pink gumballs as there are blue gumballs. So, the
number of pink gumballs can be expressed as 4x + 22. Step3:Wearegiventhatthereare12blue
gumballs,solet’ssubstitutexwith12intheequation.
Answer: 54✗
Turn-2 Response :
Let’s solve the problem step by step: Step 1: Let’s denote the number of blue gumballs as x. Step
2: We are given that the number of pink gumballs is 22 more than four times the number of blue
gumballs. So, the number of pink gumballs can be expressed as 4x + 22. Step3:Wearealsogiven
thatthereare12bluegumballs,sowecansubstitutex=12intotheexpressionforthenumberof
pinkgumballs:4*12+22=48+22=70Therefore,thereare
boxed70 pinkgumballs.
Answer: 70✓
Figure12:Examples of RISE correct its previous behavior in different modes. Some only make changes to a small part (small
edits), some may directly rewrite most of its previous answers (big edits) because the first step in the previous answer is wrong.
The mistaken steps of different turns are highlighted in red, and the correct are highlighted in green. This demonstrates shows
how RISE can correct its previous answers and finally get to a correct answer.
28
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Noise Tolerance)
Query: Ryan plants 2 flowers a day in his garden. After 15 days, how many flowers does he have if 5 did not grow?
Turn-1 Response :
Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15 days = 30 flowers in his garden.
Step 2: However, 5 flowers did not grow, so we need to subtract these non-growing flowers from the total count. Step 3:
Calculate the number of flowers that actually grew in Ryan’s garden. flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-2 Response :
Apologies for the mistake. Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total
of 2 flowers/day * 15 days = 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these
non-growing flowers from the total count. Step 3: Calculate the number of flowers that actually grew in Ryan’s garden.
flowers_grew = 30 flowers - 5 flowers = 25 flowers.
Answer: 25✓
Turn-3 Response :
Let’s reevaluate the solution. Step 1: Ryan plants 2 flowers a day for 15 days, so he plants a total of 2 flowers/day * 15
days = 30 flowers in his garden. Step 2: However, 5 flowers did not grow, so we need to add these flowers to the total
count, as they were planted but did not grow. Step3:CalculatethetotalnumberofflowersinRyan’sgarden.total_flowers
=30flowers+5flowers=35flowers.
Answer: 35✗
Turn-4 Response
Let’s correct the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, so he plants a total of 2 flowers/day * 15 days
= 30 flowers in his garden. Step 2: Since 5 flowers did not grow, we need to subtract these non-growing flowers from the
total count. Step 3: Calculate the total number of flowers in Ryan’s garden after subtracting the non-growing flowers.
total_flowers = total_planted_flowers - non_growing_flowers = 30 flowers - 5 flowers=
boxed25 flowers.
Answer: 25✓
Turn-5 Response
Let’s reevaluate the solution. Step 1: In 15 days, Ryan plants 2 flowers a day, which is 2 flowers/day * 15 days = 30
flowers in total. Step 2: However, 5 flowers did not grow, so we have to subtract these 5 flowers from the total. Step 3:
Therefore, the total number of flowers Ryan has is 30 flowers (total planted) - 5 flowers (did not grow) =
boxed25 flowers.
Answer: 25✓
Figure13:Examples of RISE’s tolerance of noisy feedback . In the evaluation where there is no oracle, we use a verifier
that always tells the model, "The answer is incorrect. Please try again. Here’s the question: <Query >". We observe that from
turn 2 to turn 5, the model is still able to output the correct answer in 3 out of 4 turns. In the response at turn 4, the model
performs half of the solution correctly, and only the last step is wrong. In addition, in the turns where the model still outputs
the correct answer, it doesn’t directly copy the answer from the previous turn but instead comes up with a new paraphrase. This
demonstrates that RISE provides the model with tolerance to noisy feedback and does not randomly change its behavior upon
receiving a revisiting request. The mistaken steps of different turns are highlighted in red
29
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
RISE Example (Error Localization)
Query: Josh decides to try flipping a house. He buys a house for $80,000 and then puts in $50,000 in repairs. This
increased the value of the house by 150%. How much profit did he make?
Turn-1 Response :
Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, which increases the value of the house by
150%. Step 3: To calculate the increase in value, we multiply the cost of the house by 150% and add it to the cost of the
house. increase_in_value = $80,000 * 150% = $120,000. Step4:Tocalculatetheprofit,wesubtractthecostofthe
housefromitsnewvalue.profit=increase_in_value -$80,000 =$120,000 -$80,000 =$40,000.
Answer: 40,000✗
Turn-2 Response :
Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000 in repairs, and
this increases the value of the house by 150%. Step 3: The percentage increase in value is 150% of $80,000, which is
$120,000 (80,000 * 1.5 = $120,000). Step4:Tofindtheactualamount thatwouldbeaddedtothehouse’svalueafter
repairs,weneedtosubtracttheamount hespentonrepairsfromtheincreased value,whichis$120,000 -$50,000 =
$70,000. Step5:TheprofitJoshwouldmakeisthedifferencebetweenthecostofbuyingthehouseandtheincreased
valueafterrepairs,whichis$70,000 -$80,000 =-$10,000 ($10,000 lessthantheinitialcost).
Answer: 0✗
Turn-3 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: This increases the value of the house by 150%. Step 4: To find the increase in value, we calculate 150%
of the original price of the house: 150% of $80,000 = $120,000. Step5:Theincreaseinvalueafterrepairsistheoriginal
priceplus150%oftheoriginalprice:$80,000 +$120,000 =$200,000. Step6:Joshsellsthehousefor$200,000 and
madeaprofitof$200,000 -$80,000 =$120,000.
Answer: 120,000✗
Turn-4 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in
$50,000 in repairs, increasing the value of the house by 150%. Step 3: The increase in value is 150% of $80,000, which
is $120,000 (80,000 * 1.5 = $120,000). Step4:Thetotalamount spent,includingthepurchaseofthehouseandthe
repairs,is$80,000 +$50,000 =$130,000. Step5:TheprofitJoshmadeistheincreaseinvalueafterrepairsminusthe
totalamount spent,whichis$120,000 -$130,000 =-$10,000. Therefore,Joshmadea
boxed0 profit.
Answer: 0✗
Turn-5 Response : Let’s solve the problem step-by-step: Step 1: Josh buys a house for $80,000. Step 2: He puts in $50,000
in repairs. Step 3: The repairs increase the value of the house by 150%. Step 4: The increase in value is $50,000, which is
150% of $33,333 (50,000 / 1.5 = $33,333). Step 5: The repairs cost $50,000, and the increase in value is $33,333. Step
6: Therefore, Josh’s profit is $33,333 - $50,000 = -$16,667. Therefore, Josh made a 16676 profit.
Answer: 16676 ✗
Figure14:ExamplesofRISEnotbeingabletocorrectitserrorwithin5stepsbutdemonstratingmeaningful errorlocalization
behavior . Even in turn 2, it has already solved the problem at step 4 but mistakenly takes another step and reaches the wrong
answer. The following turns are unable to correct this small error. Though this problem remains unsolved, we observe that (1)
the model is able to stick to the correct steps, where all responses reach an intermediate step of 12000 correctly, except for the
last response, where the model tries to modify the answer from one step ahead; (2) the model doesn’t repeat its responses,
which is a behavior we notice when evaluating some off-the-shelf models; and (3) the model is making meaningful changes to
the incorrect steps. In summary, although the final answer is still incorrect, we observe that through RISE, the model is able to
locate the error and perform local computation correctly. The mistaken steps of different turns are highlighted in red, and the
correct steps in turn 2 is highlighted in green.
30
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
C. Pseudocode
Algorithm 1 Data Collection at Iteration 𝑇
1:𝒟′
𝑇←𝒟′
𝑇−1
2:forindex 𝑖in{1, . . . ,|𝒟|}do
3: 𝑠1←𝑥𝑖
4:forstep𝑇′in{1, . . . , 𝑇−1}do
5: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇−1(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
6: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
7: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
8: if𝑟𝑖
𝑇′= 1then
9: break
10: end if
11:end for
12:if𝑟𝑖
𝑇′̸= 1then
13: 𝑇′←𝑇′+ 1
14: 𝑦𝑖
𝑇′←arg max ˜ 𝜋(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=1+𝑠𝑇′)
15: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
16:end if
17:𝒟′
𝑇←𝒟′
𝑇∪{︀(︀
𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖
𝑡,𝑟𝑖
𝑡)︀}︀𝑇′
𝑡=1
18:end for
Algorithm 2 Inference at iteration 𝑇
1:forindex 𝑖in{1, . . . ,|𝒟|}do
2: 𝑠1←𝑥𝑖
3:forstep𝑇′in{1, . . . , 𝑁}do
4: 𝑦𝑖
𝑇′←arg max 𝜋𝜃𝑇(·|(𝑠𝑖
𝑡,𝑦𝑖
𝑡,𝑓𝑖)𝑇′−1
𝑡=max{1,𝑇′−𝑇}+𝑠𝑇′)
5: 𝑠𝑖
𝑇′+1,𝑟𝑖
𝑇′←env.step (𝑠𝑖
𝑇′,𝑦𝑖
𝑇′)
6: 𝑓𝑖
𝑇′=retry message +𝑥𝑖
7:end for
8:forstep𝑇′in{1, . . . , 𝑁}do
9: ˜𝑦𝑖
𝑇′←majority voting{𝑦𝑖
𝑡}𝑇′
𝑡=1
10:end for
11:end for
31
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D. Experimental Details
D.1. Hyperparameters for Fine-Tuning with RISE
For finetuning, we utilize the FastChat codebase, but we customize the loss function to be weighted
by reward. The base models are directly loaded from Hugging Face: hrefhttps://huggingface.co/meta-
llama/Llama-2-7b-hfLlama-2-7b-chat-hf and Mistral-7B-Instruct-v0.2. The hyperparameters used for
finetuning are specified in Table 7.
Hyperparameter Values
bf16 True
epochs 2
per device train batch size 1
gpus 4xA40
gradient accumulation steps 16
learning rate 1e-5
weighted decay 0
warmup ratio 0.04
learning rate scheduler trype cosince
tf32 True
model max length 2048
Table 7: Hyperparameters used for RISE
D.2. Inference Hyperparameters
For API-based models, such as GPT-3.5, we directly query the official web API provided by OpenAI. In the
case of open-source models, we utilize FastChat to serve the model as a web API and interact with the
environment through API calls. Serving a 7B model requires a single A100 or A40 GPU. To control the
randomness and length of answers generated by the LLMs, we employ the hyperparameters specified in
Table 8.
Hyperparameters/Description Open-source GPT
temperature 1.0 0.7
top_p 1.0 1
max_new_tokens 1000 512
Table 8: The hyperparameter settings used for generating responses from open-source and the GPT
models.
D.3. Datasets
The GSM8K dataset consists of 7,473 problems in the training portion and 1,319 problems in the testing
portion. Similarly, the MATH dataset is divided into 7,500 problems for training and 1,000 problems
32
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
for testing. The training portions of both datasets are used to generate trajectories in each iteration of
the RISE method, while the testing portions are held out for evaluating the performance of the models.
Additionally, the SVAMP dataset, containing 1,000 problems, is used solely for evaluation purposes to
demonstrate the generalizability of our method.
For generating training trajectories, at iteration 𝑖, the current model is rolled out for a maximum of 𝑖
steps. Subsequently, an expert model, such as GPT-3.5, is employed to take the conversation history
between the current model and the environment and sample 5 responses. Among these responses, the
one with the highest reward is chosen, with arbitrary tie-breaking in case of multiple responses with the
same highest reward.
D.4. Prompts used for seeding RISE on the GSM8K and MATH tasks
Here we show the prompt we used for data generation and model evaluation:
RISE
System: You are an AI language model designed to assist with math problem-solving. In this task, I
will provide you with math problems. Your goal is to solve the problem step-by-step, showing your
reasoning at each step. After you have finished solving the problem, present your final answer as
∖boxed{Your Answer}.
<One-shot Example 16 >
User:<Query >
Agent:<Answer >
User: The answer is incorrect. Please try again. Here’s the question: <Query >
Agent:<Answer >
···
Figure15:Prompt for RISE : We follow the standard pipeline of math problem solving, prompt the LLM
to solve the problem and retry untill exceeds the maximum number of turns
33
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
D.5. One-shot Example
RISE One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we subtract the total
number of students taking only math, only physics, and both from the total number of students in
the drama club. This gives us $60 - 16 - 7 - 20 = ∖boxed{17}$ students taking neither.
Answer:∖boxed{17}
Figure16:One-shot Example : Demonstrates how to solve a math problem step-by-step and the expected
answer format.
34
Recursive Introspection: Teaching Language Model Agents HowtoSelf-Improve
Self-Refine One-shot example
User: Of the 60 students in the drama club, 36 take mathematics, 27 take physics and 20 students
take both mathematics and physics. How many drama club students take neither mathematics nor
physics?
Agent: Step 1: To find the number of drama club students who take neither mathematics nor
physics, we first need to determine the number of students taking only math, only physics, and both
math and physics.
Step 2: Out of the 60 students in the drama club, 36 take mathematics and 27 take physics, and 20
students take both mathematics and physics.
Step 3: To calculate the number of students taking only math, we subtract the number of students
taking both from the total taking math: $36 - 20 = 16$.
Step 4: Similarly, to calculate the number of students taking only physics, we subtract the number
of students taking both from the total taking physics: $27 - 20 = 7$.
Step 5: Now, to find the number of students taking neither math nor physics, we add the number
of students taking only math and only physics, then subtract this sum from the total number of
students in the drama club. This gives us $60 - (16 + 7) = ∖boxed{37}$ students taking neither.
Answer:∖boxed{37}
User: There is an error in the solution above because of lack of understanding of the question. What
istheerror? Tofindtheerror,gothrougheachstepofthesolution,andcheckifeverythinglooksgood.
Agent: Step 1: Correct. We need to find the number of students taking neither math nor physics.
Step 2: Correct. The given information is accurately stated.
Step 3: Correct. The calculation of students taking only math is correct.
Step 4: Correct. The calculation of students taking only physics is correct.
Step 5: Incorrect. The solution adds the number of students taking only math and only physics,
but this does not account for the students taking both subjects. By subtracting this sum from
thetotalnumberofstudents,thesolutiondouble-countsthestudentswhotakebothmathandphysics.
User: Now, rewrite the solution in the required format:
Agent:<Same as 16 >
Figure17:One-shot Example : Demonstrates the process of self-critique and error correction based on
the self-critique.
35 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18175v1 | http://arxiv.org/pdf/2407.18175v1 | Quasar-ViT: Hardware-Oriented Quantization-Aware Architecture Search for Vision Transformers | Zhengang Li, Alec Lu, Yanyue Xie, Zhenglun Kong, Mengshu Sun, Hao Tang, Zhong Jia Xue, Peiyan Dong, Caiwen Ding, Yanzhi Wang, Xue Lin, Zhenman Fang | 2024-07-25 | ABSTRACT
Vision transformers (ViTs) have demonstrated their superior accu-
racy for computer vision tasks compared to convolutional neural
networks (CNNs). However, ViT models are often computation-
intensive for efficient deployment on resource-limited edge devices.
This work proposes Quasar-ViT, a hardware-oriented quantization-
aware architecture search framework for ViTs, to design efficient
ViT models for hardware implementation while preserving the ac-
curacy. First, Quasar-ViT trains a supernet using our row-wise flex-
ible mixed-precision quantization scheme, mixed-precision weight
entanglement, and supernet layer scaling techniques. Then, it ap-
plies an efficient hardware-oriented search algorithm, integrated
with hardware latency and resource modeling, to determine a se-
ries of optimal subnets from supernet under different inference
latency targets. Finally, we propose a series of model-adaptive de-
signs on the FPGA platform to support the architecture search and
mitigate the gap between the theoretical computation reduction
and the practical inference speedup. Our searched models achieve
101.5, 159.6, and 251.6 frames-per-second (FPS) inference speed
on the AMD/Xilinx ZCU102 FPGA with 80.4%, 78.6%, and 74.9%
top-1 accuracy, respectively, for the ImageNet dataset, consistently
outperforming prior works.
ACM Reference Format:
Zhengang Li1, Alec Lu2, Yanyue Xie1, Zhenglun Kong1, Mengshu Sun†,
Hao Tang3, Zhong Jia Xue2, Peiyan Dong1, Caiwen Ding4, Yanzhi Wang1,
Xue Lin1, Zhenman Fang2,1Northeastern University,2Simon Fraser Univer-
sity,3ETH Zurich,4University of Connecticut, E-mail:1{li.zhen, xie.yany,
kong.zhe, dong.pe, yanz.wang, xue.lin}@northeastern.edu,2{alec_lu, zjxue,
zhenman}@sfu.ca. 2024. Quasar-ViT: Hardware-Oriented Quantization-
Aware Architecture Search for Vision Transformers. In Proceedings of the
38th ACM International Conference on Supercomputing (ICS ’24), June 4–7,
2024, Kyoto, Japan. ACM, New York, NY, USA, 14 pages. https://doi.org/10.
1145/3650200.3656622
†MS is now afflicted with Beijing University of Technology; she contributed to this
work during Ph.D at Northeastern University.
Permission to make digital or hard copies of all or part of this work for personal or
classroom use is granted without fee provided that copies are not made or distributed
for profit or commercial advantage and that copies bear this notice and the full citation
on the first page. Copyrights for components of this work owned by others than the
author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or
republish, to post on servers or to redistribute to lists, requires prior specific permission
and/or a fee. Request permissions from [email protected].
ICS ’24, June 4–7, 2024, Kyoto, Japan
©2024 Copyright held by the owner/author(s). Publication rights licensed to ACM.
ACM ISBN 979-8-4007-0610-3/24/06. . . $15.00
https://doi.org/10.1145/3650200.36566221 | INTRODUCTION
ViTs [ 10,35,42,62] incorporate the attention mechanism [ 46] to
fulfill various computer vision tasks, by allowing all the pixels in
an image to interact through transformer encoder blocks and thus
achieving higher accuracy compared to CNNs. Table 1 compares
representative CNN and ViT models, i.e., ResNet [ 12]/ResNeXt [ 56]
and DeiT [ 42] for the ImageNet dataset. DeiT-small (DeiT-S) with
a comparable number of parameters and GMACs as ResNet-50
achieves even higher accuracy than ResNeXt-101, whose size is
around 4×as that of DeiT-S. DeiT-base (DeiT-B) with comparable
size as ResNeXt-101 achieves 2.54% higher top-1 accuracy.
Table 1: Comparison of ResNets, ResNeXt, and DeiTs on Ima-
geNet dataset. We choose DeiT without distilling token here,
which represents state-of-the-art ViTs, as it can be directly
trained on ImageNet-10k without pre-training on a massive
dataset.
Model #Params (M) MACs (G) Top-1 Acc. Top-5 Acc.
ResNet-18 11.69 1.82 69.76% 89.08%
ResNet-50 26.56 4.14 76.13% 92.86%
ResNet-152 60.19 11.61 78.31% 94.05%
ResNeXt-101 88.79 16.59 79.31% 94.53%
DeiT-S 22.10 4.60 79.85% 94.97%
DeiT-B 87.50 17.60 81.85% 95.59%
Despite ViTs’ significant accuracy improvement, it is non-trivial
to deploy ViT inference on resource-limited edge devices due to
their huge model size and complex architectures. For example,
even the lightweight ViT model DeiT-S [ 42] has a model size of
22.10𝑀parameters×4𝐵𝑦𝑡𝑒𝑠 per floating-point parameter = 88.4𝑀𝐵,
presenting an overwhelming computing load and memory size for
most edge devices.
The basic transformer encoder with multi-headed self-attention
(MSA) and multi-layer perceptron (MLP) blocks is shown in Fig-
ure 1, consisting of multiple different computation components,
including linear layer, attention, residual addition, matrix reshape
operation, GELU, and layer norm. To further understand the bottle-
neck of the current ViT model structure, we profile the runtime of
each component of ViT on a Xeon(R) Silver 4214 CPU [ 16] using
Pytorch Profiler [ 33] as shown in Figure 1. We use the same color to
indicate the same component in both the transformer block struc-
ture and profiling figures. It shows matrix multiplication operations
dominate the processing time (94.7% and 87.3% for DeiT-B [ 42] and
DeiT-S [31], respectively) of execution cycles.arXiv:2407.18175v1 [cs.LG] 25 Jul 2024
ICS ’24, June 4–7, 2024, Kyoto, Japan
LinearLinearGELULayerNormLinear
LayerNormLinearAttentionSoftmaxAdd ResidualAdd ResidualMLPMSA×𝑁!AttentioSoftmax1.46%LayerNorm…GEL…Reshape0.40%Add Residual0.30%Nonlinea…
Attention9.2%Linear75.2%Softmax2.8%LayerNorm2.6%GELU8.1%Reshape1.4%Add Residual0.7%MatrixMultiplication84.4%Nonli…MatrixMultiplication92.85%7.15%AttentionLinearSoftmaxLayerNormGELUReshapeAdd ResidualMatrixMultiplicationNonlinearFunctionsMatrixMultiplication84.40%15.60%a) DeiT-Base
b) DeiT-S
Figure 1: Transformer encoder block structure and ViT model
execution performance profiling on CPU for a) DeiT-Base
and b) DeiT-S with 12 encoders on ImageNet dataset.
Contemporary acceleration methods mainly focus on reduc-
ing the practical inference latency of matrix multiplication opera-
tions. They primarily fall into two categories: 1) neural architecture
search (NAS) that searches the lighter-weight model; and 2) model
compression, especially model quantization that reduces the per-
parameter bit-width. However, there are two major challenges when
applying these methods on hardware. The first challenge is associ-
ated with model quantization. It has been revealed that the most
suitable quantization schemes/bit-widths depend on model sizes
and architectures [ 49,54], and there is a vast design space in the
quantization of both weights and activations for each layer on dif-
ferent models and hardware. As ViT models become deeper, the de-
sign space increases exponentially, resulting in poor performance of
rule-based strategies. Although recent studies explored automated
quantization techniques for a given ViT architecture [ 45,49,54],
they did not integrate model quantization with NAS together, which
could result in suboptimal performance. In this paper, we propose
the framework of model quantization and NAS co-design for ViTs
towards improved performance compared to treating NAS and
quantization separately.
The second challenge is the gap between the theoretical com-
putation throughput and the practical inference speed on actual
hardware. For example, layer-wise (inter-layer) mixed-precision
quantization (for CNNs) [ 49,54] quantizes each layer with a dif-
ferent bit-width and therefore executes layers through distinct
hardware components sequentially, leading to low resource utiliza-
tion. Furthermore, kernel-wise mixed-precision quantization (for
CNNs) [ 29] assigns different bit-widths down to the kernel level,
significantly diversifying the computing pattern and is inefficient
for hardware implementation.Recent work FILM-QNN [ 40] and Auto-ViT-Acc [ 22] leverage
the intra-layer mixed quantization to achieve good performance
for both model accuracy and throughput on FPGA. By applying
two different quantization bit-widths/schemes for different chan-
nels and limiting the same mixed-precision ratio across each layer,
FPGA can efficiently handle different computations on different
hardware resources sharing the same hardware design. However,
existing approaches suffer from a manually configured uniform
mixed-precision ratio across all layers, potentially compromising
quantized model accuracy. Moreover, architectural design consider-
ations are often neglected, limiting the overall model performance.
To address these problems comprehensively, we propose Quasar-
ViT, an integration of a hardware-oriented quantization-aware ar-
chitecture search targeting ViT. First, to fully unleash the com-
putation potential of FPGA resources, we investigate a hardware-
friendly row-wise mixed-precision quantization scheme. At the al-
gorithm level, different from FILM-QNN [ 40] and Auto-ViT-Acc [ 22],
we quantize different channels within each layer into lower and
higher bit-widths with the flexibility of different mix-ratios for lay-
ers, which achieves a more fine-grained architecture to maintain
the accuracy. At the hardware level, we propose the FPGA-based
model-adaptive design, including 4-bit atomic computation and
hybrid signed/unsigned DSP packing, which set basic hardware
units for the lower-bit computation, and decompose the higher-bit
computation to lower-bit ones to reuse the resources. Second, dur-
ing the supernet training, we propose the mixed-precision weight
entanglement mechanism, such that different transformer blocks in
subnets can share weights for their common parts in each layer to
enable efficient quantization during architecture search and reduce
training memory cost. On top of that, we establish the correspond-
ing FPGA latency and resource modeling to estimate the inference
latency and combine it with an efficient hardware-oriented evo-
lution search method. Based on the above, we integrate with the
one-shot NAS algorithm to efficiently find the most accurate quan-
tized model under the given inference latency. We also explore the
layer scaling in CaiT [ 43] and extend it to the supernet architecture
to improve the training efficiency and model accuracy. To demon-
strate the compatibility of our proposed framework with knowledge
distillation (KD) and further improve our searched model accuracy,
we integrate KD [ 15] into the training process. Finally, on the hard-
ware side, we implement the basic computing units for 4-bit weight
and 6-bit activations with hybrid signed/unsigned DSP packing
optimization to enable efficient FPGA implementation.
The contributions of our work are summarised as follows:
•An end-to-end hardware-oriented quantization-aware archi-
tecture search framework (Quasar-ViT) for ViTs, achieving
superior accuracy and inference speed over prior studies. La-
tency/resource modeling of the hardware accelerator design
is integrated into the search process.
•Hardware-friendly quantization techniques—such as flexible
row-wise mixed-precision quantization and mixed-precision
weight entanglement—in the architecture search, towards
high accuracy, low training cost, and efficient implementa-
tion.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
•Real FPGA implementations of our model-adaptive design,
with our proposed 4-bit weight atomic computation and
hybrid signed/unsigned DSP packing.
•Integration of proposed supernet layer scaling (SLS) in our
framework, achieving further accuracy improvement. Our
ablation study also demonstrates our framework’s good com-
patibility with knowledge distillation (KD).
Quasar-ViT achieves 101.5, 159.6 and 251.6 FPS on the AMD/Xilinx
ZCU102 FPGA board with 80.4%, 78.6%, and 74.9% top-1 accuracy
for ImageNet, respectively.
Compared to the representative ViT training-aware quantiza-
tion [ 20] and the post-training quantization [ 27], at a similar model
size, our model achieves 2.1% and 5.2% higher top-1 accuracy, re-
spectively. Compared with Auto-ViT-Acc [ 22], a state-of-the-art
FPGA accelerator for ViT with mixed-scheme quantization (with-
out NAS), we achieve 1.7% better top-1 accuracy with a similar FPS,
and 1.6×better FPS with a similar level of model accuracy.
2 | Section not found | RELATED WORK
2.1 Vision Transformers
First proposed in [ 10], the vision transformer (ViT) is a ground-
breaking work that uses transformer blocks for vision tasks. Unlike
traditional CNN architectures that use a fixed-size window with re-
stricted spatial interactions, ViT interprets an image as a sequence of
patches and adopts the self-attention mechanism [ 46]. This allows
all the positions in an image to interact through transformer blocks,
which provides the extraordinary capability to capture relations at
the pixel level in both spatial and temporal domains. However, the
original ViT requires pre-training with large-scale datasets such as
ImageNet-21k and JFT-300M. To tackle the problem, many variants
such as DeiT [ 42] and T2T-ViT [ 62] were proposed, which can be
well trained with only ImageNet-10k. ViTs improve model accu-
racy at the cost of increased volume of computation and structural
complexity. In ViTs, the main model architecture is transformer
encoder blocks with multi-headed self-attention (MSA) and multi-
layer perceptron (MLP) blocks. These blocks involve large matrix
multiplications, which incur the most computational cost. These
complex architectures and enormous computation/storage demand
make it hard to deploy ViTs on resource-limited edge devices.
Therefore, we quantize all layers involved in matrix multiplica-
tion, but not the non-linear functions, e.g., layer normalization, due
to their low computational cost and potential effects on accuracy.
2.2 Non-Transformer DNN Model Quantization
2.2.1 Quantization Scheme. To compress model size and improve
inference speed, model quantization has been widely explored
for deep neural networks (DNNs). Existing quantization research
can be categorized according to quantization schemes, such as bi-
nary [ 8,36], ternary [ 13], and low-bit-width fixed-point [ 7,7,68,68]
quantize models with the same interval between each quantization
level. Although binary and ternary quantization reduce operations
and simplify hardware implementation to the extreme, they intro-
duce large accuracy loss due to insufficient bit-width. For example,
based on reports from the above works, accuracy typically degrades
by>5%under binary quantization and 2−3%for ternary quantiza-
tion. To overcome the large accuracy loss coming from insufficientbit-width, the fixed-point quantization is proposed, applying mod-
erate and adjustable quantization bit-width, to maintain accuracy.
This quantization scheme was implemented with different | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | methods mainly focus on reduc-
ing the practical inference latency of matrix multiplication opera-
tions. They primarily fall into two categories: 1) neural architecture
search (NAS) that searches the lighter-weight model; and 2) model
compression, especially model quantization that reduces the per-
parameter bit-width. However, there are two major challenges when
applying these methods on hardware. The first challenge is associ-
ated with model quantization. It has been revealed that the most
suitable quantization schemes/bit-widths depend on model sizes
and architectures [ 49,54], and there is a vast design space in the
quantization of both weights and activations for each layer on dif-
ferent models and hardware. As ViT models become deeper, the de-
sign space increases exponentially, resulting in poor performance of
rule-based strategies. Although recent studies explored automated
quantization techniques for a given ViT architecture [ 45,49,54],
they did not integrate model quantization with NAS together, which
could result in suboptimal performance. In this paper, we propose
the framework of model quantization and NAS co-design for ViTs
towards improved performance compared to treating NAS and
quantization separately.
The second challenge is the gap between the theoretical com-
putation throughput and the practical inference speed on actual
hardware. For example, layer-wise (inter-layer) mixed-precision
quantization (for CNNs) [ 49,54] quantizes each layer with a dif-
ferent bit-width and therefore executes layers through distinct
hardware components sequentially, leading to low resource utiliza-
tion. Furthermore, kernel-wise mixed-precision quantization (for
CNNs) [ 29] assigns different bit-widths down to the kernel level,
significantly diversifying the computing pattern and is inefficient
for hardware implementation.Recent work FILM-QNN [ 40] and Auto-ViT-Acc [ 22] leverage
the intra-layer mixed quantization to achieve good performance
for both model accuracy and throughput on FPGA. By applying
two different quantization bit-widths/schemes for different chan-
nels and limiting the same mixed-precision ratio across each layer,
FPGA can efficiently handle different computations on different
hardware resources sharing the same hardware design. However,
existing approaches suffer from a manually configured uniform
mixed-precision ratio across all layers, potentially compromising
quantized model accuracy. Moreover, architectural design consider-
ations are often neglected, limiting the overall model performance.
To address these problems comprehensively, we propose Quasar-
ViT, an integration of a hardware-oriented quantization-aware ar-
chitecture search targeting ViT. First, to fully unleash the com-
putation potential of FPGA resources, we investigate a hardware-
friendly row-wise mixed-precision quantization scheme. At the al-
gorithm level, different from FILM-QNN [ 40] and Auto-ViT-Acc [ 22],
we quantize different channels within each layer into lower and
higher bit-widths with the flexibility of different mix-ratios for lay-
ers, which achieves a more fine-grained architecture to maintain
the accuracy. At the hardware level, we propose the FPGA-based
model-adaptive design, including 4-bit atomic computation and
hybrid signed/unsigned DSP packing, which set basic hardware
units for the lower-bit computation, and decompose the higher-bit
computation to lower-bit ones to reuse the resources. Second, dur-
ing the supernet training, we propose the mixed-precision weight
entanglement mechanism, such that different transformer blocks in
subnets can share weights for their common parts in each layer to
enable efficient quantization during architecture search and reduce
training memory cost. On top of that, we establish the correspond-
ing FPGA latency and resource modeling to estimate the inference
latency and combine it with an efficient hardware-oriented evo-
lution search method. Based on the above, we integrate with the
one-shot NAS algorithm to efficiently find the most accurate quan-
tized model under the given inference latency. We also explore the
layer scaling in CaiT [ 43] and extend it to the supernet architecture
to improve the training efficiency and model accuracy. To demon-
strate the compatibility of our proposed framework with knowledge
distillation (KD) and further improve our searched model accuracy,
we integrate KD [ 15] into the training process. Finally, on the hard-
ware side, we implement the basic computing units for 4-bit weight
and 6-bit activations with hybrid signed/unsigned DSP packing
optimization to enable efficient FPGA implementation.
The contributions of our work are summarised as follows:
•An end-to-end hardware-oriented quantization-aware archi-
tecture search framework (Quasar-ViT) for ViTs, achieving
superior accuracy and inference speed over prior studies. La-
tency/resource modeling of the hardware accelerator design
is integrated into the search process.
•Hardware-friendly quantization techniques—such as flexible
row-wise mixed-precision quantization and mixed-precision
weight entanglement—in the architecture search, towards
high accuracy, low training cost, and efficient implementa-
tion.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
•Real FPGA implementations of our model-adaptive design,
with our proposed 4-bit weight atomic computation and
hybrid signed/unsigned DSP packing.
•Integration of proposed supernet layer scaling (SLS) in our
framework, achieving further accuracy improvement. Our
ablation study also demonstrates our framework’s good com-
patibility with knowledge distillation (KD).
Quasar-ViT achieves 101.5, 159.6 and 251.6 FPS on the AMD/Xilinx
ZCU102 FPGA board with 80.4%, 78.6%, and 74.9% top-1 accuracy
for ImageNet, respectively.
Compared to the representative ViT training-aware quantiza-
tion [ 20] and the post-training quantization [ 27], at a similar model
size, our model achieves 2.1% and 5.2% higher top-1 accuracy, re-
spectively. Compared with Auto-ViT-Acc [ 22], a state-of-the-art
FPGA accelerator for ViT with mixed-scheme quantization (with-
out NAS), we achieve 1.7% better top-1 accuracy with a similar FPS,
and 1.6×better FPS with a similar level of model accuracy.
2 RELATED WORK
2.1 Vision Transformers
First proposed in [ 10], the vision transformer (ViT) is a ground-
breaking work that uses transformer blocks for vision tasks. Unlike
traditional CNN architectures that use a fixed-size window with re-
stricted spatial interactions, ViT interprets an image as a sequence of
patches and adopts the self-attention mechanism [ 46]. This allows
all the positions in an image to interact through transformer blocks,
which provides the extraordinary capability to capture relations at
the pixel level in both spatial and temporal domains. However, the
original ViT requires pre-training with large-scale datasets such as
ImageNet-21k and JFT-300M. To tackle the problem, many variants
such as DeiT [ 42] and T2T-ViT [ 62] were proposed, which can be
well trained with only ImageNet-10k. ViTs improve model accu-
racy at the cost of increased volume of computation and structural
complexity. In ViTs, the main model architecture is transformer
encoder blocks with multi-headed self-attention (MSA) and multi-
layer perceptron (MLP) blocks. These blocks involve large matrix
multiplications, which incur the most computational cost. These
complex architectures and enormous computation/storage demand
make it hard to deploy ViTs on resource-limited edge devices.
Therefore, we quantize all layers involved in matrix multiplica-
tion, but not the non-linear functions, e.g., layer normalization, due
to their low computational cost and potential effects on accuracy.
2.2 Non-Transformer DNN Model Quantization
2.2.1 Quantization Scheme. To compress model size and improve
inference speed, model quantization has been widely explored
for deep neural networks (DNNs). Existing quantization research
can be categorized according to quantization schemes, such as bi-
nary [ 8,36], ternary [ 13], and low-bit-width fixed-point [ 7,7,68,68]
quantize models with the same interval between each quantization
level. Although binary and ternary quantization reduce operations
and simplify hardware implementation to the extreme, they intro-
duce large accuracy loss due to insufficient bit-width. For example,
based on reports from the above works, accuracy typically degrades
by>5%under binary quantization and 2−3%for ternary quantiza-
tion. To overcome the large accuracy loss coming from insufficientbit-width, the fixed-point quantization is proposed, applying mod-
erate and adjustable quantization bit-width, to maintain accuracy.
This quantization scheme was implemented with different methods
and algorithms, such as DoReFa-Net [68] and PACT [7].
Finally, there are also non-linear quantization schemes, such as
power-of-two (PoT) [ 17] and additive PoT [ 19]. They replace the
multiplication with shifting operations where the distribution of
quantization levels becomes unbalanced, having higher precision
around the mean and less precision at the two sides.
2.2.2 Mixed-Precision/Scheme Quantization. To explore more quan-
tization potential while preserving the model accuracy, Besides
the single scheme quantization, some works [ 9,39,45,49,54] ex-
plore inter-layer mixed-precision quantization by assigning dif-
ferent precisions to layers. For example, HAQ [ 49] determines
the bit-width of each layer by an agent trained with reinforce-
ment learning. DNAS [ 54] used NAS to search layer-wise bit-width.
Furthermore, [ 29] explored intra-layer mixed quantization to en-
able different precisions or schemes within each layer. Based on
them, hardware designs [ 5,40] leveraged the intra-layer mixed-
precision/mixed-scheme to enable uniformity within each layer,
guaranteeing inference acceleration. However, they need to set the
same mixed ratio for layers, which limits the model’s accuracy.
2.3 Transformer and ViT Quantization
Quantization has also been studied for transformers, especially for
natural language processing (NLP) tasks [ 1,64,65]. Q8BERT [ 64]
finetuned BERT through 8-bit quantization-aware training. Ternary-
BERT [ 65] implemented an approximation-based and loss-aware
ternary quantization on BERT. BinaryBERT [ 1] proposed a ternary
weight splitting strategy to derive binary BERT with performance
as the ternary one. Inspired by those, [ 27] and [ 22] studied quan-
tization on ViT in computer vision tasks. PTQ [ 27] evaluated the
post-training quantization on ViT and achieved comparable accu-
racy to the full-precision version. Auto-ViT-acc [ 22] proposed an
FPGA-aware framework with mixed-scheme quantization for ViT,
which we will compare in the evaluation. FQ-ViT [ 24] proposed
power-of-two factor and log-int-softmax to proceed with the ViT
quantization. Q-ViT [ 20] used the switchable scale to achieve head-
wise ViT mixed quantization. However, these works are all based on
full-precision pre-trained models and do not include the dimension
of network architecture search.
2.4 Neural Architecture Search
2.4.1 NAS Strategies. There has been a trend to design efficient
DNNs with NAS. In general, NAS can be classified into the follow-
ing categories according to its search strategy. First, reinforcement
learning (RL) methods [ 2,4,25,32,67,69,70] use recurrent neural
networks as predictors validating the accuracy of child networks
over a proxy dataset. Second, evolution methods [ 30,37] develop
a pipeline of parent initialization, population updating, genera-
tion, and elimination of offspring to find desired networks. Third,
one-shot NAS [ 3,11,60] trains a large one-shot model containing
all operations and shares the weight parameters with all candi-
date models. Based on the above work, weight-sharing NAS has
become popular due to training efficiency [ 38,47,61]. One over-
parameterized supernet is trained with weights shared across all
ICS ’24, June 4–7, 2024, Kyoto, Japan
(a) Model-wise Quantization
(b) Layer-wise Mixed Quantization
(d) Row-wise Mixed QuantizationRows Rows
(e) Kernel-wise Mixed Quantization LayersRows
Weight kernel RowsFlexible mixed-ratio RowsHead
(c) Head-wise Mixed Quantization
Figure 2: Comparison of mixed-precision quantization under
different granularity. We use the example of two different
bit-widths, represented as blue and pink colors. We propose
the row-wise flexible mixed-precision quantization in (d).
sub-networks in the search space. This significantly reduces the
computational cost during the search. Although most of the above
work focuses on the traditional CNN architectures, such as [ 61]
and [ 38], some works have started investigating the search for ef-
ficient ViT networks [ 6,18,48,55]. Among them, Autoformer [ 6]
entangles the model weights of different ViT blocks in the same
layer during supernet training with an efficient weight-sharing
strategy to reduce training model storage consumption as well as
training time.
2.4.2 Hardware-Oriented NAS. Some recent works realize the gap
between theoretical computation improvement and practical infer-
ence speedup. They investigate the algorithm/hardware co-design
and incorporate the inference latency into NAS [ 23,41,53], which is
more accurate than intuitive volume estimation by MAC operations.
For example, MnasNet [ 41] and NPAS [ 23] utilize the latency on
mobile devices as the reward to perform RL search, where gradient-
based NAS work FBNet [ 53] adds a latency term to the loss function.
However, these works neither target ViTs nor exploit quantization
in the hardware-aware ViT search.
3 HARDWARE-ORIENTED
QUANTIZATION-AWARE NAS FOR VITS
3.1 Row-Wise Flexible Mixed-Precision
Quantization with Hardware/Software
Co-design
Figure 2 classifies quantization with different levels of granular-
ity. Model-wise quantization [ 7,68] uses a unified quantizationbit-width for the whole model and thus misses some quantization
opportunities. On the other hand, mixed-precision quantization, as
discussed in related work, explores more quantization potential (i.e.,
quantizing each component to a bit-width as low as possible) while
preserving the accuracy of the model. Specifically, layer-wise (inter-
layer) mixed-precision quantization [ 49,54] sets each layer with a
specific quantization bit-width. Besides that, Q-ViT [ 20] proposed
a head-wise mixed-precision quantization scheme, which assigns
different bit-widths to different attention heads. Both the layer-wise
and head-wise quantization schemes suffer from limited quantiza-
tion flexibility without considering the variance inside each layer.
Moreover, fixed row-wise (intra-layer) mixed-precision quantiza-
tion is proposed in prior work [ 40], which uses different quantiza-
tion bit-widths for different channels in each CNN layer and limits
the same mixed-precision ratio across different CNN layers, and
thus multiple layers can share the same hardware design, making
it more hardware-friendly. Finally, kernel-wise mixed-precision
quantization [ 29] assigns different quantization bit-widths down to
the kernel level, which greatly diversifies the computing pattern
and makes it inefficient to implement on hardware.
Based on the above discussion, we use the row-wise flexible
mixed-precision quantization scheme for ViTs, as shown in Fig-
ure 2(d), which preserves the quantization flexibility among layers
for better accuracy while maintaining the hardware uniformity for
more efficient implementation. Different from [ 40] that limits the
same mixed-precision ratio across CNN layers, for ViTs, we have to
provide the flexibility to obtain different mixed ratios in different
layers to maintain the model accuracy. To maintain hardware uni-
formity and avoid hardware under-utilization, we propose to design
the basic hardware units for the lower-bit computation, decompose
the higher-bit computation into lower-bit ones, and reuse the basic
hardware units (described in Section 4.2 and Section 4.3). As a re-
sult, we have preserved the uniformity of the hardware design and
enabled the flexible bit-width mixed-ratio among ViT layers. We
explain the hardware details in Section 4.
3.2 Intra-layer Mixed-Precision Weight
Entanglement
In classical one-shot NAS, the weights of each sample candidate
are shared with the supernet during training. However, as shown
in Figure 3 (a), when using the classical weight-sharing strategy,
the building blocks from multiple subnets, even in the same layer,
are isolated. Therefore, it leads to higher memory costs and slower
training convergence.
To address this problem, weight entanglement is proposed in [ 6]
to reduce the supernet model size: as shown in Figure 3 (b), different
transformer blocks can share their common weights in each layer. It
also allows each block to be updated more times than the previous
independent training strategy, thus achieving faster convergence.
However, this structure is hard to combine with mixed quantization
since one shared weight cannot be trained into two different bit-
widths at the same time (i.e., bit-width conflict).
In this paper, we propose the mixed-precision weight entangle-
ment, as shown in Figure 3 (c), to incorporate the quantization
search while preventing the potential bit-width conflicts problem
in the shared weight. Mixed-precision weight entanglement block
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Output
InputBlock-2
Block-1
Block-3dim (d - k) dim d dim (d + k)Output
Input
Block-2 dim d
Block-1
dim (d - k)
Block-3 dim (d + k)
Output
Input
Higher Precision Lower Precision dim d
dim aBlock dim d,
mixed-ratio (a/d)
(a) Classic Weight Sharing ... ...
(b) Original Weight Enanglement (c) Mixed-precision Weight Enanglement
Figure 3: Classic weight sharing and original weight entanglement versus our proposed mixed-precision weight entanglement.
contains two parts of weights with different precisions. Different
quantization mixed ratios can be achieved by extracting different
percentages of weights over these two parts. In the implementation,
for each layer, we only need to store the weights of the largest
of the𝑛homogeneous candidate blocks with both the 4-bit and
8-bit weights. The remaining smaller building blocks can extract
the weights directly from the largest building block. The different
quantization mixed ratios can be reached by moving the position
of the selected block.
3.3 Supernet Layer Scaling (SLS) Structure
The layer scaling structure proposed by CaiT [ 43] improves the
stability of the optimizations when training transformers for image
classification, thus improving the model accuracy. We explore this
structure and extend it to supernet layer scaling (SLS).
Layer scaling is a per-channel multiplication of the vector pro-
duced by each residual block. For ViT, this layer is deployed after
the multi-head self-attention (MSA) and multi-layer perceptron
(MLP) modules in each encoder block. The objective is to group the
updates of the weights associated with the same output channel.
Layer scaling can be denoted as a multiplication by a diagonal ma-
trixdiag 𝜆𝑙,1,...,𝜆𝑙,𝑑on the output of 𝑙-th residual block, where
𝑑is the corresponding number of output channels in the model. All
𝜆s are learnable weights.
To fit our mixed-precision weight entanglement strategy, dif-
ferent from the original CaiT [ 43] implementation that uses the
whole layer scaling in every training iteration, our SLS extracts the
corresponding elements synchronized with the output dimension
of the selected subnet while keeping the other weights frozen. As
shown in Figure 4, using the residual block of MLP as an example,
assuming that the current MLP’s output dimension starts from
𝑚-th channel and ends at 𝑛-th channel, the supernet layer scaling
computation can be formulated as:
𝑦𝑙=𝑥𝑙+diag 𝜆𝑙,𝑚,...,𝜆𝑙,𝑛×MLP(LN(𝑥𝑙)), (1)
where𝑥𝑙and𝑦𝑙denote the input and output, respectively; LN means
the layer normalization.
3.4 End-to-End Quasar-ViT Framework
3.4.1 One-shot NAS Algorithm. Our one-shot NAS algorithm con-
sists of two steps:
LN LN MLP
MSAOutput
SLSSLS
InputHidden Dimension Choice
Hidden Dimension Choiceλ1 0 ... 0 0 ... 0 ... 0
0 λ2 ... 0 0 ... 0 ... 0
... ... ... ... ... ... ... ... ...
0 0 ... λm 0 ... 0 ... 0
0 0 ... 0 λm+1 ... 0 ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... λ
n ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... 0 ... λ
d
Output dim:
1 m n dxlylFigure 4: Supernet layer scaling (SLS) in Quasar-ViT encoder
block. We use the SLS after MLP as an example.
•We train a supernet to directly sample different quantized
architectures as child models for training. The supernet is
trained with SLS and KD techniques. The search space is
encoded in the supernet, and the parameters of all candidate
networks in the search space are optimized simultaneously
by our proposed weight-sharing during training.
•We select architectures from the pre-trained supernet using
the hardware-oriented evolution search method to find the
most accurate model under the given hardware resource
constraints. We search based on the hardware latency/FPS
and resource modeling illustrated in Section 4.4.
Here, we show a toy example of the supernet training process
including candidate sampling and the corresponding searched re-
sults for different targeting FPS in Figure 5. Figure 5 (a) illustrates
one iteration of the supernet training process, where the pink area
indicates the sampled high precision values and the blue area indi-
cates the sampled low precision values in the supernet. The light
blue area indicates the frozen values (currently not sampled) in this
iteration. After the supernet training and the hardware-oriented
evolution search, we could obtain different models targeting dif-
ferent frames per second (FPS) as shown in Figure 5 (b). For the
ICS ’24, June 4–7, 2024, Kyoto, Japan
Layer-1
Layer-4
Layer-5
Layer-2Output
Layer-3
Layer-i
Input
+0.25 -0.50 +0.75 -0.50 +1.00 -1.00
+0.75 -0.25 -0.50 -0.50 +0.00 -1.00
+0.25 -0.25 -0.75 +0.50 +1.00 -0.50
+1.00 -0.75 +0.50 -0.50 +0.00 -1.00
-1.00 +0.25 -0.50 +0.50 -0.50 -0.50
+0.00 -0.25 +0.50 -0.50 +1.00 -1.00...Channel
... ...
L-3 L-2 L-1 R-1 R-2 R-3
High Precision Low Precision
(a) SuperNet Training Process (b) Different SubNets targeting different FPS after the searchOutput
Input...Output
Input...Output
Input...Target FPS-1
Target FPS-2
Target FPS-3Sampling for the training
Hardware-oriented
Evolution Search
Figure 5: SuperNet training process including candidate sampling and the searched results for different targeting FPS. We use a
model with layers of 6 channels as a toy example.
sake of brevity, we only show the quantized value here. The scaling
factor along with other related structures is omitted.
3.4.2 Search Space. We show our search space design in Table 2.
Our search components include the overall embedding dimension,
the number of transformer layers, the quantization mixed-ratio (i.e.,
the percentage of 8-bit weights mixed in the layer) for each linear
layer, and the hidden dimension and expansion ratio (for MLP) in
each ViT encoder block.
To accelerate the supernet training process and improve the
overall model performance, we partition the large-scale search
space into two sub-spaces and encode them into two independent
supernets for QUASAR-Small and QUASAR-Large, respectively. By
splitting and customizing search space for supernets of different
sizes, we mitigate the training interference caused by the huge
subnets’ difference. This training strategy has been proved in [ 66].
Such partition allows the search algorithm to concentrate on finding
models within a specific hardware inference latency, which can
be specialized by users according to their available resources and
application requirements. It also reduces gradient conflicts between
large and small sub-networks trained via weight-sharing due to
gaps in model sizes.
Table 2: An illustration of our search space: It is divided into
two independent supernets within the different parameter
ranges to satisfy different resource constraints.
QUASAR-Small QUASAR-Large
Embed Dimension (192, 216, 240) (320, 384, 448)
Hidden Dimension (192, 256) (320, 384, 448)
8-bit Mixed-ratio (0%, 25%, 50%) (0%, 25%, 50%)
Expansion Ratio (3.5, 4) (3, 3.5, 4)
Number of Layers (12,13,14) (12,13,14)
3.4.3 Supernet Training. In each iteration, we randomly select a
quantized ViT architecture from the search space. Then we obtain
its weights from the supernet and compute the losses of the subnet.Algorithm 1 Supernet Training.
Input: Training epochs 𝑁, search spaceP, supernetS, loss
function𝐿, train dataset 𝐷𝑡𝑟𝑎𝑖𝑛 , initial supernet weights WP,
candidate weightsW𝑝
for𝑖in𝑁epochs do
fordata, labels in 𝐷𝑡𝑟𝑎𝑖𝑛 do
Randomly sample one quantized ViT architecture from
search spaceP
Obtain the corresponding weights W𝑝from supernetWP
Compute the gradients based on 𝐿
Update the corresponding part of W𝑝inWPwhile freezing
the rest of the supernet S
end for
end for
OutputS
Finally, we update the corresponding weights with the remaining
weights frozen. The architecture search space 𝑃is encoded in a
supernet denoted as S(𝑃,𝑊𝑃), where𝑊𝑃is the weight of the super-
net that is shared across all the candidate architectures. Algorithm 1
illustrates the training procedure of our supernet.
3.5 Hardware-Oriented Evolution Search
In our hardware-oriented evolution search for crossover, two ran-
dom candidate architectures are first picked from the top candidates.
Then we uniformly choose one block from them in each layer to
generate a new architecture. For mutation, a candidate mutates its
depth with probability 𝑃𝑑first. Then it mutates each block with a
probability of 𝑃𝑚to produce a new architecture. Newly produced
architectures that do not satisfy the constraints will not be added
for the next generation. To evaluate the candidates, we perform
hardware latency and resource modeling based on the proposed
row-wise flexible mixed-precision quantization scheme. The details
of the modeling have been discussed in Section 4.4.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
3.6 Integration with Knowledge Distillation
(KD)
To demonstrate the compatibility of our proposed framework with
knowledge distillation (KD) and further improve the accuracy of
our supernet, we also integrate KD [ 15] in our training process. We
use the pre-trained RegNetY-32G [ 34] with 83.6% top-1 accuracy as
different teacher models. We also apply the soft distillation method.
Soft distillation [ 15] minimizes the Kullback-Leibler divergence
between the softmax of the teacher and the softmax of the student
model. The distillation loss is:
𝐿𝑠𝑜𝑓𝑡=(1−𝛼)𝐿𝐶𝐸(𝜓(𝑍𝑠),𝑦)+𝛼𝜏2𝐿𝐾𝐿(𝜓(𝑍𝑠
𝜏),𝜓(𝑍𝑡
𝜏)),(2)
where𝑍𝑡and𝑍𝑠are the logits of the teacher and student models,
respectively. 𝜓is the softmax function. 𝜏is the temperature for
the distillation, 𝛼is the coefficient balancing the Kullback–Leibler
divergence loss ( 𝐿𝐾𝐿), and the cross-entropy ( 𝐿𝐶𝐸) on the ground
truth labels 𝑦in the distillation.
4 FPGA HARDWARE DESIGN FOR
QUASAR-VIT
4.1 Overall Hardware Design for Quasar-ViT
Figure 6 presents the overall hardware architecture of the Quasar-
ViT accelerator on the ARM-FPGA platform. Below is how each
module in ViT is mapped to the hardware in Figure 6. The most
time-consuming MSA and MLP modules are accelerated by our
GEMM engine on the FPGA, which is similar to the recent Auto-
ViT-Acc work [ 22]. The lightweight SLS modules right after MSA
and MLP layers are also accelerated on the FPGA to avoid time-
consuming execution on the ARM CPU. The less time-consuming
modules including layer normalization and activation functions
(i.e., Softmax or GELU) are executed on the ARM CPU, due to their
complex structure for FPGA implementation. The hardware engines
on the FPGA and software modules on the ARM CPU exchange
data via the shared off-chip memory.
FPGA
CPU
LayerNorm
GELU
Softmax
Memory
Controller
Off-Chip
DDR MemoryControl LogicGEMM Engine
PE
SLSOutput Buf ferPing-Pong
BufferPing-Pong
BufferPE PE
PE PE PE
PE PE PEInput &
Weight
Figure 6: Quasar-ViT hardware architecture.
As previously mentioned, we mainly focus on the most time-
consuming GEMM engine design. Due to the limited on-chip mem-
ory capacity and computing resource on the FPGA, for each ViT
layer (i.e., MSA and MLP), our GEMM engine processes the input,
weight, and output data in tiles: a small tile of the input (tokens)
and weight of each ViT layer are first loaded from the off-chipDDR memory to the on-chip buffers, then they are processed by
the GEMM engine all on-chip. To improve the performance, the
double buffering technique is applied again to overlap the off-chip
memory accesses and GEMM computation, shown in Figure 6.
Next, we present our design of the basic hardware units in the
GEMM engine and the corresponding DSP (digital signal processor)
packing optimization, as well as the hardware resource and latency
modeling for the tiled GEMM design.
4.2 Unification of Atomic Computation
One major challenge in the FPGA accelerator design is to efficiently
support flexible mixed ratios of different bit-width computations
across ViT layers. On one hand, putting multiple copies of hardware
accelerator designs for each mixed-ratio (i.e., each layer) simultane-
ously on the FPGA leads to severe hardware resource contention
and under-utilization, since layers are executed sequentially. On
the other hand, pre-synthesizing multiple copies of hardware accel-
erator designs for each layer and reconfiguring the FPGA for each
layer incurs significant FPGA reconfiguration overhead.
Inspired by the approach proposed in QGTC [ 52] to support
arbitrary bit-width computation for quantized graph neural net-
works on GPUs, in our FPGA hardware design, we unify the basic
processing elements to process 4-bit weight atomic computations
and construct the 8-bit weight data computations using two 4-bit
weight data operations as such: for multiplication between an N-bit
activation value ( 𝑎𝑐𝑡𝑁) and an 8-bit weight value ( 𝑤𝑔𝑡 8), we derive
the corresponding product as:
𝑎𝑐𝑡𝑁·𝑤𝑔𝑡 8=𝑎𝑐𝑡𝑁·𝑤𝑔𝑡ℎ4<<4+𝑎𝑐𝑡𝑁·𝑤𝑔𝑡𝑙4, (3)
where𝑤𝑔𝑡ℎ4and𝑤𝑔𝑡𝑙4represent the higher and lower 4-bit data
of𝑤𝑔𝑡 8, respectively. The multiplication result between 𝑎𝑐𝑡𝑁and
𝑤𝑔𝑡ℎ4are left shifted by 4 bits.
Based on this unification, we propose hybrid signed/unsigned
DSP packing to handle the 4-bit weight atomic computation.
4.3 Proposed Hybrid Signed/Unsigned DSP
Packing
To fully exploit the potential of DSP resources on FPGAs, we pack
multiple low-bit multiplications within each DSP block follow-
ing [57,58]. Each DSP block (DSP48E2) on the AMD/Xilinx ZCU102
FPGA board could support the computation of 𝑃=(𝐴+𝐷)×𝐵, where
both𝐴and𝐷are 27-bit operands, 𝐵is an 18-bit operand, and 𝑃is
the 45-bit output. In our study, we explore the following two DSP
packing schemes and discuss their design trade-offs. The activation
bit-width𝑁is set to 6 to fully exploit the DSP for computation.
•Packing factor 3 (3 weights sharing 1 activation). In
Figure 7 (a), three 4×6-bit multiplications are packed into a
single DSP block, by holding one 6-bit signed activation in
port𝐵and three 4-bit weight values in port 𝐷. To pack three
weights into a single 27-bit port 𝐷, look-up tables (LUTs)
are utilized to first combine two weights and then integrate
them with the third weight data. With this DSP packing
scheme, for the W4A6 (i.e., 4-bit weight and 6-bit activation)
computation, we could pack three 4-bit weights that share
the same activation. And for the W8A6 computation, we
could use two DSPs to process the upper and lower 4-bit
ICS ’24, June 4–7, 2024, Kyoto, Japan
of three 8-bit weights in parallel. Note that after the 8-bit
weights are decomposed into two 4-bit weights, only the
upper 4-bit weights contain the sign bits and should be sign-
extended (required by DSP for output correctness [ 57,58]),
the lower 4-bit weights should be treated as unsigned values.
•Packing factor 4 (2 weights sharing 2 activations). In
Figure 7 (b), four 4×6-bit multiplications are packed into
a single DSP block, by holding two 6-bit signed activation
values in port 𝐷and two 4-bit weights in port 𝐵. It is worth
mentioning the port placement of the activation and weight
values are swapped from the packing factor 3 scheme, to
increase the packing strength. With this DSP packing scheme,
for the W4A6 computation, we could pack a pair of two 4-
bit weights that share the same pair of activation values.
And for the W8A6 computation, a similar technique as the
previous packing scheme is used to separately handle the
upper and lower 4-bit values of an 8-bit weight. Again for the
two decomposed 4-bit weights, only the upper 4-bit weights
contain the sign bit and should be sign-extended (required
by DSP for output correctness [ 57,58]), but the lower 4-bit
weights should be treated as unsigned values.
4.4 Hardware Resource and Latency Modeling
Here, we present our hardware resource and latency modeling used
in the hardware-oriented evolution search.
Table 3: Notations for Quasar-ViT accelerator
Notation Description
𝑀(𝑁) Number of output (input) channels
𝐹 Number of token sequences
𝑇𝑛 Tiling size for data in input channel dimension for
each head
𝑇𝑚 Tiling size for data in output channel dimension
𝑁ℎ Total number of heads
𝑃𝐹 Parallel factor along the number of tokens
𝐷𝑎𝑐𝑡 Number of data packed as one for activations
𝐷𝑤𝑔𝑡 Number of data packed as one for weights
𝐴in (𝐴out,
𝐴wgt)Number of AXI ports used for data transfer of input
(output, weight) tile
𝐿in (𝐿wgt,
𝐿out,𝐿cmpt)Number of clock cycles for input transfer (weight
transfer, output transfer, computation) for a tile
𝑆dsp(𝑆lut) Available number of DSPs (LUTs) on FPGA
𝐶dsp DSP cost for each MAC operation
𝐶lut LUT cost for each MAC operation
𝐶𝑑𝑠𝑝
𝑙𝑢𝑡Number of LUTs used by a multiplication executed
on DSPs
𝑁𝑑𝑠𝑝 Number of multiplication executed on DSPs
𝑁𝑙𝑢𝑡 Number of multiplication executed on LUTs
𝑁𝑡𝑜𝑡 The total number of multiplication on FPGA
𝛾𝑑𝑠𝑝(𝛾𝑙𝑢𝑡) DSP (LUT) utilization threshold
𝑓 FPGA accelerator frequency
𝐹𝑃𝑆 Frames per second
4.4.1 Resource Modeling. To help guide the neural architecture
search, we provide details of the resource and latency models ofour FPGA accelerator design (mainly the GEMM engine). Table 3
lists the notations used in our models. We design our FPGA accel-
erator to fully leverage the available FPGA computing resources
(i.e., DSPs and LUTs), on-chip memory (i.e., BRAMs), and off-chip
memory bandwidth. To fully exploit the computing capability with
the available hardware resources, We maximize the total number of
parallel basic hardware compute units using both DSPs (i.e., 𝑁𝑑𝑠𝑝)
and LUTs (i.e., 𝑁𝑙𝑢𝑡) for the datapath of our accelerator as
𝑁𝑡𝑜𝑡=maximize
𝑁𝑑𝑠𝑝+𝑁𝑙𝑢𝑡
, (4)
while satisfying the following resource constraints
𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝≤𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝, (5)
𝑁𝑙𝑢𝑡·𝐶𝑙𝑢𝑡+𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡, (6)
where constraints 5 and 6 bound the DSP and LUT utilization to
be under the allowable thresholds, i.e., 𝛾𝑑𝑠𝑝and𝛾𝑙𝑢𝑡with the total
resource amounts denoted by 𝑆𝑑𝑠𝑝and𝑆𝑙𝑢𝑡. The hardware costs of
each multiplication implementation are denoted as 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡.
In order to choose the best implementation method for the basic
hardware units of our design, we characterize the FPGA resource
consumption using Xilinx Vivado 2020.1 [ 59] for the three cases in
Table 4, i.e., (a) multiplications executed on DSPs with packing fac-
tor of 3, (b) multiplications executed on DSPs with packing factor of
4, and (c) multiplications executed purely using LUTs. As observed
in Table 4, we derive the hardware costs of each multiplication
implementation, particularly, the LUT costs for pure-LUT-based
and DSP-based methods correspond to 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡. Note that the
DSP-based approach also consumes LUTs, due to data packing on
the input operands and output data construction operations, such
as bit shifting and data accumulation. Regarding the efficiency
lost by decomposing 8-bit to 4-bit, for the composed W8A6 com-
putation, on average, we can achieve one computation with 25.8
LUTs and 0.5 DSP or purely 66.7 LUTs. In contrast, direct W8A6
computation used in [ 40] (i.e., packing two W8A6 operations within
one DSP method) requires 21.5 LUTs and 0.5 DSP or purely 62.2
LUTs. Since most of the weights are in 4-bit, using decomposing
does not affect the overall performance much by a slight increase
in the LUT utilization. In terms of the efficiency of DSP packing, a
single DSP can pack four W4A6 operations at most theoretically,
which is achieved by our approach.
For the LUT usage, shown in Table 4, we have:
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡<𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡<𝐶𝑙𝑢𝑡. (7)
In the final implementation, regarding which DSP packing scheme
to use and whether to use the pure-LUT-based method for the basic
hardware compute units, there are several situations according to
the available FPGA resources.
Situation-1: When𝑆𝑙𝑢𝑡is limited and insufficient to hold the
LUT consumption of full utilization of DSP packing with a factor
of 3, denoted as:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡. (8)
In this case, to fully utilize the computation resources, we directly
allocate DSP-based computations with a packing factor of 3 as much
as possible until we reach the LUT resource limit.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
Activation 6-bit
Weight 4-bitWeight 4-bit
Activation 6-bit = +Weight 8-bit
Signed number unsigned number
(a) Packing Factor of 3
(b) Packing Factor of 4
Figure 7: Illustration of DSP multiplication packing schemes for (a) 3 weights sharing 1 activation with packing factor of 3, and
(b) 2 weights sharing 2 activations with packing factor of 4.
Table 4: FPGA resource consumption for a single DSP-based
or LUT-based basic hardware compute unit. W4A6 denotes
4-bit weight and 6-bit activation; W8A6 denotes 8-bit weight
and 6-bit activation.
pure LUT-basedDSP-based
packing
factor 3packing
factor 4
W4A6𝐶𝐿𝑈𝑇 33.3 10.9 12.9
𝐶𝐷𝑆𝑃 0 0.33 0.25
W8A6𝐶𝐿𝑈𝑇 66.7 21.9 25.8
𝐶𝐷𝑆𝑃 0 0.67 0.5
W8A6
(direct)𝐶𝐿𝑈𝑇 62.2 21.5
𝐶𝐷𝑆𝑃 0 0.5
Situation-2: When𝑆𝑙𝑢𝑡is enough to hold all the LUT consump-
tion from DSP packing with the factor of 4, satisfying:
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡. (9)
Based on Eq. 4, 5, 6 and 9, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
(4·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡−3·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡·𝐶𝑙𝑢𝑡.
(10)
If it does not satisfy Eq. 10, we perform DSP-based computations
with a packing factor of 3. Besides that, for the remaining available
LUT resources, pure-LUT-based computation is also conducted in
both cases.
Situation-3: When𝑆𝑙𝑢𝑡is between the LUT demands by fully
deploying DSP computations with packing factors of 3 and 4, satis-
fying:
3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡.(11)
Based on Eq. 4, 5, 6, and 11, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡+3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·(𝐶𝑙𝑢𝑡−𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)
𝐶𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡,
(12)
Input Sequence
Load Input T ile
Output Sequence
StoreOutput T ile Weight Matrix
LoadWeight T ile Figure 8: Data tiling in ViT computations.
In this case, we conduct only DSP-based computations with a
packing factor of 4. Otherwise, if it does not satisfy Eq. 12, we per-
form DSP-based computations with a packing factor of 3 and pure
LUT-based computation for the remaining available LUT resource.
4.4.2 Latency Modeling. As discussed in the Hardware Design Sec-
tion, our GEMM hardware engine accelerates the major MSA and
MLP modules and processes their input, weight, and output data in
tiles, as shown in Figure 8. our GEMM hardware engine accelerates
the major MSA and MLP modules and processes their input, weight,
and output data in tiles, as shown in Figure 8. Each MSA can be
seen as multiple parallel matrix multiplications. The accelerator is
designed to process parallel computations within each head. This
input channel splitting is also done for fully connected (FC) layers,
each containing one matrix multiplication for compatibility, and
the results need to be accumulated from all the input channels
in all the heads. Furthermore, the computing engine exploits fine-
grained data and operation parallelisms and can process 𝑇𝑚·𝑇𝑛
multiply-accumulate (MAC) operations in parallel.
ICS ’24, June 4–7, 2024, Kyoto, Japan
We model the inference latency of our hardware design based
on the number of clock cycles. For a layer 𝑖in ViT, since data
packing can be used to transfer multiple (i.e., 𝐷𝑎𝑐𝑡or𝐷𝑤𝑔𝑡) values
at the same time in each AXI port, the clock cycles for loading one
input/weight tile and storing one output tile, are calculated as:
𝐿in=𝑇𝑛
𝐷𝑎𝑐𝑡
·𝐹
𝐴in
,
𝐿wgt=𝑇𝑛
𝐷𝑤𝑔𝑡
·𝑇𝑚
𝐴wgt
,
𝐿out=𝑇𝑚
𝐷𝑎𝑐𝑡
·𝐹
𝐴out
,(13)
where𝐿in,𝐿wgtand𝐿outindicate the number of the clock cycles
of input, weight, and output transfer for one corresponding tile,
respectively.
The clock cycle number to compute one tile is
𝐿cmpt=max𝐹
𝑃𝐹
,𝑇𝑛·𝑇𝑚·𝐹
𝑁𝑡𝑜𝑡
, (14)
where the first term is calculated by the latency model. The total
number of multiplications needed to compute one tile of matrix
multiplication is 𝑇𝑛·𝑇𝑚·𝐹. Each tile has two levels of parallelism:
one is along the 𝑇𝑛and𝑇𝑚dimension and the parallel factor is
𝑇𝑛·𝑇𝑚(i.e., fully parallel); and the other is along the 𝐹dimension
and the parallel factor is 𝑃𝐹. Therefore, the first term is calculated asl
𝐹
𝑃𝐹m
. The second term is limited by the resource constraint, where
we can support at most 𝑁𝑡𝑜𝑡parallel multipliers (Eq. 4) due to the
resource constraint.
With the double buffers overlapping the data loading and com-
putation of the tiles, the overall clock cycle number for processing
one tile is𝐿1=max{𝐿in,𝐿wgt,𝐿cmpt}.
To obtain the accumulation of output results, this process is
performed multiple times (i.e., processingl
𝑁
𝑇𝑛m
input tiles). The
clock cycle number for calculating the whole output tile is 𝐿2=
max
𝐿1·l
𝑁
𝑇𝑛m
+𝐿cmpt,𝐿out
.
Since there arel
𝑀
𝑇𝑚m
number of output tiles, the total number of
clock cycles for a ViT layer 𝑖is described by
𝐿𝑖
tot=𝑀
𝑇𝑚
·𝐿2+𝐿out. (15)
Under a working frequency 𝑓, the FPSis calculated as:
𝐹𝑃𝑆=𝑓Í
𝑖𝐿𝑖
tot. (16)
5 EXPERIMENTAL RESULTS
5.1 | Experimental Setup
Our supernet training process takes 700 epochs with a batch size of
2048. The learning rate is set to 5×10−4initially and decayed with
a cosine annealing schedule. The AdamW [ 28] optimizer is used
with the epsilon value of 1𝑒−8and weight decay of 0.05. Additional
training optimizations, such as warmup and label smoothing are
performed during training. The number of warmup epochs and
label smoothing factor are set as 20 and 0.1, respectively. After
supernet training, we perform the hardware-oriented evolution
search, without subnet retraining.Our training is conducted on 8 NVIDIA Ampere A100 GPUs
with CUDA 11.0 and PyTorch 1.7 frameworks on the Ubuntu oper-
ating system. To test the effectiveness of our framework, we also
implement Quasar-ViT framework on the Xilinx ZCU102 embedded
FPGA platform with quad-core ARM Cortex-A53 and XCZU9EG
FPGA chip. The FPGA working frequency is set to 150 MHz for all
the designs implemented via Xilinx Vitis and Vitis HLS 2020.1.
5.2 Accuracy | Section not found | Section not found | results for different targeting FPS. We use a
model with layers of 6 channels as a toy example.
sake of brevity, we only show the quantized value here. The scaling
factor along with other related structures is omitted.
3.4.2 Search Space. We show our search space design in Table 2.
Our search components include the overall embedding dimension,
the number of transformer layers, the quantization mixed-ratio (i.e.,
the percentage of 8-bit weights mixed in the layer) for each linear
layer, and the hidden dimension and expansion ratio (for MLP) in
each ViT encoder block.
To accelerate the supernet training process and improve the
overall model performance, we partition the large-scale search
space into two sub-spaces and encode them into two independent
supernets for QUASAR-Small and QUASAR-Large, respectively. By
splitting and customizing search space for supernets of different
sizes, we mitigate the training interference caused by the huge
subnets’ difference. This training strategy has been proved in [ 66].
Such partition allows the search algorithm to concentrate on finding
models within a specific hardware inference latency, which can
be specialized by users according to their available resources and
application requirements. It also reduces gradient conflicts between
large and small sub-networks trained via weight-sharing due to
gaps in model sizes.
Table 2: An illustration of our search space: It is divided into
two independent supernets within the different parameter
ranges to satisfy different resource constraints.
QUASAR-Small QUASAR-Large
Embed Dimension (192, 216, 240) (320, 384, 448)
Hidden Dimension (192, 256) (320, 384, 448)
8-bit Mixed-ratio (0%, 25%, 50%) (0%, 25%, 50%)
Expansion Ratio (3.5, 4) (3, 3.5, 4)
Number of Layers (12,13,14) (12,13,14)
3.4.3 Supernet Training. In each iteration, we randomly select a
quantized ViT architecture from the search space. Then we obtain
its weights from the supernet and compute the losses of the subnet.Algorithm 1 Supernet Training.
Input: Training epochs 𝑁, search spaceP, supernetS, loss
function𝐿, train dataset 𝐷𝑡𝑟𝑎𝑖𝑛 , initial supernet weights WP,
candidate weightsW𝑝
for𝑖in𝑁epochs do
fordata, labels in 𝐷𝑡𝑟𝑎𝑖𝑛 do
Randomly sample one quantized ViT architecture from
search spaceP
Obtain the corresponding weights W𝑝from supernetWP
Compute the gradients based on 𝐿
Update the corresponding part of W𝑝inWPwhile freezing
the rest of the supernet S
end for
end for
OutputS
Finally, we update the corresponding weights with the remaining
weights frozen. The architecture search space 𝑃is encoded in a
supernet denoted as S(𝑃,𝑊𝑃), where𝑊𝑃is the weight of the super-
net that is shared across all the candidate architectures. Algorithm 1
illustrates the training procedure of our supernet.
3.5 Hardware-Oriented Evolution Search
In our hardware-oriented evolution search for crossover, two ran-
dom candidate architectures are first picked from the top candidates.
Then we uniformly choose one block from them in each layer to
generate a new architecture. For mutation, a candidate mutates its
depth with probability 𝑃𝑑first. Then it mutates each block with a
probability of 𝑃𝑚to produce a new architecture. Newly produced
architectures that do not satisfy the constraints will not be added
for the next generation. To evaluate the candidates, we perform
hardware latency and resource modeling based on the proposed
row-wise flexible mixed-precision quantization scheme. The details
of the modeling have been discussed in Section 4.4.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
3.6 Integration with Knowledge Distillation
(KD)
To demonstrate the compatibility of our proposed framework with
knowledge distillation (KD) and further improve the accuracy of
our supernet, we also integrate KD [ 15] in our training process. We
use the pre-trained RegNetY-32G [ 34] with 83.6% top-1 accuracy as
different teacher models. We also apply the soft distillation method.
Soft distillation [ 15] minimizes the Kullback-Leibler divergence
between the softmax of the teacher and the softmax of the student
model. The distillation loss is:
𝐿𝑠𝑜𝑓𝑡=(1−𝛼)𝐿𝐶𝐸(𝜓(𝑍𝑠),𝑦)+𝛼𝜏2𝐿𝐾𝐿(𝜓(𝑍𝑠
𝜏),𝜓(𝑍𝑡
𝜏)),(2)
where𝑍𝑡and𝑍𝑠are the logits of the teacher and student models,
respectively. 𝜓is the softmax function. 𝜏is the temperature for
the distillation, 𝛼is the coefficient balancing the Kullback–Leibler
divergence loss ( 𝐿𝐾𝐿), and the cross-entropy ( 𝐿𝐶𝐸) on the ground
truth labels 𝑦in the distillation.
4 FPGA HARDWARE DESIGN FOR
QUASAR-VIT
4.1 Overall Hardware Design for Quasar-ViT
Figure 6 presents the overall hardware architecture of the Quasar-
ViT accelerator on the ARM-FPGA platform. Below is how each
module in ViT is mapped to the hardware in Figure 6. The most
time-consuming MSA and MLP modules are accelerated by our
GEMM engine on the FPGA, which is similar to the recent Auto-
ViT-Acc work [ 22]. The lightweight SLS modules right after MSA
and MLP layers are also accelerated on the FPGA to avoid time-
consuming execution on the ARM CPU. The less time-consuming
modules including layer normalization and activation functions
(i.e., Softmax or GELU) are executed on the ARM CPU, due to their
complex structure for FPGA implementation. The hardware engines
on the FPGA and software modules on the ARM CPU exchange
data via the shared off-chip memory.
FPGA
CPU
LayerNorm
GELU
Softmax
Memory
Controller
Off-Chip
DDR MemoryControl LogicGEMM Engine
PE
SLSOutput Buf ferPing-Pong
BufferPing-Pong
BufferPE PE
PE PE PE
PE PE PEInput &
Weight
Figure 6: Quasar-ViT hardware architecture.
As previously mentioned, we mainly focus on the most time-
consuming GEMM engine design. Due to the limited on-chip mem-
ory capacity and computing resource on the FPGA, for each ViT
layer (i.e., MSA and MLP), our GEMM engine processes the input,
weight, and output data in tiles: a small tile of the input (tokens)
and weight of each ViT layer are first loaded from the off-chipDDR memory to the on-chip buffers, then they are processed by
the GEMM engine all on-chip. To improve the performance, the
double buffering technique is applied again to overlap the off-chip
memory accesses and GEMM computation, shown in Figure 6.
Next, we present our design of the basic hardware units in the
GEMM engine and the corresponding DSP (digital signal processor)
packing optimization, as well as the hardware resource and latency
modeling for the tiled GEMM design.
4.2 Unification of Atomic Computation
One major challenge in the FPGA accelerator design is to efficiently
support flexible mixed ratios of different bit-width computations
across ViT layers. On one hand, putting multiple copies of hardware
accelerator designs for each mixed-ratio (i.e., each layer) simultane-
ously on the FPGA leads to severe hardware resource contention
and under-utilization, since layers are executed sequentially. On
the other hand, pre-synthesizing multiple copies of hardware accel-
erator designs for each layer and reconfiguring the FPGA for each
layer incurs significant FPGA reconfiguration overhead.
Inspired by the approach proposed in QGTC [ 52] to support
arbitrary bit-width computation for quantized graph neural net-
works on GPUs, in our FPGA hardware design, we unify the basic
processing elements to process 4-bit weight atomic computations
and construct the 8-bit weight data computations using two 4-bit
weight data operations as such: for multiplication between an N-bit
activation value ( 𝑎𝑐𝑡𝑁) and an 8-bit weight value ( 𝑤𝑔𝑡 8), we derive
the corresponding product as:
𝑎𝑐𝑡𝑁·𝑤𝑔𝑡 8=𝑎𝑐𝑡𝑁·𝑤𝑔𝑡ℎ4<<4+𝑎𝑐𝑡𝑁·𝑤𝑔𝑡𝑙4, (3)
where𝑤𝑔𝑡ℎ4and𝑤𝑔𝑡𝑙4represent the higher and lower 4-bit data
of𝑤𝑔𝑡 8, respectively. The multiplication result between 𝑎𝑐𝑡𝑁and
𝑤𝑔𝑡ℎ4are left shifted by 4 bits.
Based on this unification, we propose hybrid signed/unsigned
DSP packing to handle the 4-bit weight atomic computation.
4.3 Proposed Hybrid Signed/Unsigned DSP
Packing
To fully exploit the potential of DSP resources on FPGAs, we pack
multiple low-bit multiplications within each DSP block follow-
ing [57,58]. Each DSP block (DSP48E2) on the AMD/Xilinx ZCU102
FPGA board could support the computation of 𝑃=(𝐴+𝐷)×𝐵, where
both𝐴and𝐷are 27-bit operands, 𝐵is an 18-bit operand, and 𝑃is
the 45-bit output. In our study, we explore the following two DSP
packing schemes and discuss their design trade-offs. The activation
bit-width𝑁is set to 6 to fully exploit the DSP for computation.
•Packing factor 3 (3 weights sharing 1 activation). In
Figure 7 (a), three 4×6-bit multiplications are packed into a
single DSP block, by holding one 6-bit signed activation in
port𝐵and three 4-bit weight values in port 𝐷. To pack three
weights into a single 27-bit port 𝐷, look-up tables (LUTs)
are utilized to first combine two weights and then integrate
them with the third weight data. With this DSP packing
scheme, for the W4A6 (i.e., 4-bit weight and 6-bit activation)
computation, we could pack three 4-bit weights that share
the same activation. And for the W8A6 computation, we
could use two DSPs to process the upper and lower 4-bit
ICS ’24, June 4–7, 2024, Kyoto, Japan
of three 8-bit weights in parallel. Note that after the 8-bit
weights are decomposed into two 4-bit weights, only the
upper 4-bit weights contain the sign bits and should be sign-
extended (required by DSP for output correctness [ 57,58]),
the lower 4-bit weights should be treated as unsigned values.
•Packing factor 4 (2 weights sharing 2 activations). In
Figure 7 (b), four 4×6-bit multiplications are packed into
a single DSP block, by holding two 6-bit signed activation
values in port 𝐷and two 4-bit weights in port 𝐵. It is worth
mentioning the port placement of the activation and weight
values are swapped from the packing factor 3 scheme, to
increase the packing strength. With this DSP packing scheme,
for the W4A6 computation, we could pack a pair of two 4-
bit weights that share the same pair of activation values.
And for the W8A6 computation, a similar technique as the
previous packing scheme is used to separately handle the
upper and lower 4-bit values of an 8-bit weight. Again for the
two decomposed 4-bit weights, only the upper 4-bit weights
contain the sign bit and should be sign-extended (required
by DSP for output correctness [ 57,58]), but the lower 4-bit
weights should be treated as unsigned values.
4.4 Hardware Resource and Latency Modeling
Here, we present our hardware resource and latency modeling used
in the hardware-oriented evolution search.
Table 3: Notations for Quasar-ViT accelerator
Notation Description
𝑀(𝑁) Number of output (input) channels
𝐹 Number of token sequences
𝑇𝑛 Tiling size for data in input channel dimension for
each head
𝑇𝑚 Tiling size for data in output channel dimension
𝑁ℎ Total number of heads
𝑃𝐹 Parallel factor along the number of tokens
𝐷𝑎𝑐𝑡 Number of data packed as one for activations
𝐷𝑤𝑔𝑡 Number of data packed as one for weights
𝐴in (𝐴out,
𝐴wgt)Number of AXI ports used for data transfer of input
(output, weight) tile
𝐿in (𝐿wgt,
𝐿out,𝐿cmpt)Number of clock cycles for input transfer (weight
transfer, output transfer, computation) for a tile
𝑆dsp(𝑆lut) Available number of DSPs (LUTs) on FPGA
𝐶dsp DSP cost for each MAC operation
𝐶lut LUT cost for each MAC operation
𝐶𝑑𝑠𝑝
𝑙𝑢𝑡Number of LUTs used by a multiplication executed
on DSPs
𝑁𝑑𝑠𝑝 Number of multiplication executed on DSPs
𝑁𝑙𝑢𝑡 Number of multiplication executed on LUTs
𝑁𝑡𝑜𝑡 The total number of multiplication on FPGA
𝛾𝑑𝑠𝑝(𝛾𝑙𝑢𝑡) DSP (LUT) utilization threshold
𝑓 FPGA accelerator frequency
𝐹𝑃𝑆 Frames per second
4.4.1 Resource Modeling. To help guide the neural architecture
search, we provide details of the resource and latency models ofour FPGA accelerator design (mainly the GEMM engine). Table 3
lists the notations used in our models. We design our FPGA accel-
erator to fully leverage the available FPGA computing resources
(i.e., DSPs and LUTs), on-chip memory (i.e., BRAMs), and off-chip
memory bandwidth. To fully exploit the computing capability with
the available hardware resources, We maximize the total number of
parallel basic hardware compute units using both DSPs (i.e., 𝑁𝑑𝑠𝑝)
and LUTs (i.e., 𝑁𝑙𝑢𝑡) for the datapath of our accelerator as
𝑁𝑡𝑜𝑡=maximize
𝑁𝑑𝑠𝑝+𝑁𝑙𝑢𝑡
, (4)
while satisfying the following resource constraints
𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝≤𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝, (5)
𝑁𝑙𝑢𝑡·𝐶𝑙𝑢𝑡+𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡, (6)
where constraints 5 and 6 bound the DSP and LUT utilization to
be under the allowable thresholds, i.e., 𝛾𝑑𝑠𝑝and𝛾𝑙𝑢𝑡with the total
resource amounts denoted by 𝑆𝑑𝑠𝑝and𝑆𝑙𝑢𝑡. The hardware costs of
each multiplication implementation are denoted as 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡.
In order to choose the best implementation method for the basic
hardware units of our design, we characterize the FPGA resource
consumption using Xilinx Vivado 2020.1 [ 59] for the three cases in
Table 4, i.e., (a) multiplications executed on DSPs with packing fac-
tor of 3, (b) multiplications executed on DSPs with packing factor of
4, and (c) multiplications executed purely using LUTs. As observed
in Table 4, we derive the hardware costs of each multiplication
implementation, particularly, the LUT costs for pure-LUT-based
and DSP-based methods correspond to 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡. Note that the
DSP-based approach also consumes LUTs, due to data packing on
the input operands and output data construction operations, such
as bit shifting and data accumulation. Regarding the efficiency
lost by decomposing 8-bit to 4-bit, for the composed W8A6 com-
putation, on average, we can achieve one computation with 25.8
LUTs and 0.5 DSP or purely 66.7 LUTs. In contrast, direct W8A6
computation used in [ 40] (i.e., packing two W8A6 operations within
one DSP method) requires 21.5 LUTs and 0.5 DSP or purely 62.2
LUTs. Since most of the weights are in 4-bit, using decomposing
does not affect the overall performance much by a slight increase
in the LUT utilization. In terms of the efficiency of DSP packing, a
single DSP can pack four W4A6 operations at most theoretically,
which is achieved by our approach.
For the LUT usage, shown in Table 4, we have:
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡<𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡<𝐶𝑙𝑢𝑡. (7)
In the final implementation, regarding which DSP packing scheme
to use and whether to use the pure-LUT-based method for the basic
hardware compute units, there are several situations according to
the available FPGA resources.
Situation-1: When𝑆𝑙𝑢𝑡is limited and insufficient to hold the
LUT consumption of full utilization of DSP packing with a factor
of 3, denoted as:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡. (8)
In this case, to fully utilize the computation resources, we directly
allocate DSP-based computations with a packing factor of 3 as much
as possible until we reach the LUT resource limit.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
Activation 6-bit
Weight 4-bitWeight 4-bit
Activation 6-bit = +Weight 8-bit
Signed number unsigned number
(a) Packing Factor of 3
(b) Packing Factor of 4
Figure 7: Illustration of DSP multiplication packing schemes for (a) 3 weights sharing 1 activation with packing factor of 3, and
(b) 2 weights sharing 2 activations with packing factor of 4.
Table 4: FPGA resource consumption for a single DSP-based
or LUT-based basic hardware compute unit. W4A6 denotes
4-bit weight and 6-bit activation; W8A6 denotes 8-bit weight
and 6-bit activation.
pure LUT-basedDSP-based
packing
factor 3packing
factor 4
W4A6𝐶𝐿𝑈𝑇 33.3 10.9 12.9
𝐶𝐷𝑆𝑃 0 0.33 0.25
W8A6𝐶𝐿𝑈𝑇 66.7 21.9 25.8
𝐶𝐷𝑆𝑃 0 0.67 0.5
W8A6
(direct)𝐶𝐿𝑈𝑇 62.2 21.5
𝐶𝐷𝑆𝑃 0 0.5
Situation-2: When𝑆𝑙𝑢𝑡is enough to hold all the LUT consump-
tion from DSP packing with the factor of 4, satisfying:
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡. (9)
Based on Eq. 4, 5, 6 and 9, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
(4·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡−3·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡·𝐶𝑙𝑢𝑡.
(10)
If it does not satisfy Eq. 10, we perform DSP-based computations
with a packing factor of 3. Besides that, for the remaining available
LUT resources, pure-LUT-based computation is also conducted in
both cases.
Situation-3: When𝑆𝑙𝑢𝑡is between the LUT demands by fully
deploying DSP computations with packing factors of 3 and 4, satis-
fying:
3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡.(11)
Based on Eq. 4, 5, 6, and 11, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡+3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·(𝐶𝑙𝑢𝑡−𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)
𝐶𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡,
(12)
Input Sequence
Load Input T ile
Output Sequence
StoreOutput T ile Weight Matrix
LoadWeight T ile Figure 8: Data tiling in ViT computations.
In this case, we conduct only DSP-based computations with a
packing factor of 4. Otherwise, if it does not satisfy Eq. 12, we per-
form DSP-based computations with a packing factor of 3 and pure
LUT-based computation for the remaining available LUT resource.
4.4.2 Latency Modeling. As discussed in the Hardware Design Sec-
tion, our GEMM hardware engine accelerates the major MSA and
MLP modules and processes their input, weight, and output data in
tiles, as shown in Figure 8. our GEMM hardware engine accelerates
the major MSA and MLP modules and processes their input, weight,
and output data in tiles, as shown in Figure 8. Each MSA can be
seen as multiple parallel matrix multiplications. The accelerator is
designed to process parallel computations within each head. This
input channel splitting is also done for fully connected (FC) layers,
each containing one matrix multiplication for compatibility, and
the results need to be accumulated from all the input channels
in all the heads. Furthermore, the computing engine exploits fine-
grained data and operation parallelisms and can process 𝑇𝑚·𝑇𝑛
multiply-accumulate (MAC) operations in parallel.
ICS ’24, June 4–7, 2024, Kyoto, Japan
We model the inference latency of our hardware design based
on the number of clock cycles. For a layer 𝑖in ViT, since data
packing can be used to transfer multiple (i.e., 𝐷𝑎𝑐𝑡or𝐷𝑤𝑔𝑡) values
at the same time in each AXI port, the clock cycles for loading one
input/weight tile and storing one output tile, are calculated as:
𝐿in=𝑇𝑛
𝐷𝑎𝑐𝑡
·𝐹
𝐴in
,
𝐿wgt=𝑇𝑛
𝐷𝑤𝑔𝑡
·𝑇𝑚
𝐴wgt
,
𝐿out=𝑇𝑚
𝐷𝑎𝑐𝑡
·𝐹
𝐴out
,(13)
where𝐿in,𝐿wgtand𝐿outindicate the number of the clock cycles
of input, weight, and output transfer for one corresponding tile,
respectively.
The clock cycle number to compute one tile is
𝐿cmpt=max𝐹
𝑃𝐹
,𝑇𝑛·𝑇𝑚·𝐹
𝑁𝑡𝑜𝑡
, (14)
where the first term is calculated by the latency model. The total
number of multiplications needed to compute one tile of matrix
multiplication is 𝑇𝑛·𝑇𝑚·𝐹. Each tile has two levels of parallelism:
one is along the 𝑇𝑛and𝑇𝑚dimension and the parallel factor is
𝑇𝑛·𝑇𝑚(i.e., fully parallel); and the other is along the 𝐹dimension
and the parallel factor is 𝑃𝐹. Therefore, the first term is calculated asl
𝐹
𝑃𝐹m
. The second term is limited by the resource constraint, where
we can support at most 𝑁𝑡𝑜𝑡parallel multipliers (Eq. 4) due to the
resource constraint.
With the double buffers overlapping the data loading and com-
putation of the tiles, the overall clock cycle number for processing
one tile is𝐿1=max{𝐿in,𝐿wgt,𝐿cmpt}.
To obtain the accumulation of output results, this process is
performed multiple times (i.e., processingl
𝑁
𝑇𝑛m
input tiles). The
clock cycle number for calculating the whole output tile is 𝐿2=
max
𝐿1·l
𝑁
𝑇𝑛m
+𝐿cmpt,𝐿out
.
Since there arel
𝑀
𝑇𝑚m
number of output tiles, the total number of
clock cycles for a ViT layer 𝑖is described by
𝐿𝑖
tot=𝑀
𝑇𝑚
·𝐿2+𝐿out. (15)
Under a working frequency 𝑓, the FPSis calculated as:
𝐹𝑃𝑆=𝑓Í
𝑖𝐿𝑖
tot. (16)
5 EXPERIMENTAL RESULTS
5.1 Experimental Setup
Our supernet training process takes 700 epochs with a batch size of
2048. The learning rate is set to 5×10−4initially and decayed with
a cosine annealing schedule. The AdamW [ 28] optimizer is used
with the epsilon value of 1𝑒−8and weight decay of 0.05. Additional
training optimizations, such as warmup and label smoothing are
performed during training. The number of warmup epochs and
label smoothing factor are set as 20 and 0.1, respectively. After
supernet training, we perform the hardware-oriented evolution
search, without subnet retraining.Our training is conducted on 8 NVIDIA Ampere A100 GPUs
with CUDA 11.0 and PyTorch 1.7 frameworks on the Ubuntu oper-
ating system. To test the effectiveness of our framework, we also
implement Quasar-ViT framework on the Xilinx ZCU102 embedded
FPGA platform with quad-core ARM Cortex-A53 and XCZU9EG
FPGA chip. The FPGA working frequency is set to 150 MHz for all
the designs implemented via Xilinx Vitis and Vitis HLS 2020.1.
5.2 Accuracy Results
Here we analyze the accuracy results of our Quasar-ViT framework.
The weight precision is mixed with 4-bit and 8-bit, as mentioned
earlier, and the activation bit-width is determined by the hardware
feature. Without loss of generality, we use activation of 8-bit to
evaluate the accuracy in the ablation study of knowledge distillation
and supernet layer scaling.
5.2.1 Ablation Study of Knowledge Distillation and Supernet Layer
Scaling. To evaluate the compatibility of knowledge distillation
and our proposed SLS, we conduct an ablation study on both of
them. Without loss of generality and to prevent interference from
different model sizes and different quantization mixed ratios from
the searched subnet, we unify the search constraint with pure W8A8
(8-bit for both weight and activation) quantization implementation.
As shown in Table 6, we conduct four different settings of Quasar-
ViT with the unified model size and quantization scheme. The ac-
curacy of the four cases is 74.1% (w/o distillation and SLS), 75.6%
(only distillation), 74.9% (only SLS), and 76.1% (with both of them),
respectively. Knowledge distillation and SLS strategies are orthogo-
nal to each other, and both improve the model accuracy. Using them
together provides a better result. Given the observed effectiveness
of our proposed SLS strategy and the seamless compatibility of our
framework with knowledge distillation, we opt to incorporate both
strategies in our following experiments. Here we also quantize the
baseline DeiT-T [ 42] and compare it with our method without SLS
and distillation. Even without SLS and distillation, our quantization
NAS approach achieves a much better model accuracy than the
full-precision and the quantized (W8A8) DeiT-T models.
5.2.2 Ablation Study of Mixed-Ratio and Quantization Scheme. To
assess the efficacy of our row-wise flexible mixed-precision quanti-
zation scheme, we conducted an ablation study examining both the
quantization scheme itself and the 8-bit mixed ratio, as outlined in
Table 7. Since Quasar-ViT automatically searches the mixed ratios,
here we pick up the best model from the search stage for differ-
ent mixed ratios and compare them with the counterparts under
the fixed row-wise mixed quantization scheme. The results indi-
cate a consistent improvement in accuracy across different 8-bit
mixed-ratio levels with our flexible mixed scheme, underscoring
the efficiency of our proposed quantization scheme.
5.2.3 Overall Accuracy Results. Table 5 compares representative
ViT-based works with our proposed Quasar-ViT. Since many ViT-
based works do not incorporate model quantization, we also con-
sider the bit-width in the model size and the equivalent number of
total bit operations (BOPs).
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Table 5: Comparison of representative ViT-based works with our proposed Quasar-ViT.
ModelQuantization #Params Model Size MACs MAC Bit-width Equivalent Top-1 Accuracy
Mixed Type(𝑀) (𝑀𝐵) (𝐺) Weight Activation BOPs (𝐺) ( %)
DeiT-T [42] - 5.7 22.8 1.3 32 32 1.3×10372.2
T2T-T [63] - 4.3 17.2 1.1 32 32 1.1×10371.7
PiT-T [14] - 10.6 42.4 1.4 32 32 1.4×10372.4
LocalViT-T [21] - 5.9 23.6 1.3 32 32 1.3×10374.8
FQ-ViT [24] Model-wise 5.7 5.7 1.3 8 8 80.6 71.6
Q-ViT [20] Head-wise 5.7 - - 4-8 4-8 - 72.8
QUASAR-S (ours) Row-wise 5.9 4.1 1.4 4 & 8 6 45.6 74.9
PVT [51] - 24.5 98.0 3.8 32 32 3.9×10379.8
DeiT-S [42] - 22.9 91.6 4.6 32 32 4.8×10379.9
Swin-T [26] - 28 112.0 4.5 32 32 4.7×10381.2
BossNAS [18] - - - 3.4 32 32 3.5×10380.5
PTQ [27] Layer-wise 22.9 16.6 4.6 6-10 6-10 - 75.1
FQ-ViT [24] Model-wise 22.9 22.9 4.6 8 8 294.4 79.1
Q-ViT [20] Head-wise 22.9 - - 4-8 4-8 - 80.1
QUASAR-L1 (ours) Row-wise 14.7 9.8 3.2 4 & 8 6 103.8 78.6
QUASAR-L2 (ours) Row-wise 22.6 15.8 4.8 4 & 8 6 163.2 80.4
Table 6: Comparison between different settings of QUASAR-
Small with and without knowledge distillation (KD) and su-
pernet layer scaling (SLS) on ImageNet dataset.
ModelSetting #Params Quantization Top-1 Acc.
KD SLS (M) Scheme (%)
DeiT-T [42] No No 5.7 W32A32 72.2
DeiT-T (quant) No No 5.7 W8A8 71.5
Ours No No 5.9 W8A8 74.1
Ours Yes No 5.9 W8A8 75.6
Ours No Yes 5.9 W8A8 74.9
Ours Yes Yes 5.9 W8A8 76.1
Table 7: Comparison between different settings of 8-bit quan-
tization mixed-ratio and quantization schemes.
Scheme Model Size (MB) 8-bit mixed-ratio (%) Acc. (%)
Fixed row-wise 3.6 23 73.5
Flexible row-wise 3.6 23 74.2
Fixed row-wise 4.1 39 74.1
Flexible row-wise 4.1 39 74.9
As shown in Table 5, we present three Quasar models for dif-
ferent accuracy levels: QUASAR-S searched within the QUASAR-
Small supernet, and QUASAR-L1, QUASAR-L2 searched within the
QUASAR-Large supernet.
Our QUASAR-S achieves 74.9% top-1 accuracy with only 4.1 MB
model size and 1.4 GMACs, Compared with the representative ViT-
based model LocalViT-T [ 21] under a similar accuracy, our model
size is only 17.4% of that in LocalViT-T; although the GMACs num-
bers are similar, our MAC unit is much more hardware efficient
as it is for a 4-bit/8-bit weight and a 6-bit activation instead of a
32-bit floating-point MAC unit in LocalViT-T. For a higher modelTable 8: Comparisons of FPGA implementations for ViTs
on ImageNet, including DeiT-S and Auto-ViT-Acc from [ 22],
and our Quasar-ViT, all running at 150MHz on the same
AMD/Xilinx ZCU102 embedded FPGA platform.
DeiT-SAuto-ViT Quasar-ViT
-Acc L2 L1 S
Quant. NoMixed Mixed Mixed Mixed
Scheme Precision Precision Precision
Weight 32 4 & 8 4 & 8 4 & 8 4 & 8
Act. 32 8 6 6 6
Top-1 Acc. 79.9 78.7 80.4 78.6 74.9
kLUT 47% 67% 66% 66% 65%
FF - - 31% 31% 30%
DSP 69% 62% 69% 69% 69%
BRAM - - 44% 44% 44%
accuracy level, our QUASAR-L1 and QUASAR-L2 achieve 78.5%
and 80.4% top-1 accuracy, respectively. Among them, QUASAR-L2
only has a 15.8 MB model size with a computation volume of 4.8
GMACs, which obtains the smallest BOPs with a similar level of
accuracy compared with other baselines. Specifically, compared
with PTQ [ 27] (16.6 MB, top-1 75.1%), QUASAR-L2 achieves a simi-
lar model size and GMACs with 5.2% higher accuracy. Compared
with ViT NAS framework BossNAS [ 18], we additionally achieve
low-bit quantization with a much smaller BOPS and similar ac-
curacy. Compared with quantization-aware training framework
Q-ViT [ 20] using multiple quantization bit-widths in the range of 4
to 8, which incurs inefficiency and hardware under-utilization, our
results show better accuracy with a more unified and hardware-
friendly quantization scheme.
ICS ’24, June 4–7, 2024, Kyoto, Japan
5.3 Comparison of Hardware Results on FPGA
We implement a proof-of-concept hardware accelerator for our
Quasar-ViT on the AMD/Xilinx ZCU102 embedded FPGA platform.
We also compare our results to Auto-ViT-Acc [ 22], the state-of-
the-art FPGA accelerator for ViT with mixed-scheme quantization
(without NAS). We retrieve the hardware results for Auto-ViT-Acc
(which is quantized from DeiT-S) and the original DeiT-S on the
same Xilinx ZCU102 FPGA platform from [22].
Power (W)02.557.510
DeiT-SAuto-ViT-AccQuasar-ViT-L2Quasar-ViT-L1Quasar-ViT-SmallFPS075150225300
FPS/W07.51522.530
Accuracy (%)6066727884
Figure 9: Comparisons between DeiT-S, Auto-ViT-Acc
from [22], and our Quasar-ViT.
As shown in Table 8 and Figure 9, our approach consistently
outperforms the previous work. Specifically, compared with DeiT-
S [42], our QUASAR-L2 achieves 2.6 ×higher inference frames per
second (FPS) with 0.5% better accuracy. Compared with Auto-ViT-
Acc [ 22], our QUASAR-L1 achieves 1.6 ×higher FPS (159.6) with
a similar model accuracy level, and our QUASAR-L2 achieves a
similar level of FPS with 1.7% better top-1 accuracy.
The improvement in model accuracy and inference performance
within our framework is attributed to two key factors. Firstly, our
approach involves the training and search for a customized network
architecture, specifically tailored for both the mixed-precision quan-
tization schemes and the targeted inference latency. This strategy
enhances adaptability and efficiency, surpassing the achievements
of previous methodologies.
Secondly, our novel supernet training algorithm, coupled with
the proposed hybrid DSP packing design, allows for distinct quanti-
zation mixed ratios across various model layers. This fine-grained
model achieves better flexibility than the previous approaches, un-
leashing the full potential of mixed-precision quantization.
With regard to the efficiency of our hardware accelerator de-
sign, the performance is mainly limited by DSP, LUT, and off-chip
memory bandwidth. On par with Auto-ViT-Acc [ 22], our design
achieves 150MHz frequency with about 66% usage of LUTs and
69% DSPs without timing violations. Note a typical FPGA design
usually utilizes approximately 60% to 70% of the available FPGA
resources; otherwise, it may fail during the placement and routing
phase due to congestion or result in a lower operating frequency.
Without considering the timing violation, the maximum theoretical
expected performance is based on the 100% utilization ratio for bothDSP, LUTs, and bandwidth, which can achieve about 1.47x of our
reached FPS for the same model.
5.4 Other Transformer-based Model Accuracy
Results
To demonstrate the scalability and versatility of our methods, we
applied them across various datasets and applications, notably de-
ploying them on a large language model (LLM). This choice is mo-
tivated by two key factors. Firstly, LLM shares a transformer-based
architecture similar to that of Vision Transformer (ViT), aligning
with the framework that we propose. Secondly, LLM is frequently
integrated with ViT in text-to-image/video applications, making
it an ideal candidate to showcase the scalability of our approach
across both models and its potential for real-world applications.
Our comparative analysis, presented in Table 9, utilizes the
renowned LLM model, LLaMA, as the foundation for our supernet.
We juxtapose our optimized results with those of LLaMA-7B [ 44] on
the commonly used WikiText-2 dataset for LLMs, with perplexity
score (PPL) serving as the evaluation metric, where lower scores
indicate superior performance. According to the comparison results,
our method shows a constant pattern, achieving a similar level of
PPL with a much smaller model size.
Table 9: Result comparison on large language model.
Model Model Size (GB) W # Bits A # Bits PPL
LLaMA-7B [44] 26.8 FP32 FP32 5.68
Ours 6.7 INT8 INT8 5.73
Ours 4.8 INT4 & 8 INT8 5.91
5.5 Training Cost Comparison
Prior co-design frameworks, such as APQ [ 50], have also delved into
the integration of neural architecture search (NAS) and quantiza-
tion techniques. Please note that APQ is based on the convolutional
neural network (CNN) and BitFusion platform [ 50]. To the best of
our knowledge, we compare our Quasar-ViT models (both small
and large variants) and the APQ result. As detailed in Table 10,
our approach demonstrates superior FPS performance while main-
taining comparable or even higher model accuracy, achieved at a
reduced training cost. Compared with the 2,400 GPU hours training
cost of APQ [ 50], our approach only consumes 768 and 1,344 GPU
hours for the small and large versions of Quasar-ViT, respectively.
Our training setting has been illustrated in Section 5.1.
Table 10: Training cost and accuracy comparison with other
NAS and quantization co-design.
Method Training cost (GPU hours) FPS Acc.(%)
APQ [50] 2400 82.2 75.1
QUASAR-S 768 101.5 74.9
QUASAR-L 1344 251.6 80.4
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
6 | Section not found | discussion, we use the row-wise flexible
mixed-precision quantization scheme for ViTs, as shown in Fig-
ure 2(d), which preserves the quantization flexibility among layers
for better accuracy while maintaining the hardware uniformity for
more efficient implementation. Different from [ 40] that limits the
same mixed-precision ratio across CNN layers, for ViTs, we have to
provide the flexibility to obtain different mixed ratios in different
layers to maintain the model accuracy. To maintain hardware uni-
formity and avoid hardware under-utilization, we propose to design
the basic hardware units for the lower-bit computation, decompose
the higher-bit computation into lower-bit ones, and reuse the basic
hardware units (described in Section 4.2 and Section 4.3). As a re-
sult, we have preserved the uniformity of the hardware design and
enabled the flexible bit-width mixed-ratio among ViT layers. We
explain the hardware details in Section 4.
3.2 Intra-layer Mixed-Precision Weight
Entanglement
In classical one-shot NAS, the weights of each sample candidate
are shared with the supernet during training. However, as shown
in Figure 3 (a), when using the classical weight-sharing strategy,
the building blocks from multiple subnets, even in the same layer,
are isolated. Therefore, it leads to higher memory costs and slower
training convergence.
To address this problem, weight entanglement is proposed in [ 6]
to reduce the supernet model size: as shown in Figure 3 (b), different
transformer blocks can share their common weights in each layer. It
also allows each block to be updated more times than the previous
independent training strategy, thus achieving faster convergence.
However, this structure is hard to combine with mixed quantization
since one shared weight cannot be trained into two different bit-
widths at the same time (i.e., bit-width conflict).
In this paper, we propose the mixed-precision weight entangle-
ment, as shown in Figure 3 (c), to incorporate the quantization
search while preventing the potential bit-width conflicts problem
in the shared weight. Mixed-precision weight entanglement block
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Output
InputBlock-2
Block-1
Block-3dim (d - k) dim d dim (d + k)Output
Input
Block-2 dim d
Block-1
dim (d - k)
Block-3 dim (d + k)
Output
Input
Higher Precision Lower Precision dim d
dim aBlock dim d,
mixed-ratio (a/d)
(a) Classic Weight Sharing ... ...
(b) Original Weight Enanglement (c) Mixed-precision Weight Enanglement
Figure 3: Classic weight sharing and original weight entanglement versus our proposed mixed-precision weight entanglement.
contains two parts of weights with different precisions. Different
quantization mixed ratios can be achieved by extracting different
percentages of weights over these two parts. In the implementation,
for each layer, we only need to store the weights of the largest
of the𝑛homogeneous candidate blocks with both the 4-bit and
8-bit weights. The remaining smaller building blocks can extract
the weights directly from the largest building block. The different
quantization mixed ratios can be reached by moving the position
of the selected block.
3.3 Supernet Layer Scaling (SLS) Structure
The layer scaling structure proposed by CaiT [ 43] improves the
stability of the optimizations when training transformers for image
classification, thus improving the model accuracy. We explore this
structure and extend it to supernet layer scaling (SLS).
Layer scaling is a per-channel multiplication of the vector pro-
duced by each residual block. For ViT, this layer is deployed after
the multi-head self-attention (MSA) and multi-layer perceptron
(MLP) modules in each encoder block. The objective is to group the
updates of the weights associated with the same output channel.
Layer scaling can be denoted as a multiplication by a diagonal ma-
trixdiag 𝜆𝑙,1,...,𝜆𝑙,𝑑on the output of 𝑙-th residual block, where
𝑑is the corresponding number of output channels in the model. All
𝜆s are learnable weights.
To fit our mixed-precision weight entanglement strategy, dif-
ferent from the original CaiT [ 43] implementation that uses the
whole layer scaling in every training iteration, our SLS extracts the
corresponding elements synchronized with the output dimension
of the selected subnet while keeping the other weights frozen. As
shown in Figure 4, using the residual block of MLP as an example,
assuming that the current MLP’s output dimension starts from
𝑚-th channel and ends at 𝑛-th channel, the supernet layer scaling
computation can be formulated as:
𝑦𝑙=𝑥𝑙+diag 𝜆𝑙,𝑚,...,𝜆𝑙,𝑛×MLP(LN(𝑥𝑙)), (1)
where𝑥𝑙and𝑦𝑙denote the input and output, respectively; LN means
the layer normalization.
3.4 End-to-End Quasar-ViT Framework
3.4.1 One-shot NAS Algorithm. Our one-shot NAS algorithm con-
sists of two steps:
LN LN MLP
MSAOutput
SLSSLS
InputHidden Dimension Choice
Hidden Dimension Choiceλ1 0 ... 0 0 ... 0 ... 0
0 λ2 ... 0 0 ... 0 ... 0
... ... ... ... ... ... ... ... ...
0 0 ... λm 0 ... 0 ... 0
0 0 ... 0 λm+1 ... 0 ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... λ
n ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... 0 ... λ
d
Output dim:
1 m n dxlylFigure 4: Supernet layer scaling (SLS) in Quasar-ViT encoder
block. We use the SLS after MLP as an example.
•We train a supernet to directly sample different quantized
architectures as child models for training. The supernet is
trained with SLS and KD techniques. The search space is
encoded in the supernet, and the parameters of all candidate
networks in the search space are optimized simultaneously
by our proposed weight-sharing during training.
•We select architectures from the pre-trained supernet using
the hardware-oriented evolution search method to find the
most accurate model under the given hardware resource
constraints. We search based on the hardware latency/FPS
and resource modeling illustrated in Section 4.4.
Here, we show a toy example of the supernet training process
including candidate sampling and the corresponding searched re-
sults for different targeting FPS in Figure 5. Figure 5 (a) illustrates
one iteration of the supernet training process, where the pink area
indicates the sampled high precision values and the blue area indi-
cates the sampled low precision values in the supernet. The light
blue area indicates the frozen values (currently not sampled) in this
iteration. After the supernet training and the hardware-oriented
evolution search, we could obtain different models targeting dif-
ferent frames per second (FPS) as shown in Figure 5 (b). For the
ICS ’24, June 4–7, 2024, Kyoto, Japan
Layer-1
Layer-4
Layer-5
Layer-2Output
Layer-3
Layer-i
Input
+0.25 -0.50 +0.75 -0.50 +1.00 -1.00
+0.75 -0.25 -0.50 -0.50 +0.00 -1.00
+0.25 -0.25 -0.75 +0.50 +1.00 -0.50
+1.00 -0.75 +0.50 -0.50 +0.00 -1.00
-1.00 +0.25 -0.50 +0.50 -0.50 -0.50
+0.00 -0.25 +0.50 -0.50 +1.00 -1.00...Channel
... ...
L-3 L-2 L-1 R-1 R-2 R-3
High Precision Low Precision
(a) SuperNet Training Process (b) Different SubNets targeting different FPS after the searchOutput
Input...Output
Input...Output
Input...Target FPS-1
Target FPS-2
Target FPS-3Sampling for the training
Hardware-oriented
Evolution Search
Figure 5: SuperNet training process including candidate sampling and the searched results for different targeting FPS. We use a
model with layers of 6 channels as a toy example.
sake of brevity, we only show the quantized value here. The scaling
factor along with other related structures is omitted.
3.4.2 Search Space. We show our search space design in Table 2.
Our search components include the overall embedding dimension,
the number of transformer layers, the quantization mixed-ratio (i.e.,
the percentage of 8-bit weights mixed in the layer) for each linear
layer, and the hidden dimension and expansion ratio (for MLP) in
each ViT encoder block.
To accelerate the supernet training process and improve the
overall model performance, we partition the large-scale search
space into two sub-spaces and encode them into two independent
supernets for QUASAR-Small and QUASAR-Large, respectively. By
splitting and customizing search space for supernets of different
sizes, we mitigate the training interference caused by the huge
subnets’ difference. This training strategy has been proved in [ 66].
Such partition allows the search algorithm to concentrate on finding
models within a specific hardware inference latency, which can
be specialized by users according to their available resources and
application requirements. It also reduces gradient conflicts between
large and small sub-networks trained via weight-sharing due to
gaps in model sizes.
Table 2: An illustration of our search space: It is divided into
two independent supernets within the different parameter
ranges to satisfy different resource constraints.
QUASAR-Small QUASAR-Large
Embed Dimension (192, 216, 240) (320, 384, 448)
Hidden Dimension (192, 256) (320, 384, 448)
8-bit Mixed-ratio (0%, 25%, 50%) (0%, 25%, 50%)
Expansion Ratio (3.5, 4) (3, 3.5, 4)
Number of Layers (12,13,14) (12,13,14)
3.4.3 Supernet Training. In each iteration, we randomly select a
quantized ViT architecture from the search space. Then we obtain
its weights from the supernet and compute the losses of the subnet.Algorithm 1 Supernet Training.
Input: Training epochs 𝑁, search spaceP, supernetS, loss
function𝐿, train dataset 𝐷𝑡𝑟𝑎𝑖𝑛 , initial supernet weights WP,
candidate weightsW𝑝
for𝑖in𝑁epochs do
fordata, labels in 𝐷𝑡𝑟𝑎𝑖𝑛 do
Randomly sample one quantized ViT architecture from
search spaceP
Obtain the corresponding weights W𝑝from supernetWP
Compute the gradients based on 𝐿
Update the corresponding part of W𝑝inWPwhile freezing
the rest of the supernet S
end for
end for
OutputS
Finally, we update the corresponding weights with the remaining
weights frozen. The architecture search space 𝑃is encoded in a
supernet denoted as S(𝑃,𝑊𝑃), where𝑊𝑃is the weight of the super-
net that is shared across all the candidate architectures. Algorithm 1
illustrates the training procedure of our supernet.
3.5 Hardware-Oriented Evolution Search
In our hardware-oriented evolution search for crossover, two ran-
dom candidate architectures are first picked from the top candidates.
Then we uniformly choose one block from them in each layer to
generate a new architecture. For mutation, a candidate mutates its
depth with probability 𝑃𝑑first. Then it mutates each block with a
probability of 𝑃𝑚to produce a new architecture. Newly produced
architectures that do not satisfy the constraints will not be added
for the next generation. To evaluate the candidates, we perform
hardware latency and resource modeling based on the proposed
row-wise flexible mixed-precision quantization scheme. The details
of the modeling have been discussed in Section 4.4.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
3.6 Integration with Knowledge Distillation
(KD)
To demonstrate the compatibility of our proposed framework with
knowledge distillation (KD) and further improve the accuracy of
our supernet, we also integrate KD [ 15] in our training process. We
use the pre-trained RegNetY-32G [ 34] with 83.6% top-1 accuracy as
different teacher models. We also apply the soft distillation method.
Soft distillation [ 15] minimizes the Kullback-Leibler divergence
between the softmax of the teacher and the softmax of the student
model. The distillation loss is:
𝐿𝑠𝑜𝑓𝑡=(1−𝛼)𝐿𝐶𝐸(𝜓(𝑍𝑠),𝑦)+𝛼𝜏2𝐿𝐾𝐿(𝜓(𝑍𝑠
𝜏),𝜓(𝑍𝑡
𝜏)),(2)
where𝑍𝑡and𝑍𝑠are the logits of the teacher and student models,
respectively. 𝜓is the softmax function. 𝜏is the temperature for
the distillation, 𝛼is the coefficient balancing the Kullback–Leibler
divergence loss ( 𝐿𝐾𝐿), and the cross-entropy ( 𝐿𝐶𝐸) on the ground
truth labels 𝑦in the distillation.
4 FPGA HARDWARE DESIGN FOR
QUASAR-VIT
4.1 Overall Hardware Design for Quasar-ViT
Figure 6 presents the overall hardware architecture of the Quasar-
ViT accelerator on the ARM-FPGA platform. Below is how each
module in ViT is mapped to the hardware in Figure 6. The most
time-consuming MSA and MLP modules are accelerated by our
GEMM engine on the FPGA, which is similar to the recent Auto-
ViT-Acc work [ 22]. The lightweight SLS modules right after MSA
and MLP layers are also accelerated on the FPGA to avoid time-
consuming execution on the ARM CPU. The less time-consuming
modules including layer normalization and activation functions
(i.e., Softmax or GELU) are executed on the ARM CPU, due to their
complex structure for FPGA implementation. The hardware engines
on the FPGA and software modules on the ARM CPU exchange
data via the shared off-chip memory.
FPGA
CPU
LayerNorm
GELU
Softmax
Memory
Controller
Off-Chip
DDR MemoryControl LogicGEMM Engine
PE
SLSOutput Buf ferPing-Pong
BufferPing-Pong
BufferPE PE
PE PE PE
PE PE PEInput &
Weight
Figure 6: Quasar-ViT hardware architecture.
As previously mentioned, we mainly focus on the most time-
consuming GEMM engine design. Due to the limited on-chip mem-
ory capacity and computing resource on the FPGA, for each ViT
layer (i.e., MSA and MLP), our GEMM engine processes the input,
weight, and output data in tiles: a small tile of the input (tokens)
and weight of each ViT layer are first loaded from the off-chipDDR memory to the on-chip buffers, then they are processed by
the GEMM engine all on-chip. To improve the performance, the
double buffering technique is applied again to overlap the off-chip
memory accesses and GEMM computation, shown in Figure 6.
Next, we present our design of the basic hardware units in the
GEMM engine and the corresponding DSP (digital signal processor)
packing optimization, as well as the hardware resource and latency
modeling for the tiled GEMM design.
4.2 Unification of Atomic Computation
One major challenge in the FPGA accelerator design is to efficiently
support flexible mixed ratios of different bit-width computations
across ViT layers. On one hand, putting multiple copies of hardware
accelerator designs for each mixed-ratio (i.e., each layer) simultane-
ously on the FPGA leads to severe hardware resource contention
and under-utilization, since layers are executed sequentially. On
the other hand, pre-synthesizing multiple copies of hardware accel-
erator designs for each layer and reconfiguring the FPGA for each
layer incurs significant FPGA reconfiguration overhead.
Inspired by the approach proposed in QGTC [ 52] to support
arbitrary bit-width computation for quantized graph neural net-
works on GPUs, in our FPGA hardware design, we unify the basic
processing elements to process 4-bit weight atomic computations
and construct the 8-bit weight data computations using two 4-bit
weight data operations as such: for multiplication between an N-bit
activation value ( 𝑎𝑐𝑡𝑁) and an 8-bit weight value ( 𝑤𝑔𝑡 8), we derive
the corresponding product as:
𝑎𝑐𝑡𝑁·𝑤𝑔𝑡 8=𝑎𝑐𝑡𝑁·𝑤𝑔𝑡ℎ4<<4+𝑎𝑐𝑡𝑁·𝑤𝑔𝑡𝑙4, (3)
where𝑤𝑔𝑡ℎ4and𝑤𝑔𝑡𝑙4represent the higher and lower 4-bit data
of𝑤𝑔𝑡 8, respectively. The multiplication result between 𝑎𝑐𝑡𝑁and
𝑤𝑔𝑡ℎ4are left shifted by 4 bits.
Based on this unification, we propose hybrid signed/unsigned
DSP packing to handle the 4-bit weight atomic computation.
4.3 Proposed Hybrid Signed/Unsigned DSP
Packing
To fully exploit the potential of DSP resources on FPGAs, we pack
multiple low-bit multiplications within each DSP block follow-
ing [57,58]. Each DSP block (DSP48E2) on the AMD/Xilinx ZCU102
FPGA board could support the computation of 𝑃=(𝐴+𝐷)×𝐵, where
both𝐴and𝐷are 27-bit operands, 𝐵is an 18-bit operand, and 𝑃is
the 45-bit output. In our study, we explore the following two DSP
packing schemes and discuss their design trade-offs. The activation
bit-width𝑁is set to 6 to fully exploit the DSP for computation.
•Packing factor 3 (3 weights sharing 1 activation). In
Figure 7 (a), three 4×6-bit multiplications are packed into a
single DSP block, by holding one 6-bit signed activation in
port𝐵and three 4-bit weight values in port 𝐷. To pack three
weights into a single 27-bit port 𝐷, look-up tables (LUTs)
are utilized to first combine two weights and then integrate
them with the third weight data. With this DSP packing
scheme, for the W4A6 (i.e., 4-bit weight and 6-bit activation)
computation, we could pack three 4-bit weights that share
the same activation. And for the W8A6 computation, we
could use two DSPs to process the upper and lower 4-bit
ICS ’24, June 4–7, 2024, Kyoto, Japan
of three 8-bit weights in parallel. Note that after the 8-bit
weights are decomposed into two 4-bit weights, only the
upper 4-bit weights contain the sign bits and should be sign-
extended (required by DSP for output correctness [ 57,58]),
the lower 4-bit weights should be treated as unsigned values.
•Packing factor 4 (2 weights sharing 2 activations). In
Figure 7 (b), four 4×6-bit multiplications are packed into
a single DSP block, by holding two 6-bit signed activation
values in port 𝐷and two 4-bit weights in port 𝐵. It is worth
mentioning the port placement of the activation and weight
values are swapped from the packing factor 3 scheme, to
increase the packing strength. With this DSP packing scheme,
for the W4A6 computation, we could pack a pair of two 4-
bit weights that share the same pair of activation values.
And for the W8A6 computation, a similar technique as the
previous packing scheme is used to separately handle the
upper and lower 4-bit values of an 8-bit weight. Again for the
two decomposed 4-bit weights, only the upper 4-bit weights
contain the sign bit and should be sign-extended (required
by DSP for output correctness [ 57,58]), but the lower 4-bit
weights should be treated as unsigned values.
4.4 Hardware Resource and Latency Modeling
Here, we present our hardware resource and latency modeling used
in the hardware-oriented evolution search.
Table 3: Notations for Quasar-ViT accelerator
Notation Description
𝑀(𝑁) Number of output (input) channels
𝐹 Number of token sequences
𝑇𝑛 Tiling size for data in input channel dimension for
each head
𝑇𝑚 Tiling size for data in output channel dimension
𝑁ℎ Total number of heads
𝑃𝐹 Parallel factor along the number of tokens
𝐷𝑎𝑐𝑡 Number of data packed as one for activations
𝐷𝑤𝑔𝑡 Number of data packed as one for weights
𝐴in (𝐴out,
𝐴wgt)Number of AXI ports used for data transfer of input
(output, weight) tile
𝐿in (𝐿wgt,
𝐿out,𝐿cmpt)Number of clock cycles for input transfer (weight
transfer, output transfer, computation) for a tile
𝑆dsp(𝑆lut) Available number of DSPs (LUTs) on FPGA
𝐶dsp DSP cost for each MAC operation
𝐶lut LUT cost for each MAC operation
𝐶𝑑𝑠𝑝
𝑙𝑢𝑡Number of LUTs used by a multiplication executed
on DSPs
𝑁𝑑𝑠𝑝 Number of multiplication executed on DSPs
𝑁𝑙𝑢𝑡 Number of multiplication executed on LUTs
𝑁𝑡𝑜𝑡 The total number of multiplication on FPGA
𝛾𝑑𝑠𝑝(𝛾𝑙𝑢𝑡) DSP (LUT) utilization threshold
𝑓 FPGA accelerator frequency
𝐹𝑃𝑆 Frames per second
4.4.1 Resource Modeling. To help guide the neural architecture
search, we provide details of the resource and latency models ofour FPGA accelerator design (mainly the GEMM engine). Table 3
lists the notations used in our models. We design our FPGA accel-
erator to fully leverage the available FPGA computing resources
(i.e., DSPs and LUTs), on-chip memory (i.e., BRAMs), and off-chip
memory bandwidth. To fully exploit the computing capability with
the available hardware resources, We maximize the total number of
parallel basic hardware compute units using both DSPs (i.e., 𝑁𝑑𝑠𝑝)
and LUTs (i.e., 𝑁𝑙𝑢𝑡) for the datapath of our accelerator as
𝑁𝑡𝑜𝑡=maximize
𝑁𝑑𝑠𝑝+𝑁𝑙𝑢𝑡
, (4)
while satisfying the following resource constraints
𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝≤𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝, (5)
𝑁𝑙𝑢𝑡·𝐶𝑙𝑢𝑡+𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡, (6)
where constraints 5 and 6 bound the DSP and LUT utilization to
be under the allowable thresholds, i.e., 𝛾𝑑𝑠𝑝and𝛾𝑙𝑢𝑡with the total
resource amounts denoted by 𝑆𝑑𝑠𝑝and𝑆𝑙𝑢𝑡. The hardware costs of
each multiplication implementation are denoted as 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡.
In order to choose the best implementation method for the basic
hardware units of our design, we characterize the FPGA resource
consumption using Xilinx Vivado 2020.1 [ 59] for the three cases in
Table 4, i.e., (a) multiplications executed on DSPs with packing fac-
tor of 3, (b) multiplications executed on DSPs with packing factor of
4, and (c) multiplications executed purely using LUTs. As observed
in Table 4, we derive the hardware costs of each multiplication
implementation, particularly, the LUT costs for pure-LUT-based
and DSP-based methods correspond to 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡. Note that the
DSP-based approach also consumes LUTs, due to data packing on
the input operands and output data construction operations, such
as bit shifting and data accumulation. Regarding the efficiency
lost by decomposing 8-bit to 4-bit, for the composed W8A6 com-
putation, on average, we can achieve one computation with 25.8
LUTs and 0.5 DSP or purely 66.7 LUTs. In contrast, direct W8A6
computation used in [ 40] (i.e., packing two W8A6 operations within
one DSP method) requires 21.5 LUTs and 0.5 DSP or purely 62.2
LUTs. Since most of the weights are in 4-bit, using decomposing
does not affect the overall performance much by a slight increase
in the LUT utilization. In terms of the efficiency of DSP packing, a
single DSP can pack four W4A6 operations at most theoretically,
which is achieved by our approach.
For the LUT usage, shown in Table 4, we have:
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡<𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡<𝐶𝑙𝑢𝑡. (7)
In the final implementation, regarding which DSP packing scheme
to use and whether to use the pure-LUT-based method for the basic
hardware compute units, there are several situations according to
the available FPGA resources.
Situation-1: When𝑆𝑙𝑢𝑡is limited and insufficient to hold the
LUT consumption of full utilization of DSP packing with a factor
of 3, denoted as:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡. (8)
In this case, to fully utilize the computation resources, we directly
allocate DSP-based computations with a packing factor of 3 as much
as possible until we reach the LUT resource limit.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
Activation 6-bit
Weight 4-bitWeight 4-bit
Activation 6-bit = +Weight 8-bit
Signed number unsigned number
(a) Packing Factor of 3
(b) Packing Factor of 4
Figure 7: Illustration of DSP multiplication packing schemes for (a) 3 weights sharing 1 activation with packing factor of 3, and
(b) 2 weights sharing 2 activations with packing factor of 4.
Table 4: FPGA resource consumption for a single DSP-based
or LUT-based basic hardware compute unit. W4A6 denotes
4-bit weight and 6-bit activation; W8A6 denotes 8-bit weight
and 6-bit activation.
pure LUT-basedDSP-based
packing
factor 3packing
factor 4
W4A6𝐶𝐿𝑈𝑇 33.3 10.9 12.9
𝐶𝐷𝑆𝑃 0 0.33 0.25
W8A6𝐶𝐿𝑈𝑇 66.7 21.9 25.8
𝐶𝐷𝑆𝑃 0 0.67 0.5
W8A6
(direct)𝐶𝐿𝑈𝑇 62.2 21.5
𝐶𝐷𝑆𝑃 0 0.5
Situation-2: When𝑆𝑙𝑢𝑡is enough to hold all the LUT consump-
tion from DSP packing with the factor of 4, satisfying:
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡. (9)
Based on Eq. 4, 5, 6 and 9, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
(4·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡−3·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡·𝐶𝑙𝑢𝑡.
(10)
If it does not satisfy Eq. 10, we perform DSP-based computations
with a packing factor of 3. Besides that, for the remaining available
LUT resources, pure-LUT-based computation is also conducted in
both cases.
Situation-3: When𝑆𝑙𝑢𝑡is between the LUT demands by fully
deploying DSP computations with packing factors of 3 and 4, satis-
fying:
3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡.(11)
Based on Eq. 4, 5, 6, and 11, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡+3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·(𝐶𝑙𝑢𝑡−𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)
𝐶𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡,
(12)
Input Sequence
Load Input T ile
Output Sequence
StoreOutput T ile Weight Matrix
LoadWeight T ile Figure 8: Data tiling in ViT computations.
In this case, we conduct only DSP-based computations with a
packing factor of 4. Otherwise, if it does not satisfy Eq. 12, we per-
form DSP-based computations with a packing factor of 3 and pure
LUT-based computation for the remaining available LUT resource.
4.4.2 Latency Modeling. As discussed in the Hardware Design Sec-
tion, our GEMM hardware engine accelerates the major MSA and
MLP modules and processes their input, weight, and output data in
tiles, as shown in Figure 8. our GEMM hardware engine accelerates
the major MSA and MLP modules and processes their input, weight,
and output data in tiles, as shown in Figure 8. Each MSA can be
seen as multiple parallel matrix multiplications. The accelerator is
designed to process parallel computations within each head. This
input channel splitting is also done for fully connected (FC) layers,
each containing one matrix multiplication for compatibility, and
the results need to be accumulated from all the input channels
in all the heads. Furthermore, the computing engine exploits fine-
grained data and operation parallelisms and can process 𝑇𝑚·𝑇𝑛
multiply-accumulate (MAC) operations in parallel.
ICS ’24, June 4–7, 2024, Kyoto, Japan
We model the inference latency of our hardware design based
on the number of clock cycles. For a layer 𝑖in ViT, since data
packing can be used to transfer multiple (i.e., 𝐷𝑎𝑐𝑡or𝐷𝑤𝑔𝑡) values
at the same time in each AXI port, the clock cycles for loading one
input/weight tile and storing one output tile, are calculated as:
𝐿in=𝑇𝑛
𝐷𝑎𝑐𝑡
·𝐹
𝐴in
,
𝐿wgt=𝑇𝑛
𝐷𝑤𝑔𝑡
·𝑇𝑚
𝐴wgt
,
𝐿out=𝑇𝑚
𝐷𝑎𝑐𝑡
·𝐹
𝐴out
,(13)
where𝐿in,𝐿wgtand𝐿outindicate the number of the clock cycles
of input, weight, and output transfer for one corresponding tile,
respectively.
The clock cycle number to compute one tile is
𝐿cmpt=max𝐹
𝑃𝐹
,𝑇𝑛·𝑇𝑚·𝐹
𝑁𝑡𝑜𝑡
, (14)
where the first term is calculated by the latency model. The total
number of multiplications needed to compute one tile of matrix
multiplication is 𝑇𝑛·𝑇𝑚·𝐹. Each tile has two levels of parallelism:
one is along the 𝑇𝑛and𝑇𝑚dimension and the parallel factor is
𝑇𝑛·𝑇𝑚(i.e., fully parallel); and the other is along the 𝐹dimension
and the parallel factor is 𝑃𝐹. Therefore, the first term is calculated asl
𝐹
𝑃𝐹m
. The second term is limited by the resource constraint, where
we can support at most 𝑁𝑡𝑜𝑡parallel multipliers (Eq. 4) due to the
resource constraint.
With the double buffers overlapping the data loading and com-
putation of the tiles, the overall clock cycle number for processing
one tile is𝐿1=max{𝐿in,𝐿wgt,𝐿cmpt}.
To obtain the accumulation of output results, this process is
performed multiple times (i.e., processingl
𝑁
𝑇𝑛m
input tiles). The
clock cycle number for calculating the whole output tile is 𝐿2=
max
𝐿1·l
𝑁
𝑇𝑛m
+𝐿cmpt,𝐿out
.
Since there arel
𝑀
𝑇𝑚m
number of output tiles, the total number of
clock cycles for a ViT layer 𝑖is described by
𝐿𝑖
tot=𝑀
𝑇𝑚
·𝐿2+𝐿out. (15)
Under a working frequency 𝑓, the FPSis calculated as:
𝐹𝑃𝑆=𝑓Í
𝑖𝐿𝑖
tot. (16)
5 EXPERIMENTAL RESULTS
5.1 Experimental Setup
Our supernet training process takes 700 epochs with a batch size of
2048. The learning rate is set to 5×10−4initially and decayed with
a cosine annealing schedule. The AdamW [ 28] optimizer is used
with the epsilon value of 1𝑒−8and weight decay of 0.05. Additional
training optimizations, such as warmup and label smoothing are
performed during training. The number of warmup epochs and
label smoothing factor are set as 20 and 0.1, respectively. After
supernet training, we perform the hardware-oriented evolution
search, without subnet retraining.Our training is conducted on 8 NVIDIA Ampere A100 GPUs
with CUDA 11.0 and PyTorch 1.7 frameworks on the Ubuntu oper-
ating system. To test the effectiveness of our framework, we also
implement Quasar-ViT framework on the Xilinx ZCU102 embedded
FPGA platform with quad-core ARM Cortex-A53 and XCZU9EG
FPGA chip. The FPGA working frequency is set to 150 MHz for all
the designs implemented via Xilinx Vitis and Vitis HLS 2020.1.
5.2 Accuracy Results
Here we analyze the accuracy results of our Quasar-ViT framework.
The weight precision is mixed with 4-bit and 8-bit, as mentioned
earlier, and the activation bit-width is determined by the hardware
feature. Without loss of generality, we use activation of 8-bit to
evaluate the accuracy in the ablation study of knowledge distillation
and supernet layer scaling.
5.2.1 Ablation Study of Knowledge Distillation and Supernet Layer
Scaling. To evaluate the compatibility of knowledge distillation
and our proposed SLS, we conduct an ablation study on both of
them. Without loss of generality and to prevent interference from
different model sizes and different quantization mixed ratios from
the searched subnet, we unify the search constraint with pure W8A8
(8-bit for both weight and activation) quantization implementation.
As shown in Table 6, we conduct four different settings of Quasar-
ViT with the unified model size and quantization scheme. The ac-
curacy of the four cases is 74.1% (w/o distillation and SLS), 75.6%
(only distillation), 74.9% (only SLS), and 76.1% (with both of them),
respectively. Knowledge distillation and SLS strategies are orthogo-
nal to each other, and both improve the model accuracy. Using them
together provides a better result. Given the observed effectiveness
of our proposed SLS strategy and the seamless compatibility of our
framework with knowledge distillation, we opt to incorporate both
strategies in our following experiments. Here we also quantize the
baseline DeiT-T [ 42] and compare it with our method without SLS
and distillation. Even without SLS and distillation, our quantization
NAS approach achieves a much better model accuracy than the
full-precision and the quantized (W8A8) DeiT-T models.
5.2.2 Ablation Study of Mixed-Ratio and Quantization Scheme. To
assess the efficacy of our row-wise flexible mixed-precision quanti-
zation scheme, we conducted an ablation study examining both the
quantization scheme itself and the 8-bit mixed ratio, as outlined in
Table 7. Since Quasar-ViT automatically searches the mixed ratios,
here we pick up the best model from the search stage for differ-
ent mixed ratios and compare them with the counterparts under
the fixed row-wise mixed quantization scheme. The results indi-
cate a consistent improvement in accuracy across different 8-bit
mixed-ratio levels with our flexible mixed scheme, underscoring
the efficiency of our proposed quantization scheme.
5.2.3 Overall Accuracy Results. Table 5 compares representative
ViT-based works with our proposed Quasar-ViT. Since many ViT-
based works do not incorporate model quantization, we also con-
sider the bit-width in the model size and the equivalent number of
total bit operations (BOPs).
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Table 5: Comparison of representative ViT-based works with our proposed Quasar-ViT.
ModelQuantization #Params Model Size MACs MAC Bit-width Equivalent Top-1 Accuracy
Mixed Type(𝑀) (𝑀𝐵) (𝐺) Weight Activation BOPs (𝐺) ( %)
DeiT-T [42] - 5.7 22.8 1.3 32 32 1.3×10372.2
T2T-T [63] - 4.3 17.2 1.1 32 32 1.1×10371.7
PiT-T [14] - 10.6 42.4 1.4 32 32 1.4×10372.4
LocalViT-T [21] - 5.9 23.6 1.3 32 32 1.3×10374.8
FQ-ViT [24] Model-wise 5.7 5.7 1.3 8 8 80.6 71.6
Q-ViT [20] Head-wise 5.7 - - 4-8 4-8 - 72.8
QUASAR-S (ours) Row-wise 5.9 4.1 1.4 4 & 8 6 45.6 74.9
PVT [51] - 24.5 98.0 3.8 32 32 3.9×10379.8
DeiT-S [42] - 22.9 91.6 4.6 32 32 4.8×10379.9
Swin-T [26] - 28 112.0 4.5 32 32 4.7×10381.2
BossNAS [18] - - - 3.4 32 32 3.5×10380.5
PTQ [27] Layer-wise 22.9 16.6 4.6 6-10 6-10 - 75.1
FQ-ViT [24] Model-wise 22.9 22.9 4.6 8 8 294.4 79.1
Q-ViT [20] Head-wise 22.9 - - 4-8 4-8 - 80.1
QUASAR-L1 (ours) Row-wise 14.7 9.8 3.2 4 & 8 6 103.8 78.6
QUASAR-L2 (ours) Row-wise 22.6 15.8 4.8 4 & 8 6 163.2 80.4
Table 6: Comparison between different settings of QUASAR-
Small with and without knowledge distillation (KD) and su-
pernet layer scaling (SLS) on ImageNet dataset.
ModelSetting #Params Quantization Top-1 Acc.
KD SLS (M) Scheme (%)
DeiT-T [42] No No 5.7 W32A32 72.2
DeiT-T (quant) No No 5.7 W8A8 71.5
Ours No No 5.9 W8A8 74.1
Ours Yes No 5.9 W8A8 75.6
Ours No Yes 5.9 W8A8 74.9
Ours Yes Yes 5.9 W8A8 76.1
Table 7: Comparison between different settings of 8-bit quan-
tization mixed-ratio and quantization schemes.
Scheme Model Size (MB) 8-bit mixed-ratio (%) Acc. (%)
Fixed row-wise 3.6 23 73.5
Flexible row-wise 3.6 23 74.2
Fixed row-wise 4.1 39 74.1
Flexible row-wise 4.1 39 74.9
As shown in Table 5, we present three Quasar models for dif-
ferent accuracy levels: QUASAR-S searched within the QUASAR-
Small supernet, and QUASAR-L1, QUASAR-L2 searched within the
QUASAR-Large supernet.
Our QUASAR-S achieves 74.9% top-1 accuracy with only 4.1 MB
model size and 1.4 GMACs, Compared with the representative ViT-
based model LocalViT-T [ 21] under a similar accuracy, our model
size is only 17.4% of that in LocalViT-T; although the GMACs num-
bers are similar, our MAC unit is much more hardware efficient
as it is for a 4-bit/8-bit weight and a 6-bit activation instead of a
32-bit floating-point MAC unit in LocalViT-T. For a higher modelTable 8: Comparisons of FPGA implementations for ViTs
on ImageNet, including DeiT-S and Auto-ViT-Acc from [ 22],
and our Quasar-ViT, all running at 150MHz on the same
AMD/Xilinx ZCU102 embedded FPGA platform.
DeiT-SAuto-ViT Quasar-ViT
-Acc L2 L1 S
Quant. NoMixed Mixed Mixed Mixed
Scheme Precision Precision Precision
Weight 32 4 & 8 4 & 8 4 & 8 4 & 8
Act. 32 8 6 6 6
Top-1 Acc. 79.9 78.7 80.4 78.6 74.9
kLUT 47% 67% 66% 66% 65%
FF - - 31% 31% 30%
DSP 69% 62% 69% 69% 69%
BRAM - - 44% 44% 44%
accuracy level, our QUASAR-L1 and QUASAR-L2 achieve 78.5%
and 80.4% top-1 accuracy, respectively. Among them, QUASAR-L2
only has a 15.8 MB model size with a computation volume of 4.8
GMACs, which obtains the smallest BOPs with a similar level of
accuracy compared with other baselines. Specifically, compared
with PTQ [ 27] (16.6 MB, top-1 75.1%), QUASAR-L2 achieves a simi-
lar model size and GMACs with 5.2% higher accuracy. Compared
with ViT NAS framework BossNAS [ 18], we additionally achieve
low-bit quantization with a much smaller BOPS and similar ac-
curacy. Compared with quantization-aware training framework
Q-ViT [ 20] using multiple quantization bit-widths in the range of 4
to 8, which incurs inefficiency and hardware under-utilization, our
results show better accuracy with a more unified and hardware-
friendly quantization scheme.
ICS ’24, June 4–7, 2024, Kyoto, Japan
5.3 Comparison of Hardware Results on FPGA
We implement a proof-of-concept hardware accelerator for our
Quasar-ViT on the AMD/Xilinx ZCU102 embedded FPGA platform.
We also compare our results to Auto-ViT-Acc [ 22], the state-of-
the-art FPGA accelerator for ViT with mixed-scheme quantization
(without NAS). We retrieve the hardware results for Auto-ViT-Acc
(which is quantized from DeiT-S) and the original DeiT-S on the
same Xilinx ZCU102 FPGA platform from [22].
Power (W)02.557.510
DeiT-SAuto-ViT-AccQuasar-ViT-L2Quasar-ViT-L1Quasar-ViT-SmallFPS075150225300
FPS/W07.51522.530
Accuracy (%)6066727884
Figure 9: Comparisons between DeiT-S, Auto-ViT-Acc
from [22], and our Quasar-ViT.
As shown in Table 8 and Figure 9, our approach consistently
outperforms the previous work. Specifically, compared with DeiT-
S [42], our QUASAR-L2 achieves 2.6 ×higher inference frames per
second (FPS) with 0.5% better accuracy. Compared with Auto-ViT-
Acc [ 22], our QUASAR-L1 achieves 1.6 ×higher FPS (159.6) with
a similar model accuracy level, and our QUASAR-L2 achieves a
similar level of FPS with 1.7% better top-1 accuracy.
The improvement in model accuracy and inference performance
within our framework is attributed to two key factors. Firstly, our
approach involves the training and search for a customized network
architecture, specifically tailored for both the mixed-precision quan-
tization schemes and the targeted inference latency. This strategy
enhances adaptability and efficiency, surpassing the achievements
of previous methodologies.
Secondly, our novel supernet training algorithm, coupled with
the proposed hybrid DSP packing design, allows for distinct quanti-
zation mixed ratios across various model layers. This fine-grained
model achieves better flexibility than the previous approaches, un-
leashing the full potential of mixed-precision quantization.
With regard to the efficiency of our hardware accelerator de-
sign, the performance is mainly limited by DSP, LUT, and off-chip
memory bandwidth. On par with Auto-ViT-Acc [ 22], our design
achieves 150MHz frequency with about 66% usage of LUTs and
69% DSPs without timing violations. Note a typical FPGA design
usually utilizes approximately 60% to 70% of the available FPGA
resources; otherwise, it may fail during the placement and routing
phase due to congestion or result in a lower operating frequency.
Without considering the timing violation, the maximum theoretical
expected performance is based on the 100% utilization ratio for bothDSP, LUTs, and bandwidth, which can achieve about 1.47x of our
reached FPS for the same model.
5.4 Other Transformer-based Model Accuracy
Results
To demonstrate the scalability and versatility of our methods, we
applied them across various datasets and applications, notably de-
ploying them on a large language model (LLM). This choice is mo-
tivated by two key factors. Firstly, LLM shares a transformer-based
architecture similar to that of Vision Transformer (ViT), aligning
with the framework that we propose. Secondly, LLM is frequently
integrated with ViT in text-to-image/video applications, making
it an ideal candidate to showcase the scalability of our approach
across both models and its potential for real-world applications.
Our comparative analysis, presented in Table 9, utilizes the
renowned LLM model, LLaMA, as the foundation for our supernet.
We juxtapose our optimized results with those of LLaMA-7B [ 44] on
the commonly used WikiText-2 dataset for LLMs, with perplexity
score (PPL) serving as the evaluation metric, where lower scores
indicate superior performance. According to the comparison results,
our method shows a constant pattern, achieving a similar level of
PPL with a much smaller model size.
Table 9: Result comparison on large language model.
Model Model Size (GB) W # Bits A # Bits PPL
LLaMA-7B [44] 26.8 FP32 FP32 5.68
Ours 6.7 INT8 INT8 5.73
Ours 4.8 INT4 & 8 INT8 5.91
5.5 Training Cost Comparison
Prior co-design frameworks, such as APQ [ 50], have also delved into
the integration of neural architecture search (NAS) and quantiza-
tion techniques. Please note that APQ is based on the convolutional
neural network (CNN) and BitFusion platform [ 50]. To the best of
our knowledge, we compare our Quasar-ViT models (both small
and large variants) and the APQ result. As detailed in Table 10,
our approach demonstrates superior FPS performance while main-
taining comparable or even higher model accuracy, achieved at a
reduced training cost. Compared with the 2,400 GPU hours training
cost of APQ [ 50], our approach only consumes 768 and 1,344 GPU
hours for the small and large versions of Quasar-ViT, respectively.
Our training setting has been illustrated in Section 5.1.
Table 10: Training cost and accuracy comparison with other
NAS and quantization co-design.
Method Training cost (GPU hours) FPS Acc.(%)
APQ [50] 2400 82.2 75.1
QUASAR-S 768 101.5 74.9
QUASAR-L 1344 251.6 80.4
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
6 | Section not found | Section not found | Section not found | Section not found | CONCLUSION
In this work, we propose Quasar-ViT, a hardware-oriented quantization-
aware network architecture search framework to enable efficient
ViT deployment on resource-constrained edge devices. First, we
proposed hardware-friendly quantization techniques including flex-
ible row-wise mixed-precision quantization scheme and intra-layer
mixed-precision weight entanglement in architecture search to-
wards high accuracy and low training cost for efficient implemen-
tation. Second, we propose 4-bit weight atomic computation and
hybrid signed/unsigned DSP packing for FPGA implementation,
then incorporate latency/resource modeling to enable the hardware-
oriented architecture search. Third, we extend the supernet layer
scaling technique to further improve the training convergence and
supernet accuracy. We also demonstrate the compatibility of our
proposed framework with knowledge distillation during super-
net training. Finally, we developed an efficient hardware-oriented
search algorithm—integrated with hardware latency and resource
modeling—to search the efficient subnet with high accuracy under
a given inference latency target and implemented the searched
model on real FPGA hardware for validation. From the experiment
evaluation results, our approach achieves 101.5, 159.6, and 251.6
FPS on the AMD/Xilinx ZCU102 FPGA board with 80.4%, 78.6%,
and 74.9% top-1 accuracy for ImageNet, respectively, consistently
outperforming prior works. | Section not found | ACKNOWLEDGMENTS
This work was supported in part by NSERC Discovery Grant RGPIN-
2019-04613, DGECR-2019-00120, Alliance Grant ALLRP-552042-
2020; CFI John R. Evans Leaders Fund; BC Knowledge Development
Fund; Army Research Office/Army Research Laboratory via grant
W911-NF-20-1-0167 to Northeastern University; National Science
Foundation CCF-1937500, CNS-1909172, and IIS-2310254. No exter-
nal funding support to CD and MS for this project. | REFERENCES
[1]Haoli Bai, Wei Zhang, Lu Hou, Lifeng Shang, Jing Jin, Xin Jiang, Qun Liu, Michael
Lyu, and Irwin King. 2021. BinaryBERT: Pushing the Limit of BERT Quantization.
InProceedings of the 59th Annual Meeting of the Association for Computational Lin-
guistics and the 11th International Joint Conference on Natural Language Processing
(Volume 1: Long Papers) .
[2]Bowen Baker, Otkrist Gupta, Nikhil Naik, and Ramesh Raskar. 2017. Designing
Neural Network Architectures using Reinforcement Learning. In International
Conference on Learning Representations (ICLR) .
[3]Gabriel Bender, Pieter-Jan Kindermans, Barret Zoph, Vijay Vasudevan, and Quoc
Le. 2018. Understanding and simplifying one-shot architecture search. In Pro-
ceedings of the International Conference on Machine Learning (ICML) . 550–559.
[4]Han Cai, Tianyao Chen, Weinan Zhang, Yong Yu, and Jun Wang. 2018. Effi-
cient architecture search by network transformation. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 32.
[5]Sung-En Chang, Yanyu Li, Mengshu Sun, Runbin Shi, Hayden K-H So, Xuehai
Qian, Yanzhi Wang, and Xue Lin. 2021. Mix and Match: A novel FPGA-centric deep
neural network quantization framework. In 2021 IEEE International Symposium
on High-Performance Computer Architecture (HPCA) . 208–220.
[6]Minghao Chen, Houwen Peng, Jianlong Fu, and Haibin Ling. 2021. Autoformer:
Searching transformers for visual recognition. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 12270–12280.
[7]Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang,
Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. 2018. Pact: Parameterized
clipping activation for quantized neural networks. arXiv:1805.06085 (2018).
[8]Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. 2015. Binarycon-
nect: Training deep neural networks with binary weights during propagations.
InAdvances in Neural Information Processing Systems (NeurIPS) . 3123–3131.[9]Zhen Dong, Zhewei Yao, Amir Gholami, Michael W Mahoney, and Kurt Keutzer.
2019. Hawq: Hessian aware quantization of neural networks with mixed-
precision. In Proceedings of the IEEE/CVF International Conference on Computer
Vision (ICCV) .
[10] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xi-
aohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg
Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. 2021. An Image is
Worth 16x16 Words: Transformers for Image Recognition at Scale. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=YicbFdNTTy
[11] Zichao Guo, Xiangyu Zhang, Haoyuan Mu, Wen Heng, Zechun Liu, Yichen Wei,
and Jian Sun. 2020. Single path one-shot neural architecture search with uniform
sampling. In Proceedings of the European Conference on Computer Vision (ECCV) .
Springer, 544–560.
[12] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 2016. Deep residual
learning for image recognition. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 770–778.
[13] Zhezhi He and Deliang Fan. 2019. Simultaneously optimizing weight and quan-
tizer of ternary neural network using truncated gaussian approximation. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recogni-
tion (CVPR) .
[14] Byeongho Heo, Sangdoo Yun, Dongyoon Han, Sanghyuk Chun, Junsuk Choe,
and Seong Joon Oh. 2021. Rethinking spatial dimensions of vision transformers.
arXiv:2103.16302 (2021).
[15] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. 2015. Distilling the knowledge in
a neural network. arXiv:1503.02531 (2015).
[16] Intel. 2024. Intel ®Xeon®Silver 4214 Processor. https://ark.intel.com/content/
www/us/en/ark/products/193385/intel-xeon-silver-4214-processor-16-5m-
cache-2-20-ghz.html. Last accessed Jan. 18, 2024.
[17] Cong Leng, Zesheng Dou, Hao Li, Shenghuo Zhu, and Rong Jin. 2018. Extremely
low bit neural network: Squeeze the last bit out with admm. In Proceedings of the
AAAI Conference on Artificial Intelligence .
[18] Changlin Li, Tao Tang, Guangrun Wang, Jiefeng Peng, Bing Wang, Xiaodan
Liang, and Xiaojun Chang. 2021. Bossnas: Exploring hybrid cnn-transformers
with block-wisely self-supervised neural architecture search. In Proceedings of
the IEEE/CVF International Conference on Computer Vision (ICCV) . 12281–12291.
[19] Yuhang Li, Xin Dong, and Wei Wang. 2020. Additive Powers-of-Two Quantization:
An Efficient Non-uniform Discretization for Neural Networks. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=BkgXT24tDS
[20] Yanjing Li, Sheng Xu, Baochang Zhang, Xianbin Cao, Peng Gao, and Guodong
Guo. 2022. Q-ViT: Accurate and Fully Quantized Low-bit Vision Transformer. In
Advances in Neural Information Processing Systems (NeurIPS) . https://openreview.
net/forum?id=fU-m9kQe0ke
[21] Yawei Li, Kai Zhang, Jiezhang Cao, Radu Timofte, and Luc Van Gool. 2021.
LocalViT: Bringing Locality to Vision Transformers. arXiv:2104.05707 [cs.CV]
[22] Zhengang Li, Mengshu Sun, Alec Lu, Haoyu Ma, Geng Yuan, Yanyue Xie, Hao
Tang, Yanyu Li, Miriam Leeser, Zhangyang Wang, Xue Lin, and Zhenman Fang.
2022. Auto-vit-acc: An fpga-aware automatic acceleration framework for vi-
sion transformer with mixed-scheme quantization. In 2022 32nd International
Conference on Field-Programmable Logic and Applications (FPL) . IEEE, 109–116.
[23] Zhengang Li, Geng Yuan, Wei Niu, Pu Zhao, Yanyu Li, Yuxuan Cai, Xuan Shen,
Zheng Zhan, Zhenglun Kong, Qing Jin, et al .2021. NPAS: A Compiler-aware
Framework of Unified Network Pruning and Architecture Search for Beyond
Real-Time Mobile Acceleration. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 14255–14266.
[24] Yang Lin, Tianyu Zhang, Peiqin Sun, Zheng Li, and Shuchang Zhou. 2022. FQ-ViT:
Post-Training Quantization for Fully Quantized Vision Transformer. In Proceed-
ings of the Thirty-First International Joint Conference on Artificial Intelligence,
IJCAI-22 . 1173–1179.
[25] Chenxi Liu, Barret Zoph, Maxim Neumann, Jonathon Shlens, Wei Hua, Li-Jia Li,
Li Fei-Fei, Alan Yuille, Jonathan Huang, and Kevin Murphy. 2018. Progressive
neural architecture search. In Proceedings of the European conference on computer
vision (ECCV) . 19–34.
[26] Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin,
and Baining Guo. 2021. Swin transformer: Hierarchical vision transformer using
shifted windows. In Proceedings of the IEEE International Conference on Computer
Vision (ICCV) .
[27] Zhenhua Liu, Yunhe Wang, Kai Han, Siwei Ma, and Wen Gao. 2021. Post-Training
Quantization for Vision Transformer. In Advances in Neural Information Processing
Systems (NeurIPS) .
[28] Ilya Loshchilov and Frank Hutter. 2019. Decoupled Weight Decay Regular-
ization. In International Conference on Learning Representations (ICLR) . https:
//openreview.net/forum?id=Bkg6RiCqY7
[29] Qian Lou, Feng Guo, Minje Kim, Lantao Liu, and Lei Jiang. 2019. AutoQ: Auto-
mated Kernel-Wise Neural Network Quantization. In International Conference on
Learning Representations (ICLR) .
ICS ’24, June 4–7, 2024, Kyoto, Japan
[30] Risto Miikkulainen, Jason Liang, Elliot Meyerson, Aditya Rawal, Dan Fink, Olivier
Francon, Bala Raju, Hormoz Shahrzad, Arshak Navruzyan, Nigel Duffy, et al .
2019. Evolving deep neural networks. In Artificial Intelligence in the Age of Neural
Networks and Brain Computing . Elsevier, 293–312.
[31] Bowen Pan, Rameswar Panda, Yifan Jiang, Zhangyang Wang, Rogerio Feris, and
Aude Oliva. 2021. IA-RED2: Interpretability-Aware Redundancy Reduction for
Vision Transformers. Advances in Neural Information Processing Systems (NeurIPS)
34 (2021), 24898–24911.
[32] Hieu Pham, Melody Guan, Barret Zoph, Quoc Le, and Jeff Dean. 2018. Effi-
cient neural architecture search via parameters sharing. In Proceedings of the
International Conference on Machine Learning (ICML) . 4095–4104.
[33] PyTorch. 2024. PYTORCH PROFILER. https://pytorch.org/tutorials/recipes/
recipes/profiler_recipe.html. Last accessed Jan. 18, 2024.
[34] Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, and Piotr
Dollár. 2020. Designing network design spaces. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 10428–10436.
[35] Maithra Raghu, Thomas Unterthiner, Simon Kornblith, Chiyuan Zhang, and
Alexey Dosovitskiy. 2021. Do Vision Transformers See Like Convolutional Neural
Networks?. In Advances in Neural Information Processing Systems (NeurIPS) .
[36] Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. 2016.
Xnor-net: Imagenet classification using binary convolutional neural networks.
InProceedings of the European Conference on Computer Vision (ECCV) . 525–542.
[37] Esteban Real, Alok Aggarwal, Yanping Huang, and Quoc V Le. 2019. Regularized
evolution for image classifier architecture search. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 33. 4780–4789.
[38] Manas Sahni, Shreya Varshini, Alind Khare, and Alexey Tumanov. 2021. Com-
pOFA: Compound Once-For-All Networks for Faster Multi-Platform Deployment.
arXiv preprint arXiv:2104.12642 (2021).
[39] Sheng Shen, Zhen Dong, Jiayu Ye, Linjian Ma, Zhewei Yao, Amir Gholami,
Michael W Mahoney, and Kurt Keutzer. 2020. Q-bert: Hessian based ultra low
precision quantization of bert. In Proceedings of the AAAI Conference on Artificial
Intelligence , Vol. 34:05. 8815–8821.
[40] Mengshu Sun, Zhengang Li, Alec Lu, Yanyu Li, Sung-En Chang, Xiaolong Ma,
Xue Lin, and Zhenman Fang. 2022. Film-qnn: Efficient fpga acceleration of deep
neural networks with intra-layer, mixed-precision quantization. In Proceedings
of the 2022 ACM/SIGDA International Symposium on Field-Programmable Gate
Arrays . 134–145.
[41] Mingxing Tan, Bo Chen, Ruoming Pang, Vijay Vasudevan, Mark Sandler, Andrew
Howard, and Quoc V Le. 2019. Mnasnet: Platform-aware neural architecture
search for mobile. In Proceedings of the IEEE/CVF Conference on Computer Vision
and Pattern Recognition (CVPR) . 2820–2828.
[42] Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre
Sablayrolles, and Hervé Jégou. 2021. Training data-efficient image transformers
& distillation through attention. In Proceedings of the International Conference on
Machine Learning (ICML) . PMLR, 10347–10357.
[43] Hugo Touvron, Matthieu Cord, Alexandre Sablayrolles, Gabriel Synnaeve, and
Hervé Jégou. 2021. Going deeper with image transformers. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) . 32–42.
[44] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne
Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al .2023. Llama: Open and efficient foundation language models. arXiv
preprint arXiv:2302.13971 (2023).
[45] Stefan Uhlich, Lukas Mauch, Fabien Cardinaux, Kazuki Yoshiyama, Javier Alonso
Garcia, Stephen Tiedemann, Thomas Kemp, and Akira Nakamura. 2020. Mixed
Precision DNNs: All you need is a good parametrization. In International Confer-
ence on Learning Representations (ICLR) .
[46] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,
Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you
need. In Advances in Neural Information Processing Systems (NeurIPS) . 5998–6008.
[47] Dilin Wang, Meng Li, Chengyue Gong, and Vikas Chandra. 2021. Attentivenas:
Improving neural architecture search via attentive sampling. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
6418–6427.
[48] Hanrui Wang, Zhanghao Wu, Zhijian Liu, Han Cai, Ligeng Zhu, Chuang Gan,
and Song Han. 2020. Hat: Hardware-aware transformers for efficient natural
language processing. arXiv:2005.14187 (2020).
[49] Kuan Wang, Zhijian Liu, Yujun Lin, Ji Lin, and Song Han. 2019. HAQ: Hardware-
Aware Automated Quantization with Mixed Precision. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[50] Tianzhe Wang, Kuan Wang, Han Cai, Ji Lin, Zhijian Liu, Hanrui Wang, Yujun
Lin, and Song Han. 2020. Apq: Joint search for network architecture, pruning
and quantization policy. In Proceedings of the IEEE/CVF Conference on Computer
Vision and Pattern Recognition . 2078–2087.
[51] Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan, Kaitao Song, Ding Liang,
Tong Lu, Ping Luo, and Ling Shao. 2021. Pyramid Vision Transformer: A Versa-
tile Backbone for Dense Prediction without Convolutions. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) .[52] Yuke Wang, Boyuan Feng, and Yufei Ding. 2022. QGTC: accelerating quantized
graph neural networks via GPU tensor core. In Proceedings of the 27th ACM
SIGPLAN Symposium on Principles and Practice of Parallel Programming . 107–119.
[53] Bichen Wu, Xiaoliang Dai, Peizhao Zhang, Yanghan Wang, Fei Sun, Yiming
Wu, Yuandong Tian, Peter Vajda, Yangqing Jia, and Kurt Keutzer. 2019. Fbnet:
Hardware-aware efficient convnet design via differentiable neural architecture
search. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern
Recognition (CVPR) . 10734–10742.
[54] Bichen Wu, Yanghan Wang, Peizhao Zhang, Yuandong Tian, Peter Vajda, and
Kurt Keutzer. 2018. Mixed precision quantization of convnets via differentiable
neural architecture search. arXiv:1812.00090 (2018).
[55] Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, and
Lei Zhang. 2021. Cvt: Introducing convolutions to vision transformers. arXiv
preprint arXiv:2103.15808 (2021).
[56] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, and Kaiming He. 2017.
Aggregated residual transformations for deep neural networks. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[57] Xilinx. 2017. Deep Learning with INT8 Optimization on Xilinx Devices. https:
//docs.xilinx.com/v/u/en-US/wp486-deep-learning-int8. Last accessed Mar. 28,
2022.
[58] Xilinx. 2020. Convolutional Neural Network with INT4 Optimization on Xilinx
Devices. https://docs.xilinx.com/v/u/en-US/wp521-4bit-optimization. Last
accessed Mar. 28, 2022.
[59] Xilinx. 2020. Vivado Design Suite. https://www.xilinx.com/products/design-
tools/vivado.html. Last accessed Aug. 28, 2022.
[60] Shan You, Tao Huang, Mingmin Yang, Fei Wang, Chen Qian, and Changshui
Zhang. 2020. GreedyNAS: Towards Fast One-Shot NAS with Greedy Supernet. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition
(CVPR) . 1999–2008.
[61] Jiahui Yu, Pengchong Jin, Hanxiao Liu, Gabriel Bender, Pieter-Jan Kindermans,
Mingxing Tan, Thomas Huang, Xiaodan Song, Ruoming Pang, and Quoc Le. 2020.
Bignas: Scaling up neural architecture search with big single-stage models. In
Proceedings of the European Conference on Computer Vision (ECCV) . 702–717.
[62] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[63] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[64] Ofir Zafrir, Guy Boudoukh, Peter Izsak, and Moshe Wasserblat. 2019. Q8bert:
Quantized 8bit bert. In 2019 Fifth Workshop on Energy Efficient Machine Learning
and Cognitive Computing-NeurIPS Edition (EMC2-NIPS) . 36–39.
[65] Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, and Qun
Liu. 2020. Ternarybert: Distillation-aware ultra-low bit bert. In Proceedings of the
2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) .
[66] Yiyang Zhao, Linnan Wang, Yuandong Tian, Rodrigo Fonseca, and Tian Guo.
2021. Few-shot neural architecture search. In Proceedings of the International
Conference on Machine Learning (ICML) . PMLR, 12707–12718.
[67] Zhao Zhong, Junjie Yan, Wei Wu, Jing Shao, and Cheng-Lin Liu. 2018. Practical
block-wise neural network architecture generation. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 2423–2432.
[68] Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou.
2016. Dorefa-net: Training low bitwidth convolutional neural networks with low
bitwidth gradients. arXiv:1606.06160 (2016).
[69] Barret Zoph and Quoc V. Le. 2017. Neural Architecture Search with Reinforcement
Learning. In International Conference on Learning Representations (ICLR) .
[70] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, and Quoc V Le. 2018. Learning
transferable architectures for scalable image recognition. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) . 8697–
8710. | Section not found | Section not found | Section not found | funding support to CD and MS for this project.
REFERENCES
[1]Haoli Bai, Wei Zhang, Lu Hou, Lifeng Shang, Jing Jin, Xin Jiang, Qun Liu, Michael
Lyu, and Irwin King. 2021. BinaryBERT: Pushing the Limit of BERT Quantization.
InProceedings of the 59th Annual Meeting of the Association for Computational Lin-
guistics and the 11th International Joint Conference on Natural Language Processing
(Volume 1: Long Papers) .
[2]Bowen Baker, Otkrist Gupta, Nikhil Naik, and Ramesh Raskar. 2017. Designing
Neural Network Architectures using Reinforcement Learning. In International
Conference on Learning Representations (ICLR) .
[3]Gabriel Bender, Pieter-Jan Kindermans, Barret Zoph, Vijay Vasudevan, and Quoc
Le. 2018. Understanding and simplifying one-shot architecture search. In Pro-
ceedings of the International Conference on Machine Learning (ICML) . 550–559.
[4]Han Cai, Tianyao Chen, Weinan Zhang, Yong Yu, and Jun Wang. 2018. Effi-
cient architecture search by network transformation. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 32.
[5]Sung-En Chang, Yanyu Li, Mengshu Sun, Runbin Shi, Hayden K-H So, Xuehai
Qian, Yanzhi Wang, and Xue Lin. 2021. Mix and Match: A novel FPGA-centric deep
neural network quantization framework. In 2021 IEEE International Symposium
on High-Performance Computer Architecture (HPCA) . 208–220.
[6]Minghao Chen, Houwen Peng, Jianlong Fu, and Haibin Ling. 2021. Autoformer:
Searching transformers for visual recognition. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 12270–12280.
[7]Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang,
Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. 2018. Pact: Parameterized
clipping activation for quantized neural networks. arXiv:1805.06085 (2018).
[8]Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. 2015. Binarycon-
nect: Training deep neural networks with binary weights during propagations.
InAdvances in Neural Information Processing Systems (NeurIPS) . 3123–3131.[9]Zhen Dong, Zhewei Yao, Amir Gholami, Michael W Mahoney, and Kurt Keutzer.
2019. Hawq: Hessian aware quantization of neural networks with mixed-
precision. In Proceedings of the IEEE/CVF International Conference on Computer
Vision (ICCV) .
[10] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xi-
aohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg
Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. 2021. An Image is
Worth 16x16 Words: Transformers for Image Recognition at Scale. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=YicbFdNTTy
[11] Zichao Guo, Xiangyu Zhang, Haoyuan Mu, Wen Heng, Zechun Liu, Yichen Wei,
and Jian Sun. 2020. Single path one-shot neural architecture search with uniform
sampling. In Proceedings of the European Conference on Computer Vision (ECCV) .
Springer, 544–560.
[12] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 2016. Deep residual
learning for image recognition. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 770–778.
[13] Zhezhi He and Deliang Fan. 2019. Simultaneously optimizing weight and quan-
tizer of ternary neural network using truncated gaussian approximation. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recogni-
tion (CVPR) .
[14] Byeongho Heo, Sangdoo Yun, Dongyoon Han, Sanghyuk Chun, Junsuk Choe,
and Seong Joon Oh. 2021. Rethinking spatial dimensions of vision transformers.
arXiv:2103.16302 (2021).
[15] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. 2015. Distilling the knowledge in
a neural network. arXiv:1503.02531 (2015).
[16] Intel. 2024. Intel ®Xeon®Silver 4214 Processor. https://ark.intel.com/content/
www/us/en/ark/products/193385/intel-xeon-silver-4214-processor-16-5m-
cache-2-20-ghz.html. Last accessed Jan. 18, 2024.
[17] Cong Leng, Zesheng Dou, Hao Li, Shenghuo Zhu, and Rong Jin. 2018. Extremely
low bit neural network: Squeeze the last bit out with admm. In Proceedings of the
AAAI Conference on Artificial Intelligence .
[18] Changlin Li, Tao Tang, Guangrun Wang, Jiefeng Peng, Bing Wang, Xiaodan
Liang, and Xiaojun Chang. 2021. Bossnas: Exploring hybrid cnn-transformers
with block-wisely self-supervised neural architecture search. In Proceedings of
the IEEE/CVF International Conference on Computer Vision (ICCV) . 12281–12291.
[19] Yuhang Li, Xin Dong, and Wei Wang. 2020. Additive Powers-of-Two Quantization:
An Efficient Non-uniform Discretization for Neural Networks. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=BkgXT24tDS
[20] Yanjing Li, Sheng Xu, Baochang Zhang, Xianbin Cao, Peng Gao, and Guodong
Guo. 2022. Q-ViT: Accurate and Fully Quantized Low-bit Vision Transformer. In
Advances in Neural Information Processing Systems (NeurIPS) . https://openreview.
net/forum?id=fU-m9kQe0ke
[21] Yawei Li, Kai Zhang, Jiezhang Cao, Radu Timofte, and Luc Van Gool. 2021.
LocalViT: Bringing Locality to Vision Transformers. arXiv:2104.05707 [cs.CV]
[22] Zhengang Li, Mengshu Sun, Alec Lu, Haoyu Ma, Geng Yuan, Yanyue Xie, Hao
Tang, Yanyu Li, Miriam Leeser, Zhangyang Wang, Xue Lin, and Zhenman Fang.
2022. Auto-vit-acc: An fpga-aware automatic acceleration framework for vi-
sion transformer with mixed-scheme quantization. In 2022 32nd International
Conference on Field-Programmable Logic and Applications (FPL) . IEEE, 109–116.
[23] Zhengang Li, Geng Yuan, Wei Niu, Pu Zhao, Yanyu Li, Yuxuan Cai, Xuan Shen,
Zheng Zhan, Zhenglun Kong, Qing Jin, et al .2021. NPAS: A Compiler-aware
Framework of Unified Network Pruning and Architecture Search for Beyond
Real-Time Mobile Acceleration. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 14255–14266.
[24] Yang Lin, Tianyu Zhang, Peiqin Sun, Zheng Li, and Shuchang Zhou. 2022. FQ-ViT:
Post-Training Quantization for Fully Quantized Vision Transformer. In Proceed-
ings of the Thirty-First International Joint Conference on Artificial Intelligence,
IJCAI-22 . 1173–1179.
[25] Chenxi Liu, Barret Zoph, Maxim Neumann, Jonathon Shlens, Wei Hua, Li-Jia Li,
Li Fei-Fei, Alan Yuille, Jonathan Huang, and Kevin Murphy. 2018. Progressive
neural architecture search. In Proceedings of the European conference on computer
vision (ECCV) . 19–34.
[26] Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin,
and Baining Guo. 2021. Swin transformer: Hierarchical vision transformer using
shifted windows. In Proceedings of the IEEE International Conference on Computer
Vision (ICCV) .
[27] Zhenhua Liu, Yunhe Wang, Kai Han, Siwei Ma, and Wen Gao. 2021. Post-Training
Quantization for Vision Transformer. In Advances in Neural Information Processing
Systems (NeurIPS) .
[28] Ilya Loshchilov and Frank Hutter. 2019. Decoupled Weight Decay Regular-
ization. In International Conference on Learning Representations (ICLR) . https:
//openreview.net/forum?id=Bkg6RiCqY7
[29] Qian Lou, Feng Guo, Minje Kim, Lantao Liu, and Lei Jiang. 2019. AutoQ: Auto-
mated Kernel-Wise Neural Network Quantization. In International Conference on
Learning Representations (ICLR) .
ICS ’24, June 4–7, 2024, Kyoto, Japan
[30] Risto Miikkulainen, Jason Liang, Elliot Meyerson, Aditya Rawal, Dan Fink, Olivier
Francon, Bala Raju, Hormoz Shahrzad, Arshak Navruzyan, Nigel Duffy, et al .
2019. Evolving deep neural networks. In Artificial Intelligence in the Age of Neural
Networks and Brain Computing . Elsevier, 293–312.
[31] Bowen Pan, Rameswar Panda, Yifan Jiang, Zhangyang Wang, Rogerio Feris, and
Aude Oliva. 2021. IA-RED2: Interpretability-Aware Redundancy Reduction for
Vision Transformers. Advances in Neural Information Processing Systems (NeurIPS)
34 (2021), 24898–24911.
[32] Hieu Pham, Melody Guan, Barret Zoph, Quoc Le, and Jeff Dean. 2018. Effi-
cient neural architecture search via parameters sharing. In Proceedings of the
International Conference on Machine Learning (ICML) . 4095–4104.
[33] PyTorch. 2024. PYTORCH PROFILER. https://pytorch.org/tutorials/recipes/
recipes/profiler_recipe.html. Last accessed Jan. 18, 2024.
[34] Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, and Piotr
Dollár. 2020. Designing network design spaces. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 10428–10436.
[35] Maithra Raghu, Thomas Unterthiner, Simon Kornblith, Chiyuan Zhang, and
Alexey Dosovitskiy. 2021. Do Vision Transformers See Like Convolutional Neural
Networks?. In Advances in Neural Information Processing Systems (NeurIPS) .
[36] Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. 2016.
Xnor-net: Imagenet classification using binary convolutional neural networks.
InProceedings of the European Conference on Computer Vision (ECCV) . 525–542.
[37] Esteban Real, Alok Aggarwal, Yanping Huang, and Quoc V Le. 2019. Regularized
evolution for image classifier architecture search. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 33. 4780–4789.
[38] Manas Sahni, Shreya Varshini, Alind Khare, and Alexey Tumanov. 2021. Com-
pOFA: Compound Once-For-All Networks for Faster Multi-Platform Deployment.
arXiv preprint arXiv:2104.12642 (2021).
[39] Sheng Shen, Zhen Dong, Jiayu Ye, Linjian Ma, Zhewei Yao, Amir Gholami,
Michael W Mahoney, and Kurt Keutzer. 2020. Q-bert: Hessian based ultra low
precision quantization of bert. In Proceedings of the AAAI Conference on Artificial
Intelligence , Vol. 34:05. 8815–8821.
[40] Mengshu Sun, Zhengang Li, Alec Lu, Yanyu Li, Sung-En Chang, Xiaolong Ma,
Xue Lin, and Zhenman Fang. 2022. Film-qnn: Efficient fpga acceleration of deep
neural networks with intra-layer, mixed-precision quantization. In Proceedings
of the 2022 ACM/SIGDA International Symposium on Field-Programmable Gate
Arrays . 134–145.
[41] Mingxing Tan, Bo Chen, Ruoming Pang, Vijay Vasudevan, Mark Sandler, Andrew
Howard, and Quoc V Le. 2019. Mnasnet: Platform-aware neural architecture
search for mobile. In Proceedings of the IEEE/CVF Conference on Computer Vision
and Pattern Recognition (CVPR) . 2820–2828.
[42] Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre
Sablayrolles, and Hervé Jégou. 2021. Training data-efficient image transformers
& distillation through attention. In Proceedings of the International Conference on
Machine Learning (ICML) . PMLR, 10347–10357.
[43] Hugo Touvron, Matthieu Cord, Alexandre Sablayrolles, Gabriel Synnaeve, and
Hervé Jégou. 2021. Going deeper with image transformers. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) . 32–42.
[44] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne
Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al .2023. Llama: Open and efficient foundation language models. arXiv
preprint arXiv:2302.13971 (2023).
[45] Stefan Uhlich, Lukas Mauch, Fabien Cardinaux, Kazuki Yoshiyama, Javier Alonso
Garcia, Stephen Tiedemann, Thomas Kemp, and Akira Nakamura. 2020. Mixed
Precision DNNs: All you need is a good parametrization. In International Confer-
ence on Learning Representations (ICLR) .
[46] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,
Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you
need. In Advances in Neural Information Processing Systems (NeurIPS) . 5998–6008.
[47] Dilin Wang, Meng Li, Chengyue Gong, and Vikas Chandra. 2021. Attentivenas:
Improving neural architecture search via attentive sampling. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
6418–6427.
[48] Hanrui Wang, Zhanghao Wu, Zhijian Liu, Han Cai, Ligeng Zhu, Chuang Gan,
and Song Han. 2020. Hat: Hardware-aware transformers for efficient natural
language processing. arXiv:2005.14187 (2020).
[49] Kuan Wang, Zhijian Liu, Yujun Lin, Ji Lin, and Song Han. 2019. HAQ: Hardware-
Aware Automated Quantization with Mixed Precision. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[50] Tianzhe Wang, Kuan Wang, Han Cai, Ji Lin, Zhijian Liu, Hanrui Wang, Yujun
Lin, and Song Han. 2020. Apq: Joint search for network architecture, pruning
and quantization policy. In Proceedings of the IEEE/CVF Conference on Computer
Vision and Pattern Recognition . 2078–2087.
[51] Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan, Kaitao Song, Ding Liang,
Tong Lu, Ping Luo, and Ling Shao. 2021. Pyramid Vision Transformer: A Versa-
tile Backbone for Dense Prediction without Convolutions. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) .[52] Yuke Wang, Boyuan Feng, and Yufei Ding. 2022. QGTC: accelerating quantized
graph neural networks via GPU tensor core. In Proceedings of the 27th ACM
SIGPLAN Symposium on Principles and Practice of Parallel Programming . 107–119.
[53] Bichen Wu, Xiaoliang Dai, Peizhao Zhang, Yanghan Wang, Fei Sun, Yiming
Wu, Yuandong Tian, Peter Vajda, Yangqing Jia, and Kurt Keutzer. 2019. Fbnet:
Hardware-aware efficient convnet design via differentiable neural architecture
search. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern
Recognition (CVPR) . 10734–10742.
[54] Bichen Wu, Yanghan Wang, Peizhao Zhang, Yuandong Tian, Peter Vajda, and
Kurt Keutzer. 2018. Mixed precision quantization of convnets via differentiable
neural architecture search. arXiv:1812.00090 (2018).
[55] Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, and
Lei Zhang. 2021. Cvt: Introducing convolutions to vision transformers. arXiv
preprint arXiv:2103.15808 (2021).
[56] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, and Kaiming He. 2017.
Aggregated residual transformations for deep neural networks. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[57] Xilinx. 2017. Deep Learning with INT8 Optimization on Xilinx Devices. https:
//docs.xilinx.com/v/u/en-US/wp486-deep-learning-int8. Last accessed Mar. 28,
2022.
[58] Xilinx. 2020. Convolutional Neural Network with INT4 Optimization on Xilinx
Devices. https://docs.xilinx.com/v/u/en-US/wp521-4bit-optimization. Last
accessed Mar. 28, 2022.
[59] Xilinx. 2020. Vivado Design Suite. https://www.xilinx.com/products/design-
tools/vivado.html. Last accessed Aug. 28, 2022.
[60] Shan You, Tao Huang, Mingmin Yang, Fei Wang, Chen Qian, and Changshui
Zhang. 2020. GreedyNAS: Towards Fast One-Shot NAS with Greedy Supernet. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition
(CVPR) . 1999–2008.
[61] Jiahui Yu, Pengchong Jin, Hanxiao Liu, Gabriel Bender, Pieter-Jan Kindermans,
Mingxing Tan, Thomas Huang, Xiaodan Song, Ruoming Pang, and Quoc Le. 2020.
Bignas: Scaling up neural architecture search with big single-stage models. In
Proceedings of the European Conference on Computer Vision (ECCV) . 702–717.
[62] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[63] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[64] Ofir Zafrir, Guy Boudoukh, Peter Izsak, and Moshe Wasserblat. 2019. Q8bert:
Quantized 8bit bert. In 2019 Fifth Workshop on Energy Efficient Machine Learning
and Cognitive Computing-NeurIPS Edition (EMC2-NIPS) . 36–39.
[65] Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, and Qun
Liu. 2020. Ternarybert: Distillation-aware ultra-low bit bert. In Proceedings of the
2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) .
[66] Yiyang Zhao, Linnan Wang, Yuandong Tian, Rodrigo Fonseca, and Tian Guo.
2021. Few-shot neural architecture search. In Proceedings of the International
Conference on Machine Learning (ICML) . PMLR, 12707–12718.
[67] Zhao Zhong, Junjie Yan, Wei Wu, Jing Shao, and Cheng-Lin Liu. 2018. Practical
block-wise neural network architecture generation. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 2423–2432.
[68] Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou.
2016. Dorefa-net: Training low bitwidth convolutional neural networks with low
bitwidth gradients. arXiv:1606.06160 (2016).
[69] Barret Zoph and Quoc V. Le. 2017. Neural Architecture Search with Reinforcement
Learning. In International Conference on Learning Representations (ICLR) .
[70] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, and Quoc V Le. 2018. Learning
transferable architectures for scalable image recognition. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) . 8697–
8710. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | model architecture is transformer
encoder blocks with multi-headed self-attention (MSA) and multi-
layer perceptron (MLP) blocks. These blocks involve large matrix
multiplications, which incur the most computational cost. These
complex architectures and enormous computation/storage demand
make it hard to deploy ViTs on resource-limited edge devices.
Therefore, we quantize all layers involved in matrix multiplica-
tion, but not the non-linear functions, e.g., layer normalization, due
to their low computational cost and potential effects on accuracy.
2.2 Non-Transformer DNN Model Quantization
2.2.1 Quantization Scheme. To compress model size and improve
inference speed, model quantization has been widely explored
for deep neural networks (DNNs). Existing quantization research
can be categorized according to quantization schemes, such as bi-
nary [ 8,36], ternary [ 13], and low-bit-width fixed-point [ 7,7,68,68]
quantize models with the same interval between each quantization
level. Although binary and ternary quantization reduce operations
and simplify hardware implementation to the extreme, they intro-
duce large accuracy loss due to insufficient bit-width. For example,
based on reports from the above works, accuracy typically degrades
by>5%under binary quantization and 2−3%for ternary quantiza-
tion. To overcome the large accuracy loss coming from insufficientbit-width, the fixed-point quantization is proposed, applying mod-
erate and adjustable quantization bit-width, to maintain accuracy.
This quantization scheme was implemented with different methods
and algorithms, such as DoReFa-Net [68] and PACT [7].
Finally, there are also non-linear quantization schemes, such as
power-of-two (PoT) [ 17] and additive PoT [ 19]. They replace the
multiplication with shifting operations where the distribution of
quantization levels becomes unbalanced, having higher precision
around the mean and less precision at the two sides.
2.2.2 Mixed-Precision/Scheme Quantization. To explore more quan-
tization potential while preserving the model accuracy, Besides
the single scheme quantization, some works [ 9,39,45,49,54] ex-
plore inter-layer mixed-precision quantization by assigning dif-
ferent precisions to layers. For example, HAQ [ 49] determines
the bit-width of each layer by an agent trained with reinforce-
ment learning. DNAS [ 54] used NAS to search layer-wise bit-width.
Furthermore, [ 29] explored intra-layer mixed quantization to en-
able different precisions or schemes within each layer. Based on
them, hardware designs [ 5,40] leveraged the intra-layer mixed-
precision/mixed-scheme to enable uniformity within each layer,
guaranteeing inference acceleration. However, they need to set the
same mixed ratio for layers, which limits the model’s accuracy.
2.3 Transformer and ViT Quantization
Quantization has also been studied for transformers, especially for
natural language processing (NLP) tasks [ 1,64,65]. Q8BERT [ 64]
finetuned BERT through 8-bit quantization-aware training. Ternary-
BERT [ 65] implemented an approximation-based and loss-aware
ternary quantization on BERT. BinaryBERT [ 1] proposed a ternary
weight splitting strategy to derive binary BERT with performance
as the ternary one. Inspired by those, [ 27] and [ 22] studied quan-
tization on ViT in computer vision tasks. PTQ [ 27] evaluated the
post-training quantization on ViT and achieved comparable accu-
racy to the full-precision version. Auto-ViT-acc [ 22] proposed an
FPGA-aware framework with mixed-scheme quantization for ViT,
which we will compare in the evaluation. FQ-ViT [ 24] proposed
power-of-two factor and log-int-softmax to proceed with the ViT
quantization. Q-ViT [ 20] used the switchable scale to achieve head-
wise ViT mixed quantization. However, these works are all based on
full-precision pre-trained models and do not include the dimension
of network architecture search.
2.4 Neural Architecture Search
2.4.1 NAS Strategies. There has been a trend to design efficient
DNNs with NAS. In general, NAS can be classified into the follow-
ing categories according to its search strategy. First, reinforcement
learning (RL) methods [ 2,4,25,32,67,69,70] use recurrent neural
networks as predictors validating the accuracy of child networks
over a proxy dataset. Second, evolution methods [ 30,37] develop
a pipeline of parent initialization, population updating, genera-
tion, and elimination of offspring to find desired networks. Third,
one-shot NAS [ 3,11,60] trains a large one-shot model containing
all operations and shares the weight parameters with all candi-
date models. Based on the above work, weight-sharing NAS has
become popular due to training efficiency [ 38,47,61]. One over-
parameterized supernet is trained with weights shared across all
ICS ’24, June 4–7, 2024, Kyoto, Japan
(a) Model-wise Quantization
(b) Layer-wise Mixed Quantization
(d) Row-wise Mixed QuantizationRows Rows
(e) Kernel-wise Mixed Quantization LayersRows
Weight kernel RowsFlexible mixed-ratio RowsHead
(c) Head-wise Mixed Quantization
Figure 2: Comparison of mixed-precision quantization under
different granularity. We use the example of two different
bit-widths, represented as blue and pink colors. We propose
the row-wise flexible mixed-precision quantization in (d).
sub-networks in the search space. This significantly reduces the
computational cost during the search. Although most of the above
work focuses on the traditional CNN architectures, such as [ 61]
and [ 38], some works have started investigating the search for ef-
ficient ViT networks [ 6,18,48,55]. Among them, Autoformer [ 6]
entangles the model weights of different ViT blocks in the same
layer during supernet training with an efficient weight-sharing
strategy to reduce training model storage consumption as well as
training time.
2.4.2 Hardware-Oriented NAS. Some recent works realize the gap
between theoretical computation improvement and practical infer-
ence speedup. They investigate the algorithm/hardware co-design
and incorporate the inference latency into NAS [ 23,41,53], which is
more accurate than intuitive volume estimation by MAC operations.
For example, MnasNet [ 41] and NPAS [ 23] utilize the latency on
mobile devices as the reward to perform RL search, where gradient-
based NAS work FBNet [ 53] adds a latency term to the loss function.
However, these works neither target ViTs nor exploit quantization
in the hardware-aware ViT search.
3 HARDWARE-ORIENTED
QUANTIZATION-AWARE NAS FOR VITS
3.1 Row-Wise Flexible Mixed-Precision
Quantization with Hardware/Software
Co-design
Figure 2 classifies quantization with different levels of granular-
ity. Model-wise quantization [ 7,68] uses a unified quantizationbit-width for the whole model and thus misses some quantization
opportunities. On the other hand, mixed-precision quantization, as
discussed in related work, explores more quantization potential (i.e.,
quantizing each component to a bit-width as low as possible) while
preserving the accuracy of the model. Specifically, layer-wise (inter-
layer) mixed-precision quantization [ 49,54] sets each layer with a
specific quantization bit-width. Besides that, Q-ViT [ 20] proposed
a head-wise mixed-precision quantization scheme, which assigns
different bit-widths to different attention heads. Both the layer-wise
and head-wise quantization schemes suffer from limited quantiza-
tion flexibility without considering the variance inside each layer.
Moreover, fixed row-wise (intra-layer) mixed-precision quantiza-
tion is proposed in prior work [ 40], which uses different quantiza-
tion bit-widths for different channels in each CNN layer and limits
the same mixed-precision ratio across different CNN layers, and
thus multiple layers can share the same hardware design, making
it more hardware-friendly. Finally, kernel-wise mixed-precision
quantization [ 29] assigns different quantization bit-widths down to
the kernel level, which greatly diversifies the computing pattern
and makes it inefficient to implement on hardware.
Based on the above discussion, we use the row-wise flexible
mixed-precision quantization scheme for ViTs, as shown in Fig-
ure 2(d), which preserves the quantization flexibility among layers
for better accuracy while maintaining the hardware uniformity for
more efficient implementation. Different from [ 40] that limits the
same mixed-precision ratio across CNN layers, for ViTs, we have to
provide the flexibility to obtain different mixed ratios in different
layers to maintain the model accuracy. To maintain hardware uni-
formity and avoid hardware under-utilization, we propose to design
the basic hardware units for the lower-bit computation, decompose
the higher-bit computation into lower-bit ones, and reuse the basic
hardware units (described in Section 4.2 and Section 4.3). As a re-
sult, we have preserved the uniformity of the hardware design and
enabled the flexible bit-width mixed-ratio among ViT layers. We
explain the hardware details in Section 4.
3.2 Intra-layer Mixed-Precision Weight
Entanglement
In classical one-shot NAS, the weights of each sample candidate
are shared with the supernet during training. However, as shown
in Figure 3 (a), when using the classical weight-sharing strategy,
the building blocks from multiple subnets, even in the same layer,
are isolated. Therefore, it leads to higher memory costs and slower
training convergence.
To address this problem, weight entanglement is proposed in [ 6]
to reduce the supernet model size: as shown in Figure 3 (b), different
transformer blocks can share their common weights in each layer. It
also allows each block to be updated more times than the previous
independent training strategy, thus achieving faster convergence.
However, this structure is hard to combine with mixed quantization
since one shared weight cannot be trained into two different bit-
widths at the same time (i.e., bit-width conflict).
In this paper, we propose the mixed-precision weight entangle-
ment, as shown in Figure 3 (c), to incorporate the quantization
search while preventing the potential bit-width conflicts problem
in the shared weight. Mixed-precision weight entanglement block
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Output
InputBlock-2
Block-1
Block-3dim (d - k) dim d dim (d + k)Output
Input
Block-2 dim d
Block-1
dim (d - k)
Block-3 dim (d + k)
Output
Input
Higher Precision Lower Precision dim d
dim aBlock dim d,
mixed-ratio (a/d)
(a) Classic Weight Sharing ... ...
(b) Original Weight Enanglement (c) Mixed-precision Weight Enanglement
Figure 3: Classic weight sharing and original weight entanglement versus our proposed mixed-precision weight entanglement.
contains two parts of weights with different precisions. Different
quantization mixed ratios can be achieved by extracting different
percentages of weights over these two parts. In the implementation,
for each layer, we only need to store the weights of the largest
of the𝑛homogeneous candidate blocks with both the 4-bit and
8-bit weights. The remaining smaller building blocks can extract
the weights directly from the largest building block. The different
quantization mixed ratios can be reached by moving the position
of the selected block.
3.3 Supernet Layer Scaling (SLS) Structure
The layer scaling structure proposed by CaiT [ 43] improves the
stability of the optimizations when training transformers for image
classification, thus improving the model accuracy. We explore this
structure and extend it to supernet layer scaling (SLS).
Layer scaling is a per-channel multiplication of the vector pro-
duced by each residual block. For ViT, this layer is deployed after
the multi-head self-attention (MSA) and multi-layer perceptron
(MLP) modules in each encoder block. The objective is to group the
updates of the weights associated with the same output channel.
Layer scaling can be denoted as a multiplication by a diagonal ma-
trixdiag 𝜆𝑙,1,...,𝜆𝑙,𝑑on the output of 𝑙-th residual block, where
𝑑is the corresponding number of output channels in the model. All
𝜆s are learnable weights.
To fit our mixed-precision weight entanglement strategy, dif-
ferent from the original CaiT [ 43] implementation that uses the
whole layer scaling in every training iteration, our SLS extracts the
corresponding elements synchronized with the output dimension
of the selected subnet while keeping the other weights frozen. As
shown in Figure 4, using the residual block of MLP as an example,
assuming that the current MLP’s output dimension starts from
𝑚-th channel and ends at 𝑛-th channel, the supernet layer scaling
computation can be formulated as:
𝑦𝑙=𝑥𝑙+diag 𝜆𝑙,𝑚,...,𝜆𝑙,𝑛×MLP(LN(𝑥𝑙)), (1)
where𝑥𝑙and𝑦𝑙denote the input and output, respectively; LN means
the layer normalization.
3.4 End-to-End Quasar-ViT Framework
3.4.1 One-shot NAS Algorithm. Our one-shot NAS algorithm con-
sists of two steps:
LN LN MLP
MSAOutput
SLSSLS
InputHidden Dimension Choice
Hidden Dimension Choiceλ1 0 ... 0 0 ... 0 ... 0
0 λ2 ... 0 0 ... 0 ... 0
... ... ... ... ... ... ... ... ...
0 0 ... λm 0 ... 0 ... 0
0 0 ... 0 λm+1 ... 0 ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... λ
n ... 0
... ... ... ... ... ... ... ... ...0 0 ... 0 0 ... 0 ... λ
d
Output dim:
1 m n dxlylFigure 4: Supernet layer scaling (SLS) in Quasar-ViT encoder
block. We use the SLS after MLP as an example.
•We train a supernet to directly sample different quantized
architectures as child models for training. The supernet is
trained with SLS and KD techniques. The search space is
encoded in the supernet, and the parameters of all candidate
networks in the search space are optimized simultaneously
by our proposed weight-sharing during training.
•We select architectures from the pre-trained supernet using
the hardware-oriented evolution search method to find the
most accurate model under the given hardware resource
constraints. We search based on the hardware latency/FPS
and resource modeling illustrated in Section 4.4.
Here, we show a toy example of the supernet training process
including candidate sampling and the corresponding searched re-
sults for different targeting FPS in Figure 5. Figure 5 (a) illustrates
one iteration of the supernet training process, where the pink area
indicates the sampled high precision values and the blue area indi-
cates the sampled low precision values in the supernet. The light
blue area indicates the frozen values (currently not sampled) in this
iteration. After the supernet training and the hardware-oriented
evolution search, we could obtain different models targeting dif-
ferent frames per second (FPS) as shown in Figure 5 (b). For the
ICS ’24, June 4–7, 2024, Kyoto, Japan
Layer-1
Layer-4
Layer-5
Layer-2Output
Layer-3
Layer-i
Input
+0.25 -0.50 +0.75 -0.50 +1.00 -1.00
+0.75 -0.25 -0.50 -0.50 +0.00 -1.00
+0.25 -0.25 -0.75 +0.50 +1.00 -0.50
+1.00 -0.75 +0.50 -0.50 +0.00 -1.00
-1.00 +0.25 -0.50 +0.50 -0.50 -0.50
+0.00 -0.25 +0.50 -0.50 +1.00 -1.00...Channel
... ...
L-3 L-2 L-1 R-1 R-2 R-3
High Precision Low Precision
(a) SuperNet Training Process (b) Different SubNets targeting different FPS after the searchOutput
Input...Output
Input...Output
Input...Target FPS-1
Target FPS-2
Target FPS-3Sampling for the training
Hardware-oriented
Evolution Search
Figure 5: SuperNet training process including candidate sampling and the searched results for different targeting FPS. We use a
model with layers of 6 channels as a toy example.
sake of brevity, we only show the quantized value here. The scaling
factor along with other related structures is omitted.
3.4.2 Search Space. We show our search space design in Table 2.
Our search components include the overall embedding dimension,
the number of transformer layers, the quantization mixed-ratio (i.e.,
the percentage of 8-bit weights mixed in the layer) for each linear
layer, and the hidden dimension and expansion ratio (for MLP) in
each ViT encoder block.
To accelerate the supernet training process and improve the
overall model performance, we partition the large-scale search
space into two sub-spaces and encode them into two independent
supernets for QUASAR-Small and QUASAR-Large, respectively. By
splitting and customizing search space for supernets of different
sizes, we mitigate the training interference caused by the huge
subnets’ difference. This training strategy has been proved in [ 66].
Such partition allows the search algorithm to concentrate on finding
models within a specific hardware inference latency, which can
be specialized by users according to their available resources and
application requirements. It also reduces gradient conflicts between
large and small sub-networks trained via weight-sharing due to
gaps in model sizes.
Table 2: An illustration of our search space: It is divided into
two independent supernets within the different parameter
ranges to satisfy different resource constraints.
QUASAR-Small QUASAR-Large
Embed Dimension (192, 216, 240) (320, 384, 448)
Hidden Dimension (192, 256) (320, 384, 448)
8-bit Mixed-ratio (0%, 25%, 50%) (0%, 25%, 50%)
Expansion Ratio (3.5, 4) (3, 3.5, 4)
Number of Layers (12,13,14) (12,13,14)
3.4.3 Supernet Training. In each iteration, we randomly select a
quantized ViT architecture from the search space. Then we obtain
its weights from the supernet and compute the losses of the subnet.Algorithm 1 Supernet Training.
Input: Training epochs 𝑁, search spaceP, supernetS, loss
function𝐿, train dataset 𝐷𝑡𝑟𝑎𝑖𝑛 , initial supernet weights WP,
candidate weightsW𝑝
for𝑖in𝑁epochs do
fordata, labels in 𝐷𝑡𝑟𝑎𝑖𝑛 do
Randomly sample one quantized ViT architecture from
search spaceP
Obtain the corresponding weights W𝑝from supernetWP
Compute the gradients based on 𝐿
Update the corresponding part of W𝑝inWPwhile freezing
the rest of the supernet S
end for
end for
OutputS
Finally, we update the corresponding weights with the remaining
weights frozen. The architecture search space 𝑃is encoded in a
supernet denoted as S(𝑃,𝑊𝑃), where𝑊𝑃is the weight of the super-
net that is shared across all the candidate architectures. Algorithm 1
illustrates the training procedure of our supernet.
3.5 Hardware-Oriented Evolution Search
In our hardware-oriented evolution search for crossover, two ran-
dom candidate architectures are first picked from the top candidates.
Then we uniformly choose one block from them in each layer to
generate a new architecture. For mutation, a candidate mutates its
depth with probability 𝑃𝑑first. Then it mutates each block with a
probability of 𝑃𝑚to produce a new architecture. Newly produced
architectures that do not satisfy the constraints will not be added
for the next generation. To evaluate the candidates, we perform
hardware latency and resource modeling based on the proposed
row-wise flexible mixed-precision quantization scheme. The details
of the modeling have been discussed in Section 4.4.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
3.6 Integration with Knowledge Distillation
(KD)
To demonstrate the compatibility of our proposed framework with
knowledge distillation (KD) and further improve the accuracy of
our supernet, we also integrate KD [ 15] in our training process. We
use the pre-trained RegNetY-32G [ 34] with 83.6% top-1 accuracy as
different teacher models. We also apply the soft distillation method.
Soft distillation [ 15] minimizes the Kullback-Leibler divergence
between the softmax of the teacher and the softmax of the student
model. The distillation loss is:
𝐿𝑠𝑜𝑓𝑡=(1−𝛼)𝐿𝐶𝐸(𝜓(𝑍𝑠),𝑦)+𝛼𝜏2𝐿𝐾𝐿(𝜓(𝑍𝑠
𝜏),𝜓(𝑍𝑡
𝜏)),(2)
where𝑍𝑡and𝑍𝑠are the logits of the teacher and student models,
respectively. 𝜓is the softmax function. 𝜏is the temperature for
the distillation, 𝛼is the coefficient balancing the Kullback–Leibler
divergence loss ( 𝐿𝐾𝐿), and the cross-entropy ( 𝐿𝐶𝐸) on the ground
truth labels 𝑦in the distillation.
4 FPGA HARDWARE DESIGN FOR
QUASAR-VIT
4.1 Overall Hardware Design for Quasar-ViT
Figure 6 presents the overall hardware architecture of the Quasar-
ViT accelerator on the ARM-FPGA platform. Below is how each
module in ViT is mapped to the hardware in Figure 6. The most
time-consuming MSA and MLP modules are accelerated by our
GEMM engine on the FPGA, which is similar to the recent Auto-
ViT-Acc work [ 22]. The lightweight SLS modules right after MSA
and MLP layers are also accelerated on the FPGA to avoid time-
consuming execution on the ARM CPU. The less time-consuming
modules including layer normalization and activation functions
(i.e., Softmax or GELU) are executed on the ARM CPU, due to their
complex structure for FPGA implementation. The hardware engines
on the FPGA and software modules on the ARM CPU exchange
data via the shared off-chip memory.
FPGA
CPU
LayerNorm
GELU
Softmax
Memory
Controller
Off-Chip
DDR MemoryControl LogicGEMM Engine
PE
SLSOutput Buf ferPing-Pong
BufferPing-Pong
BufferPE PE
PE PE PE
PE PE PEInput &
Weight
Figure 6: Quasar-ViT hardware architecture.
As previously mentioned, we mainly focus on the most time-
consuming GEMM engine design. Due to the limited on-chip mem-
ory capacity and computing resource on the FPGA, for each ViT
layer (i.e., MSA and MLP), our GEMM engine processes the input,
weight, and output data in tiles: a small tile of the input (tokens)
and weight of each ViT layer are first loaded from the off-chipDDR memory to the on-chip buffers, then they are processed by
the GEMM engine all on-chip. To improve the performance, the
double buffering technique is applied again to overlap the off-chip
memory accesses and GEMM computation, shown in Figure 6.
Next, we present our design of the basic hardware units in the
GEMM engine and the corresponding DSP (digital signal processor)
packing optimization, as well as the hardware resource and latency
modeling for the tiled GEMM design.
4.2 Unification of Atomic Computation
One major challenge in the FPGA accelerator design is to efficiently
support flexible mixed ratios of different bit-width computations
across ViT layers. On one hand, putting multiple copies of hardware
accelerator designs for each mixed-ratio (i.e., each layer) simultane-
ously on the FPGA leads to severe hardware resource contention
and under-utilization, since layers are executed sequentially. On
the other hand, pre-synthesizing multiple copies of hardware accel-
erator designs for each layer and reconfiguring the FPGA for each
layer incurs significant FPGA reconfiguration overhead.
Inspired by the approach proposed in QGTC [ 52] to support
arbitrary bit-width computation for quantized graph neural net-
works on GPUs, in our FPGA hardware design, we unify the basic
processing elements to process 4-bit weight atomic computations
and construct the 8-bit weight data computations using two 4-bit
weight data operations as such: for multiplication between an N-bit
activation value ( 𝑎𝑐𝑡𝑁) and an 8-bit weight value ( 𝑤𝑔𝑡 8), we derive
the corresponding product as:
𝑎𝑐𝑡𝑁·𝑤𝑔𝑡 8=𝑎𝑐𝑡𝑁·𝑤𝑔𝑡ℎ4<<4+𝑎𝑐𝑡𝑁·𝑤𝑔𝑡𝑙4, (3)
where𝑤𝑔𝑡ℎ4and𝑤𝑔𝑡𝑙4represent the higher and lower 4-bit data
of𝑤𝑔𝑡 8, respectively. The multiplication result between 𝑎𝑐𝑡𝑁and
𝑤𝑔𝑡ℎ4are left shifted by 4 bits.
Based on this unification, we propose hybrid signed/unsigned
DSP packing to handle the 4-bit weight atomic computation.
4.3 Proposed Hybrid Signed/Unsigned DSP
Packing
To fully exploit the potential of DSP resources on FPGAs, we pack
multiple low-bit multiplications within each DSP block follow-
ing [57,58]. Each DSP block (DSP48E2) on the AMD/Xilinx ZCU102
FPGA board could support the computation of 𝑃=(𝐴+𝐷)×𝐵, where
both𝐴and𝐷are 27-bit operands, 𝐵is an 18-bit operand, and 𝑃is
the 45-bit output. In our study, we explore the following two DSP
packing schemes and discuss their design trade-offs. The activation
bit-width𝑁is set to 6 to fully exploit the DSP for computation.
•Packing factor 3 (3 weights sharing 1 activation). In
Figure 7 (a), three 4×6-bit multiplications are packed into a
single DSP block, by holding one 6-bit signed activation in
port𝐵and three 4-bit weight values in port 𝐷. To pack three
weights into a single 27-bit port 𝐷, look-up tables (LUTs)
are utilized to first combine two weights and then integrate
them with the third weight data. With this DSP packing
scheme, for the W4A6 (i.e., 4-bit weight and 6-bit activation)
computation, we could pack three 4-bit weights that share
the same activation. And for the W8A6 computation, we
could use two DSPs to process the upper and lower 4-bit
ICS ’24, June 4–7, 2024, Kyoto, Japan
of three 8-bit weights in parallel. Note that after the 8-bit
weights are decomposed into two 4-bit weights, only the
upper 4-bit weights contain the sign bits and should be sign-
extended (required by DSP for output correctness [ 57,58]),
the lower 4-bit weights should be treated as unsigned values.
•Packing factor 4 (2 weights sharing 2 activations). In
Figure 7 (b), four 4×6-bit multiplications are packed into
a single DSP block, by holding two 6-bit signed activation
values in port 𝐷and two 4-bit weights in port 𝐵. It is worth
mentioning the port placement of the activation and weight
values are swapped from the packing factor 3 scheme, to
increase the packing strength. With this DSP packing scheme,
for the W4A6 computation, we could pack a pair of two 4-
bit weights that share the same pair of activation values.
And for the W8A6 computation, a similar technique as the
previous packing scheme is used to separately handle the
upper and lower 4-bit values of an 8-bit weight. Again for the
two decomposed 4-bit weights, only the upper 4-bit weights
contain the sign bit and should be sign-extended (required
by DSP for output correctness [ 57,58]), but the lower 4-bit
weights should be treated as unsigned values.
4.4 Hardware Resource and Latency Modeling
Here, we present our hardware resource and latency modeling used
in the hardware-oriented evolution search.
Table 3: Notations for Quasar-ViT accelerator
Notation Description
𝑀(𝑁) Number of output (input) channels
𝐹 Number of token sequences
𝑇𝑛 Tiling size for data in input channel dimension for
each head
𝑇𝑚 Tiling size for data in output channel dimension
𝑁ℎ Total number of heads
𝑃𝐹 Parallel factor along the number of tokens
𝐷𝑎𝑐𝑡 Number of data packed as one for activations
𝐷𝑤𝑔𝑡 Number of data packed as one for weights
𝐴in (𝐴out,
𝐴wgt)Number of AXI ports used for data transfer of input
(output, weight) tile
𝐿in (𝐿wgt,
𝐿out,𝐿cmpt)Number of clock cycles for input transfer (weight
transfer, output transfer, computation) for a tile
𝑆dsp(𝑆lut) Available number of DSPs (LUTs) on FPGA
𝐶dsp DSP cost for each MAC operation
𝐶lut LUT cost for each MAC operation
𝐶𝑑𝑠𝑝
𝑙𝑢𝑡Number of LUTs used by a multiplication executed
on DSPs
𝑁𝑑𝑠𝑝 Number of multiplication executed on DSPs
𝑁𝑙𝑢𝑡 Number of multiplication executed on LUTs
𝑁𝑡𝑜𝑡 The total number of multiplication on FPGA
𝛾𝑑𝑠𝑝(𝛾𝑙𝑢𝑡) DSP (LUT) utilization threshold
𝑓 FPGA accelerator frequency
𝐹𝑃𝑆 Frames per second
4.4.1 Resource Modeling. To help guide the neural architecture
search, we provide details of the resource and latency models ofour FPGA accelerator design (mainly the GEMM engine). Table 3
lists the notations used in our models. We design our FPGA accel-
erator to fully leverage the available FPGA computing resources
(i.e., DSPs and LUTs), on-chip memory (i.e., BRAMs), and off-chip
memory bandwidth. To fully exploit the computing capability with
the available hardware resources, We maximize the total number of
parallel basic hardware compute units using both DSPs (i.e., 𝑁𝑑𝑠𝑝)
and LUTs (i.e., 𝑁𝑙𝑢𝑡) for the datapath of our accelerator as
𝑁𝑡𝑜𝑡=maximize
𝑁𝑑𝑠𝑝+𝑁𝑙𝑢𝑡
, (4)
while satisfying the following resource constraints
𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝≤𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝, (5)
𝑁𝑙𝑢𝑡·𝐶𝑙𝑢𝑡+𝑁𝑑𝑠𝑝·𝐶𝑑𝑠𝑝
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡, (6)
where constraints 5 and 6 bound the DSP and LUT utilization to
be under the allowable thresholds, i.e., 𝛾𝑑𝑠𝑝and𝛾𝑙𝑢𝑡with the total
resource amounts denoted by 𝑆𝑑𝑠𝑝and𝑆𝑙𝑢𝑡. The hardware costs of
each multiplication implementation are denoted as 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡.
In order to choose the best implementation method for the basic
hardware units of our design, we characterize the FPGA resource
consumption using Xilinx Vivado 2020.1 [ 59] for the three cases in
Table 4, i.e., (a) multiplications executed on DSPs with packing fac-
tor of 3, (b) multiplications executed on DSPs with packing factor of
4, and (c) multiplications executed purely using LUTs. As observed
in Table 4, we derive the hardware costs of each multiplication
implementation, particularly, the LUT costs for pure-LUT-based
and DSP-based methods correspond to 𝐶𝑙𝑢𝑡and𝐶𝑑𝑠𝑝
𝑙𝑢𝑡. Note that the
DSP-based approach also consumes LUTs, due to data packing on
the input operands and output data construction operations, such
as bit shifting and data accumulation. Regarding the efficiency
lost by decomposing 8-bit to 4-bit, for the composed W8A6 com-
putation, on average, we can achieve one computation with 25.8
LUTs and 0.5 DSP or purely 66.7 LUTs. In contrast, direct W8A6
computation used in [ 40] (i.e., packing two W8A6 operations within
one DSP method) requires 21.5 LUTs and 0.5 DSP or purely 62.2
LUTs. Since most of the weights are in 4-bit, using decomposing
does not affect the overall performance much by a slight increase
in the LUT utilization. In terms of the efficiency of DSP packing, a
single DSP can pack four W4A6 operations at most theoretically,
which is achieved by our approach.
For the LUT usage, shown in Table 4, we have:
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡<𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡<𝐶𝑙𝑢𝑡. (7)
In the final implementation, regarding which DSP packing scheme
to use and whether to use the pure-LUT-based method for the basic
hardware compute units, there are several situations according to
the available FPGA resources.
Situation-1: When𝑆𝑙𝑢𝑡is limited and insufficient to hold the
LUT consumption of full utilization of DSP packing with a factor
of 3, denoted as:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡. (8)
In this case, to fully utilize the computation resources, we directly
allocate DSP-based computations with a packing factor of 3 as much
as possible until we reach the LUT resource limit.
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
D Port 27-bit
B Port 18-bit
P Port
48 Bits (45 Bits Usable)X
Activation 6-bit
Weight 4-bitWeight 4-bit
Activation 6-bit = +Weight 8-bit
Signed number unsigned number
(a) Packing Factor of 3
(b) Packing Factor of 4
Figure 7: Illustration of DSP multiplication packing schemes for (a) 3 weights sharing 1 activation with packing factor of 3, and
(b) 2 weights sharing 2 activations with packing factor of 4.
Table 4: FPGA resource consumption for a single DSP-based
or LUT-based basic hardware compute unit. W4A6 denotes
4-bit weight and 6-bit activation; W8A6 denotes 8-bit weight
and 6-bit activation.
pure LUT-basedDSP-based
packing
factor 3packing
factor 4
W4A6𝐶𝐿𝑈𝑇 33.3 10.9 12.9
𝐶𝐷𝑆𝑃 0 0.33 0.25
W8A6𝐶𝐿𝑈𝑇 66.7 21.9 25.8
𝐶𝐷𝑆𝑃 0 0.67 0.5
W8A6
(direct)𝐶𝐿𝑈𝑇 62.2 21.5
𝐶𝐷𝑆𝑃 0 0.5
Situation-2: When𝑆𝑙𝑢𝑡is enough to hold all the LUT consump-
tion from DSP packing with the factor of 4, satisfying:
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡. (9)
Based on Eq. 4, 5, 6 and 9, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
(4·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡−3·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡·𝐶𝑙𝑢𝑡.
(10)
If it does not satisfy Eq. 10, we perform DSP-based computations
with a packing factor of 3. Besides that, for the remaining available
LUT resources, pure-LUT-based computation is also conducted in
both cases.
Situation-3: When𝑆𝑙𝑢𝑡is between the LUT demands by fully
deploying DSP computations with packing factors of 3 and 4, satis-
fying:
3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡≤
4·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡.(11)
Based on Eq. 4, 5, 6, and 11, we can conclude that using DSP
packing with the factor of 4 is more efficient if it meets the following
condition:
𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡+3·𝑆𝑑𝑠𝑝·𝛾𝑑𝑠𝑝·(𝐶𝑙𝑢𝑡−𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 3
𝑙𝑢𝑡)
𝐶𝑙𝑢𝑡≤𝑆𝑙𝑢𝑡·𝛾𝑙𝑢𝑡
𝐶𝑑𝑠𝑝,𝑝𝑎𝑐𝑘 4
𝑙𝑢𝑡,
(12)
Input Sequence
Load Input T ile
Output Sequence
StoreOutput T ile Weight Matrix
LoadWeight T ile Figure 8: Data tiling in ViT computations.
In this case, we conduct only DSP-based computations with a
packing factor of 4. Otherwise, if it does not satisfy Eq. 12, we per-
form DSP-based computations with a packing factor of 3 and pure
LUT-based computation for the remaining available LUT resource.
4.4.2 Latency Modeling. As discussed in the Hardware Design Sec-
tion, our GEMM hardware engine accelerates the major MSA and
MLP modules and processes their input, weight, and output data in
tiles, as shown in Figure 8. our GEMM hardware engine accelerates
the major MSA and MLP modules and processes their input, weight,
and output data in tiles, as shown in Figure 8. Each MSA can be
seen as multiple parallel matrix multiplications. The accelerator is
designed to process parallel computations within each head. This
input channel splitting is also done for fully connected (FC) layers,
each containing one matrix multiplication for compatibility, and
the results need to be accumulated from all the input channels
in all the heads. Furthermore, the computing engine exploits fine-
grained data and operation parallelisms and can process 𝑇𝑚·𝑇𝑛
multiply-accumulate (MAC) operations in parallel.
ICS ’24, June 4–7, 2024, Kyoto, Japan
We model the inference latency of our hardware design based
on the number of clock cycles. For a layer 𝑖in ViT, since data
packing can be used to transfer multiple (i.e., 𝐷𝑎𝑐𝑡or𝐷𝑤𝑔𝑡) values
at the same time in each AXI port, the clock cycles for loading one
input/weight tile and storing one output tile, are calculated as:
𝐿in=𝑇𝑛
𝐷𝑎𝑐𝑡
·𝐹
𝐴in
,
𝐿wgt=𝑇𝑛
𝐷𝑤𝑔𝑡
·𝑇𝑚
𝐴wgt
,
𝐿out=𝑇𝑚
𝐷𝑎𝑐𝑡
·𝐹
𝐴out
,(13)
where𝐿in,𝐿wgtand𝐿outindicate the number of the clock cycles
of input, weight, and output transfer for one corresponding tile,
respectively.
The clock cycle number to compute one tile is
𝐿cmpt=max𝐹
𝑃𝐹
,𝑇𝑛·𝑇𝑚·𝐹
𝑁𝑡𝑜𝑡
, (14)
where the first term is calculated by the latency model. The total
number of multiplications needed to compute one tile of matrix
multiplication is 𝑇𝑛·𝑇𝑚·𝐹. Each tile has two levels of parallelism:
one is along the 𝑇𝑛and𝑇𝑚dimension and the parallel factor is
𝑇𝑛·𝑇𝑚(i.e., fully parallel); and the other is along the 𝐹dimension
and the parallel factor is 𝑃𝐹. Therefore, the first term is calculated asl
𝐹
𝑃𝐹m
. The second term is limited by the resource constraint, where
we can support at most 𝑁𝑡𝑜𝑡parallel multipliers (Eq. 4) due to the
resource constraint.
With the double buffers overlapping the data loading and com-
putation of the tiles, the overall clock cycle number for processing
one tile is𝐿1=max{𝐿in,𝐿wgt,𝐿cmpt}.
To obtain the accumulation of output results, this process is
performed multiple times (i.e., processingl
𝑁
𝑇𝑛m
input tiles). The
clock cycle number for calculating the whole output tile is 𝐿2=
max
𝐿1·l
𝑁
𝑇𝑛m
+𝐿cmpt,𝐿out
.
Since there arel
𝑀
𝑇𝑚m
number of output tiles, the total number of
clock cycles for a ViT layer 𝑖is described by
𝐿𝑖
tot=𝑀
𝑇𝑚
·𝐿2+𝐿out. (15)
Under a working frequency 𝑓, the FPSis calculated as:
𝐹𝑃𝑆=𝑓Í
𝑖𝐿𝑖
tot. (16)
5 EXPERIMENTAL RESULTS
5.1 Experimental Setup
Our supernet training process takes 700 epochs with a batch size of
2048. The learning rate is set to 5×10−4initially and decayed with
a cosine annealing schedule. The AdamW [ 28] optimizer is used
with the epsilon value of 1𝑒−8and weight decay of 0.05. Additional
training optimizations, such as warmup and label smoothing are
performed during training. The number of warmup epochs and
label smoothing factor are set as 20 and 0.1, respectively. After
supernet training, we perform the hardware-oriented evolution
search, without subnet retraining.Our training is conducted on 8 NVIDIA Ampere A100 GPUs
with CUDA 11.0 and PyTorch 1.7 frameworks on the Ubuntu oper-
ating system. To test the effectiveness of our framework, we also
implement Quasar-ViT framework on the Xilinx ZCU102 embedded
FPGA platform with quad-core ARM Cortex-A53 and XCZU9EG
FPGA chip. The FPGA working frequency is set to 150 MHz for all
the designs implemented via Xilinx Vitis and Vitis HLS 2020.1.
5.2 Accuracy Results
Here we analyze the accuracy results of our Quasar-ViT framework.
The weight precision is mixed with 4-bit and 8-bit, as mentioned
earlier, and the activation bit-width is determined by the hardware
feature. Without loss of generality, we use activation of 8-bit to
evaluate the accuracy in the ablation study of knowledge distillation
and supernet layer scaling.
5.2.1 Ablation Study of Knowledge Distillation and Supernet Layer
Scaling. To evaluate the compatibility of knowledge distillation
and our proposed SLS, we conduct an ablation study on both of
them. Without loss of generality and to prevent interference from
different model sizes and different quantization mixed ratios from
the searched subnet, we unify the search constraint with pure W8A8
(8-bit for both weight and activation) quantization implementation.
As shown in Table 6, we conduct four different settings of Quasar-
ViT with the unified model size and quantization scheme. The ac-
curacy of the four cases is 74.1% (w/o distillation and SLS), 75.6%
(only distillation), 74.9% (only SLS), and 76.1% (with both of them),
respectively. Knowledge distillation and SLS strategies are orthogo-
nal to each other, and both improve the model accuracy. Using them
together provides a better result. Given the observed effectiveness
of our proposed SLS strategy and the seamless compatibility of our
framework with knowledge distillation, we opt to incorporate both
strategies in our following experiments. Here we also quantize the
baseline DeiT-T [ 42] and compare it with our method without SLS
and distillation. Even without SLS and distillation, our quantization
NAS approach achieves a much better model accuracy than the
full-precision and the quantized (W8A8) DeiT-T models.
5.2.2 Ablation Study of Mixed-Ratio and Quantization Scheme. To
assess the efficacy of our row-wise flexible mixed-precision quanti-
zation scheme, we conducted an ablation study examining both the
quantization scheme itself and the 8-bit mixed ratio, as outlined in
Table 7. Since Quasar-ViT automatically searches the mixed ratios,
here we pick up the best model from the search stage for differ-
ent mixed ratios and compare them with the counterparts under
the fixed row-wise mixed quantization scheme. The results indi-
cate a consistent improvement in accuracy across different 8-bit
mixed-ratio levels with our flexible mixed scheme, underscoring
the efficiency of our proposed quantization scheme.
5.2.3 Overall Accuracy Results. Table 5 compares representative
ViT-based works with our proposed Quasar-ViT. Since many ViT-
based works do not incorporate model quantization, we also con-
sider the bit-width in the model size and the equivalent number of
total bit operations (BOPs).
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Table 5: Comparison of representative ViT-based works with our proposed Quasar-ViT.
ModelQuantization #Params Model Size MACs MAC Bit-width Equivalent Top-1 Accuracy
Mixed Type(𝑀) (𝑀𝐵) (𝐺) Weight Activation BOPs (𝐺) ( %)
DeiT-T [42] - 5.7 22.8 1.3 32 32 1.3×10372.2
T2T-T [63] - 4.3 17.2 1.1 32 32 1.1×10371.7
PiT-T [14] - 10.6 42.4 1.4 32 32 1.4×10372.4
LocalViT-T [21] - 5.9 23.6 1.3 32 32 1.3×10374.8
FQ-ViT [24] Model-wise 5.7 5.7 1.3 8 8 80.6 71.6
Q-ViT [20] Head-wise 5.7 - - 4-8 4-8 - 72.8
QUASAR-S (ours) Row-wise 5.9 4.1 1.4 4 & 8 6 45.6 74.9
PVT [51] - 24.5 98.0 3.8 32 32 3.9×10379.8
DeiT-S [42] - 22.9 91.6 4.6 32 32 4.8×10379.9
Swin-T [26] - 28 112.0 4.5 32 32 4.7×10381.2
BossNAS [18] - - - 3.4 32 32 3.5×10380.5
PTQ [27] Layer-wise 22.9 16.6 4.6 6-10 6-10 - 75.1
FQ-ViT [24] Model-wise 22.9 22.9 4.6 8 8 294.4 79.1
Q-ViT [20] Head-wise 22.9 - - 4-8 4-8 - 80.1
QUASAR-L1 (ours) Row-wise 14.7 9.8 3.2 4 & 8 6 103.8 78.6
QUASAR-L2 (ours) Row-wise 22.6 15.8 4.8 4 & 8 6 163.2 80.4
Table 6: Comparison between different settings of QUASAR-
Small with and without knowledge distillation (KD) and su-
pernet layer scaling (SLS) on ImageNet dataset.
ModelSetting #Params Quantization Top-1 Acc.
KD SLS (M) Scheme (%)
DeiT-T [42] No No 5.7 W32A32 72.2
DeiT-T (quant) No No 5.7 W8A8 71.5
Ours No No 5.9 W8A8 74.1
Ours Yes No 5.9 W8A8 75.6
Ours No Yes 5.9 W8A8 74.9
Ours Yes Yes 5.9 W8A8 76.1
Table 7: Comparison between different settings of 8-bit quan-
tization mixed-ratio and quantization schemes.
Scheme Model Size (MB) 8-bit mixed-ratio (%) Acc. (%)
Fixed row-wise 3.6 23 73.5
Flexible row-wise 3.6 23 74.2
Fixed row-wise 4.1 39 74.1
Flexible row-wise 4.1 39 74.9
As shown in Table 5, we present three Quasar models for dif-
ferent accuracy levels: QUASAR-S searched within the QUASAR-
Small supernet, and QUASAR-L1, QUASAR-L2 searched within the
QUASAR-Large supernet.
Our QUASAR-S achieves 74.9% top-1 accuracy with only 4.1 MB
model size and 1.4 GMACs, Compared with the representative ViT-
based model LocalViT-T [ 21] under a similar accuracy, our model
size is only 17.4% of that in LocalViT-T; although the GMACs num-
bers are similar, our MAC unit is much more hardware efficient
as it is for a 4-bit/8-bit weight and a 6-bit activation instead of a
32-bit floating-point MAC unit in LocalViT-T. For a higher modelTable 8: Comparisons of FPGA implementations for ViTs
on ImageNet, including DeiT-S and Auto-ViT-Acc from [ 22],
and our Quasar-ViT, all running at 150MHz on the same
AMD/Xilinx ZCU102 embedded FPGA platform.
DeiT-SAuto-ViT Quasar-ViT
-Acc L2 L1 S
Quant. NoMixed Mixed Mixed Mixed
Scheme Precision Precision Precision
Weight 32 4 & 8 4 & 8 4 & 8 4 & 8
Act. 32 8 6 6 6
Top-1 Acc. 79.9 78.7 80.4 78.6 74.9
kLUT 47% 67% 66% 66% 65%
FF - - 31% 31% 30%
DSP 69% 62% 69% 69% 69%
BRAM - - 44% 44% 44%
accuracy level, our QUASAR-L1 and QUASAR-L2 achieve 78.5%
and 80.4% top-1 accuracy, respectively. Among them, QUASAR-L2
only has a 15.8 MB model size with a computation volume of 4.8
GMACs, which obtains the smallest BOPs with a similar level of
accuracy compared with other baselines. Specifically, compared
with PTQ [ 27] (16.6 MB, top-1 75.1%), QUASAR-L2 achieves a simi-
lar model size and GMACs with 5.2% higher accuracy. Compared
with ViT NAS framework BossNAS [ 18], we additionally achieve
low-bit quantization with a much smaller BOPS and similar ac-
curacy. Compared with quantization-aware training framework
Q-ViT [ 20] using multiple quantization bit-widths in the range of 4
to 8, which incurs inefficiency and hardware under-utilization, our
results show better accuracy with a more unified and hardware-
friendly quantization scheme.
ICS ’24, June 4–7, 2024, Kyoto, Japan
5.3 Comparison of Hardware Results on FPGA
We implement a proof-of-concept hardware accelerator for our
Quasar-ViT on the AMD/Xilinx ZCU102 embedded FPGA platform.
We also compare our results to Auto-ViT-Acc [ 22], the state-of-
the-art FPGA accelerator for ViT with mixed-scheme quantization
(without NAS). We retrieve the hardware results for Auto-ViT-Acc
(which is quantized from DeiT-S) and the original DeiT-S on the
same Xilinx ZCU102 FPGA platform from [22].
Power (W)02.557.510
DeiT-SAuto-ViT-AccQuasar-ViT-L2Quasar-ViT-L1Quasar-ViT-SmallFPS075150225300
FPS/W07.51522.530
Accuracy (%)6066727884
Figure 9: Comparisons between DeiT-S, Auto-ViT-Acc
from [22], and our Quasar-ViT.
As shown in Table 8 and Figure 9, our approach consistently
outperforms the previous work. Specifically, compared with DeiT-
S [42], our QUASAR-L2 achieves 2.6 ×higher inference frames per
second (FPS) with 0.5% better accuracy. Compared with Auto-ViT-
Acc [ 22], our QUASAR-L1 achieves 1.6 ×higher FPS (159.6) with
a similar model accuracy level, and our QUASAR-L2 achieves a
similar level of FPS with 1.7% better top-1 accuracy.
The improvement in model accuracy and inference performance
within our framework is attributed to two key factors. Firstly, our
approach involves the training and search for a customized network
architecture, specifically tailored for both the mixed-precision quan-
tization schemes and the targeted inference latency. This strategy
enhances adaptability and efficiency, surpassing the achievements
of previous methodologies.
Secondly, our novel supernet training algorithm, coupled with
the proposed hybrid DSP packing design, allows for distinct quanti-
zation mixed ratios across various model layers. This fine-grained
model achieves better flexibility than the previous approaches, un-
leashing the full potential of mixed-precision quantization.
With regard to the efficiency of our hardware accelerator de-
sign, the performance is mainly limited by DSP, LUT, and off-chip
memory bandwidth. On par with Auto-ViT-Acc [ 22], our design
achieves 150MHz frequency with about 66% usage of LUTs and
69% DSPs without timing violations. Note a typical FPGA design
usually utilizes approximately 60% to 70% of the available FPGA
resources; otherwise, it may fail during the placement and routing
phase due to congestion or result in a lower operating frequency.
Without considering the timing violation, the maximum theoretical
expected performance is based on the 100% utilization ratio for bothDSP, LUTs, and bandwidth, which can achieve about 1.47x of our
reached FPS for the same model.
5.4 Other Transformer-based Model Accuracy
Results
To demonstrate the scalability and versatility of our methods, we
applied them across various datasets and applications, notably de-
ploying them on a large language model (LLM). This choice is mo-
tivated by two key factors. Firstly, LLM shares a transformer-based
architecture similar to that of Vision Transformer (ViT), aligning
with the framework that we propose. Secondly, LLM is frequently
integrated with ViT in text-to-image/video applications, making
it an ideal candidate to showcase the scalability of our approach
across both models and its potential for real-world applications.
Our | Section not found | Section not found | Section not found | Section not found | Section not found | comparative analysis, presented in Table 9, utilizes the
renowned LLM model, LLaMA, as the foundation for our supernet.
We juxtapose our optimized results with those of LLaMA-7B [ 44] on
the commonly used WikiText-2 dataset for LLMs, with perplexity
score (PPL) serving as the evaluation metric, where lower scores
indicate superior performance. According to the comparison results,
our method shows a constant pattern, achieving a similar level of
PPL with a much smaller model size.
Table 9: Result comparison on large language model.
Model Model Size (GB) W # Bits A # Bits PPL
LLaMA-7B [44] 26.8 FP32 FP32 5.68
Ours 6.7 INT8 INT8 5.73
Ours 4.8 INT4 & 8 INT8 5.91
5.5 Training Cost Comparison
Prior co-design frameworks, such as APQ [ 50], have also delved into
the integration of neural architecture search (NAS) and quantiza-
tion techniques. Please note that APQ is based on the convolutional
neural network (CNN) and BitFusion platform [ 50]. To the best of
our knowledge, we compare our Quasar-ViT models (both small
and large variants) and the APQ result. As detailed in Table 10,
our approach demonstrates superior FPS performance while main-
taining comparable or even higher model accuracy, achieved at a
reduced training cost. Compared with the 2,400 GPU hours training
cost of APQ [ 50], our approach only consumes 768 and 1,344 GPU
hours for the small and large versions of Quasar-ViT, respectively.
Our training setting has been illustrated in Section 5.1.
Table 10: Training cost and accuracy comparison with other
NAS and quantization co-design.
Method Training cost (GPU hours) FPS Acc.(%)
APQ [50] 2400 82.2 75.1
QUASAR-S 768 101.5 74.9
QUASAR-L 1344 251.6 80.4
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
6 CONCLUSION
In this work, we propose Quasar-ViT, a hardware-oriented quantization-
aware network architecture search framework to enable efficient
ViT deployment on resource-constrained edge devices. First, we
proposed hardware-friendly quantization techniques including flex-
ible row-wise mixed-precision quantization scheme and intra-layer
mixed-precision weight entanglement in architecture search to-
wards high accuracy and low training cost for efficient implemen-
tation. Second, we propose 4-bit weight atomic computation and
hybrid signed/unsigned DSP packing for FPGA implementation,
then incorporate latency/resource modeling to enable the hardware-
oriented architecture search. Third, we extend the supernet layer
scaling technique to further improve the training convergence and
supernet accuracy. We also demonstrate the compatibility of our
proposed framework with knowledge distillation during super-
net training. Finally, we developed an efficient hardware-oriented
search algorithm—integrated with hardware latency and resource
modeling—to search the efficient subnet with high accuracy under
a given inference latency target and implemented the searched
model on real FPGA hardware for validation. From the experiment
evaluation results, our approach achieves 101.5, 159.6, and 251.6
FPS on the AMD/Xilinx ZCU102 FPGA board with 80.4%, 78.6%,
and 74.9% top-1 accuracy for ImageNet, respectively, consistently
outperforming prior works.
ACKNOWLEDGMENTS
This work was supported in part by NSERC Discovery Grant RGPIN-
2019-04613, DGECR-2019-00120, Alliance Grant ALLRP-552042-
2020; CFI John R. Evans Leaders Fund; BC Knowledge Development
Fund; Army Research Office/Army Research Laboratory via grant
W911-NF-20-1-0167 to Northeastern University; National Science
Foundation CCF-1937500, CNS-1909172, and IIS-2310254. No exter-
nal funding support to CD and MS for this project.
REFERENCES
[1]Haoli Bai, Wei Zhang, Lu Hou, Lifeng Shang, Jing Jin, Xin Jiang, Qun Liu, Michael
Lyu, and Irwin King. 2021. BinaryBERT: Pushing the Limit of BERT Quantization.
InProceedings of the 59th Annual Meeting of the Association for Computational Lin-
guistics and the 11th International Joint Conference on Natural Language Processing
(Volume 1: Long Papers) .
[2]Bowen Baker, Otkrist Gupta, Nikhil Naik, and Ramesh Raskar. 2017. Designing
Neural Network Architectures using Reinforcement Learning. In International
Conference on Learning Representations (ICLR) .
[3]Gabriel Bender, Pieter-Jan Kindermans, Barret Zoph, Vijay Vasudevan, and Quoc
Le. 2018. Understanding and simplifying one-shot architecture search. In Pro-
ceedings of the International Conference on Machine Learning (ICML) . 550–559.
[4]Han Cai, Tianyao Chen, Weinan Zhang, Yong Yu, and Jun Wang. 2018. Effi-
cient architecture search by network transformation. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 32.
[5]Sung-En Chang, Yanyu Li, Mengshu Sun, Runbin Shi, Hayden K-H So, Xuehai
Qian, Yanzhi Wang, and Xue Lin. 2021. Mix and Match: A novel FPGA-centric deep
neural network quantization framework. In 2021 IEEE International Symposium
on High-Performance Computer Architecture (HPCA) . 208–220.
[6]Minghao Chen, Houwen Peng, Jianlong Fu, and Haibin Ling. 2021. Autoformer:
Searching transformers for visual recognition. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 12270–12280.
[7]Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang,
Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. 2018. Pact: Parameterized
clipping activation for quantized neural networks. arXiv:1805.06085 (2018).
[8]Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. 2015. Binarycon-
nect: Training deep neural networks with binary weights during propagations.
InAdvances in Neural Information Processing Systems (NeurIPS) . 3123–3131.[9]Zhen Dong, Zhewei Yao, Amir Gholami, Michael W Mahoney, and Kurt Keutzer.
2019. Hawq: Hessian aware quantization of neural networks with mixed-
precision. In Proceedings of the IEEE/CVF International Conference on Computer
Vision (ICCV) .
[10] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xi-
aohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg
Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. 2021. An Image is
Worth 16x16 Words: Transformers for Image Recognition at Scale. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=YicbFdNTTy
[11] Zichao Guo, Xiangyu Zhang, Haoyuan Mu, Wen Heng, Zechun Liu, Yichen Wei,
and Jian Sun. 2020. Single path one-shot neural architecture search with uniform
sampling. In Proceedings of the European Conference on Computer Vision (ECCV) .
Springer, 544–560.
[12] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 2016. Deep residual
learning for image recognition. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 770–778.
[13] Zhezhi He and Deliang Fan. 2019. Simultaneously optimizing weight and quan-
tizer of ternary neural network using truncated gaussian approximation. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recogni-
tion (CVPR) .
[14] Byeongho Heo, Sangdoo Yun, Dongyoon Han, Sanghyuk Chun, Junsuk Choe,
and Seong Joon Oh. 2021. Rethinking spatial dimensions of vision transformers.
arXiv:2103.16302 (2021).
[15] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. 2015. Distilling the knowledge in
a neural network. arXiv:1503.02531 (2015).
[16] Intel. 2024. Intel ®Xeon®Silver 4214 Processor. https://ark.intel.com/content/
www/us/en/ark/products/193385/intel-xeon-silver-4214-processor-16-5m-
cache-2-20-ghz.html. Last accessed Jan. 18, 2024.
[17] Cong Leng, Zesheng Dou, Hao Li, Shenghuo Zhu, and Rong Jin. 2018. Extremely
low bit neural network: Squeeze the last bit out with admm. In Proceedings of the
AAAI Conference on Artificial Intelligence .
[18] Changlin Li, Tao Tang, Guangrun Wang, Jiefeng Peng, Bing Wang, Xiaodan
Liang, and Xiaojun Chang. 2021. Bossnas: Exploring hybrid cnn-transformers
with block-wisely self-supervised neural architecture search. In Proceedings of
the IEEE/CVF International Conference on Computer Vision (ICCV) . 12281–12291.
[19] Yuhang Li, Xin Dong, and Wei Wang. 2020. Additive Powers-of-Two Quantization:
An Efficient Non-uniform Discretization for Neural Networks. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=BkgXT24tDS
[20] Yanjing Li, Sheng Xu, Baochang Zhang, Xianbin Cao, Peng Gao, and Guodong
Guo. 2022. Q-ViT: Accurate and Fully Quantized Low-bit Vision Transformer. In
Advances in Neural Information Processing Systems (NeurIPS) . https://openreview.
net/forum?id=fU-m9kQe0ke
[21] Yawei Li, Kai Zhang, Jiezhang Cao, Radu Timofte, and Luc Van Gool. 2021.
LocalViT: Bringing Locality to Vision Transformers. arXiv:2104.05707 [cs.CV]
[22] Zhengang Li, Mengshu Sun, Alec Lu, Haoyu Ma, Geng Yuan, Yanyue Xie, Hao
Tang, Yanyu Li, Miriam Leeser, Zhangyang Wang, Xue Lin, and Zhenman Fang.
2022. Auto-vit-acc: An fpga-aware automatic acceleration framework for vi-
sion transformer with mixed-scheme quantization. In 2022 32nd International
Conference on Field-Programmable Logic and Applications (FPL) . IEEE, 109–116.
[23] Zhengang Li, Geng Yuan, Wei Niu, Pu Zhao, Yanyu Li, Yuxuan Cai, Xuan Shen,
Zheng Zhan, Zhenglun Kong, Qing Jin, et al .2021. NPAS: A Compiler-aware
Framework of Unified Network Pruning and Architecture Search for Beyond
Real-Time Mobile Acceleration. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 14255–14266.
[24] Yang Lin, Tianyu Zhang, Peiqin Sun, Zheng Li, and Shuchang Zhou. 2022. FQ-ViT:
Post-Training Quantization for Fully Quantized Vision Transformer. In Proceed-
ings of the Thirty-First International Joint Conference on Artificial Intelligence,
IJCAI-22 . 1173–1179.
[25] Chenxi Liu, Barret Zoph, Maxim Neumann, Jonathon Shlens, Wei Hua, Li-Jia Li,
Li Fei-Fei, Alan Yuille, Jonathan Huang, and Kevin Murphy. 2018. Progressive
neural architecture search. In Proceedings of the European conference on computer
vision (ECCV) . 19–34.
[26] Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin,
and Baining Guo. 2021. Swin transformer: Hierarchical vision transformer using
shifted windows. In Proceedings of the IEEE International Conference on Computer
Vision (ICCV) .
[27] Zhenhua Liu, Yunhe Wang, Kai Han, Siwei Ma, and Wen Gao. 2021. Post-Training
Quantization for Vision Transformer. In Advances in Neural Information Processing
Systems (NeurIPS) .
[28] Ilya Loshchilov and Frank Hutter. 2019. Decoupled Weight Decay Regular-
ization. In International Conference on Learning Representations (ICLR) . https:
//openreview.net/forum?id=Bkg6RiCqY7
[29] Qian Lou, Feng Guo, Minje Kim, Lantao Liu, and Lei Jiang. 2019. AutoQ: Auto-
mated Kernel-Wise Neural Network Quantization. In International Conference on
Learning Representations (ICLR) .
ICS ’24, June 4–7, 2024, Kyoto, Japan
[30] Risto Miikkulainen, Jason Liang, Elliot Meyerson, Aditya Rawal, Dan Fink, Olivier
Francon, Bala Raju, Hormoz Shahrzad, Arshak Navruzyan, Nigel Duffy, et al .
2019. Evolving deep neural networks. In Artificial Intelligence in the Age of Neural
Networks and Brain Computing . Elsevier, 293–312.
[31] Bowen Pan, Rameswar Panda, Yifan Jiang, Zhangyang Wang, Rogerio Feris, and
Aude Oliva. 2021. IA-RED2: Interpretability-Aware Redundancy Reduction for
Vision Transformers. Advances in Neural Information Processing Systems (NeurIPS)
34 (2021), 24898–24911.
[32] Hieu Pham, Melody Guan, Barret Zoph, Quoc Le, and Jeff Dean. 2018. Effi-
cient neural architecture search via parameters sharing. In Proceedings of the
International Conference on Machine Learning (ICML) . 4095–4104.
[33] PyTorch. 2024. PYTORCH PROFILER. https://pytorch.org/tutorials/recipes/
recipes/profiler_recipe.html. Last accessed Jan. 18, 2024.
[34] Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, and Piotr
Dollár. 2020. Designing network design spaces. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 10428–10436.
[35] Maithra Raghu, Thomas Unterthiner, Simon Kornblith, Chiyuan Zhang, and
Alexey Dosovitskiy. 2021. Do Vision Transformers See Like Convolutional Neural
Networks?. In Advances in Neural Information Processing Systems (NeurIPS) .
[36] Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. 2016.
Xnor-net: Imagenet classification using binary convolutional neural networks.
InProceedings of the European Conference on Computer Vision (ECCV) . 525–542.
[37] Esteban Real, Alok Aggarwal, Yanping Huang, and Quoc V Le. 2019. Regularized
evolution for image classifier architecture search. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 33. 4780–4789.
[38] Manas Sahni, Shreya Varshini, Alind Khare, and Alexey Tumanov. 2021. Com-
pOFA: Compound Once-For-All Networks for Faster Multi-Platform Deployment.
arXiv preprint arXiv:2104.12642 (2021).
[39] Sheng Shen, Zhen Dong, Jiayu Ye, Linjian Ma, Zhewei Yao, Amir Gholami,
Michael W Mahoney, and Kurt Keutzer. 2020. Q-bert: Hessian based ultra low
precision quantization of bert. In Proceedings of the AAAI Conference on Artificial
Intelligence , Vol. 34:05. 8815–8821.
[40] Mengshu Sun, Zhengang Li, Alec Lu, Yanyu Li, Sung-En Chang, Xiaolong Ma,
Xue Lin, and Zhenman Fang. 2022. Film-qnn: Efficient fpga acceleration of deep
neural networks with intra-layer, mixed-precision quantization. In Proceedings
of the 2022 ACM/SIGDA International Symposium on Field-Programmable Gate
Arrays . 134–145.
[41] Mingxing Tan, Bo Chen, Ruoming Pang, Vijay Vasudevan, Mark Sandler, Andrew
Howard, and Quoc V Le. 2019. Mnasnet: Platform-aware neural architecture
search for mobile. In Proceedings of the IEEE/CVF Conference on Computer Vision
and Pattern Recognition (CVPR) . 2820–2828.
[42] Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre
Sablayrolles, and Hervé Jégou. 2021. Training data-efficient image transformers
& distillation through attention. In Proceedings of the International Conference on
Machine Learning (ICML) . PMLR, 10347–10357.
[43] Hugo Touvron, Matthieu Cord, Alexandre Sablayrolles, Gabriel Synnaeve, and
Hervé Jégou. 2021. Going deeper with image transformers. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) . 32–42.
[44] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne
Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al .2023. Llama: Open and efficient foundation language models. arXiv
preprint arXiv:2302.13971 (2023).
[45] Stefan Uhlich, Lukas Mauch, Fabien Cardinaux, Kazuki Yoshiyama, Javier Alonso
Garcia, Stephen Tiedemann, Thomas Kemp, and Akira Nakamura. 2020. Mixed
Precision DNNs: All you need is a good parametrization. In International Confer-
ence on Learning Representations (ICLR) .
[46] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,
Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you
need. In Advances in Neural Information Processing Systems (NeurIPS) . 5998–6008.
[47] Dilin Wang, Meng Li, Chengyue Gong, and Vikas Chandra. 2021. Attentivenas:
Improving neural architecture search via attentive sampling. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
6418–6427.
[48] Hanrui Wang, Zhanghao Wu, Zhijian Liu, Han Cai, Ligeng Zhu, Chuang Gan,
and Song Han. 2020. Hat: Hardware-aware transformers for efficient natural
language processing. arXiv:2005.14187 (2020).
[49] Kuan Wang, Zhijian Liu, Yujun Lin, Ji Lin, and Song Han. 2019. HAQ: Hardware-
Aware Automated Quantization with Mixed Precision. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[50] Tianzhe Wang, Kuan Wang, Han Cai, Ji Lin, Zhijian Liu, Hanrui Wang, Yujun
Lin, and Song Han. 2020. Apq: Joint search for network architecture, pruning
and quantization policy. In Proceedings of the IEEE/CVF Conference on Computer
Vision and Pattern Recognition . 2078–2087.
[51] Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan, Kaitao Song, Ding Liang,
Tong Lu, Ping Luo, and Ling Shao. 2021. Pyramid Vision Transformer: A Versa-
tile Backbone for Dense Prediction without Convolutions. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) .[52] Yuke Wang, Boyuan Feng, and Yufei Ding. 2022. QGTC: accelerating quantized
graph neural networks via GPU tensor core. In Proceedings of the 27th ACM
SIGPLAN Symposium on Principles and Practice of Parallel Programming . 107–119.
[53] Bichen Wu, Xiaoliang Dai, Peizhao Zhang, Yanghan Wang, Fei Sun, Yiming
Wu, Yuandong Tian, Peter Vajda, Yangqing Jia, and Kurt Keutzer. 2019. Fbnet:
Hardware-aware efficient convnet design via differentiable neural architecture
search. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern
Recognition (CVPR) . 10734–10742.
[54] Bichen Wu, Yanghan Wang, Peizhao Zhang, Yuandong Tian, Peter Vajda, and
Kurt Keutzer. 2018. Mixed precision quantization of convnets via differentiable
neural architecture search. arXiv:1812.00090 (2018).
[55] Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, and
Lei Zhang. 2021. Cvt: Introducing convolutions to vision transformers. arXiv
preprint arXiv:2103.15808 (2021).
[56] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, and Kaiming He. 2017.
Aggregated residual transformations for deep neural networks. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[57] Xilinx. 2017. Deep Learning with INT8 Optimization on Xilinx Devices. https:
//docs.xilinx.com/v/u/en-US/wp486-deep-learning-int8. Last accessed Mar. 28,
2022.
[58] Xilinx. 2020. Convolutional Neural Network with INT4 Optimization on Xilinx
Devices. https://docs.xilinx.com/v/u/en-US/wp521-4bit-optimization. Last
accessed Mar. 28, 2022.
[59] Xilinx. 2020. Vivado Design Suite. https://www.xilinx.com/products/design-
tools/vivado.html. Last accessed Aug. 28, 2022.
[60] Shan You, Tao Huang, Mingmin Yang, Fei Wang, Chen Qian, and Changshui
Zhang. 2020. GreedyNAS: Towards Fast One-Shot NAS with Greedy Supernet. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition
(CVPR) . 1999–2008.
[61] Jiahui Yu, Pengchong Jin, Hanxiao Liu, Gabriel Bender, Pieter-Jan Kindermans,
Mingxing Tan, Thomas Huang, Xiaodan Song, Ruoming Pang, and Quoc Le. 2020.
Bignas: Scaling up neural architecture search with big single-stage models. In
Proceedings of the European Conference on Computer Vision (ECCV) . 702–717.
[62] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[63] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[64] Ofir Zafrir, Guy Boudoukh, Peter Izsak, and Moshe Wasserblat. 2019. Q8bert:
Quantized 8bit bert. In 2019 Fifth Workshop on Energy Efficient Machine Learning
and Cognitive Computing-NeurIPS Edition (EMC2-NIPS) . 36–39.
[65] Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, and Qun
Liu. 2020. Ternarybert: Distillation-aware ultra-low bit bert. In Proceedings of the
2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) .
[66] Yiyang Zhao, Linnan Wang, Yuandong Tian, Rodrigo Fonseca, and Tian Guo.
2021. Few-shot neural architecture search. In Proceedings of the International
Conference on Machine Learning (ICML) . PMLR, 12707–12718.
[67] Zhao Zhong, Junjie Yan, Wei Wu, Jing Shao, and Cheng-Lin Liu. 2018. Practical
block-wise neural network architecture generation. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 2423–2432.
[68] Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou.
2016. Dorefa-net: Training low bitwidth convolutional neural networks with low
bitwidth gradients. arXiv:1606.06160 (2016).
[69] Barret Zoph and Quoc V. Le. 2017. Neural Architecture Search with Reinforcement
Learning. In International Conference on Learning Representations (ICLR) .
[70] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, and Quoc V Le. 2018. Learning
transferable architectures for scalable image recognition. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) . 8697–
8710. | Section not found | Section not found | EXPERIMENTAL RESULTS
5.1 Experimental Setup
Our supernet training process takes 700 epochs with a batch size of
2048. The learning rate is set to 5×10−4initially and decayed with
a cosine annealing schedule. The AdamW [ 28] optimizer is used
with the epsilon value of 1𝑒−8and weight decay of 0.05. Additional
training optimizations, such as warmup and label smoothing are
performed during training. The number of warmup epochs and
label smoothing factor are set as 20 and 0.1, respectively. After
supernet training, we perform the hardware-oriented evolution
search, without subnet retraining.Our training is conducted on 8 NVIDIA Ampere A100 GPUs
with CUDA 11.0 and PyTorch 1.7 frameworks on the Ubuntu oper-
ating system. To test the effectiveness of our framework, we also
implement Quasar-ViT framework on the Xilinx ZCU102 embedded
FPGA platform with quad-core ARM Cortex-A53 and XCZU9EG
FPGA chip. The FPGA working frequency is set to 150 MHz for all
the designs implemented via Xilinx Vitis and Vitis HLS 2020.1.
5.2 Accuracy Results
Here we analyze the accuracy results of our Quasar-ViT framework.
The weight precision is mixed with 4-bit and 8-bit, as mentioned
earlier, and the activation bit-width is determined by the hardware
feature. Without loss of generality, we use activation of 8-bit to
evaluate the accuracy in the ablation study of knowledge distillation
and supernet layer scaling.
5.2.1 Ablation Study of Knowledge Distillation and Supernet Layer
Scaling. To evaluate the compatibility of knowledge distillation
and our proposed SLS, we conduct an ablation study on both of
them. Without loss of generality and to prevent interference from
different model sizes and different quantization mixed ratios from
the searched subnet, we unify the search constraint with pure W8A8
(8-bit for both weight and activation) quantization implementation.
As shown in Table 6, we conduct four different settings of Quasar-
ViT with the unified model size and quantization scheme. The ac-
curacy of the four cases is 74.1% (w/o distillation and SLS), 75.6%
(only distillation), 74.9% (only SLS), and 76.1% (with both of them),
respectively. Knowledge distillation and SLS strategies are orthogo-
nal to each other, and both improve the model accuracy. Using them
together provides a better result. Given the observed effectiveness
of our proposed SLS strategy and the seamless compatibility of our
framework with knowledge distillation, we opt to incorporate both
strategies in our following experiments. Here we also quantize the
baseline DeiT-T [ 42] and compare it with our method without SLS
and distillation. Even without SLS and distillation, our quantization
NAS approach achieves a much better model accuracy than the
full-precision and the quantized (W8A8) DeiT-T models.
5.2.2 Ablation Study of Mixed-Ratio and Quantization Scheme. To
assess the efficacy of our row-wise flexible mixed-precision quanti-
zation scheme, we conducted an ablation study examining both the
quantization scheme itself and the 8-bit mixed ratio, as outlined in
Table 7. Since Quasar-ViT automatically searches the mixed ratios,
here we pick up the best model from the search stage for differ-
ent mixed ratios and compare them with the counterparts under
the fixed row-wise mixed quantization scheme. The results indi-
cate a consistent improvement in accuracy across different 8-bit
mixed-ratio levels with our flexible mixed scheme, underscoring
the efficiency of our proposed quantization scheme.
5.2.3 Overall Accuracy Results. Table 5 compares representative
ViT-based works with our proposed Quasar-ViT. Since many ViT-
based works do not incorporate model quantization, we also con-
sider the bit-width in the model size and the equivalent number of
total bit operations (BOPs).
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
Table 5: Comparison of representative ViT-based works with our proposed Quasar-ViT.
ModelQuantization #Params Model Size MACs MAC Bit-width Equivalent Top-1 Accuracy
Mixed Type(𝑀) (𝑀𝐵) (𝐺) Weight Activation BOPs (𝐺) ( %)
DeiT-T [42] - 5.7 22.8 1.3 32 32 1.3×10372.2
T2T-T [63] - 4.3 17.2 1.1 32 32 1.1×10371.7
PiT-T [14] - 10.6 42.4 1.4 32 32 1.4×10372.4
LocalViT-T [21] - 5.9 23.6 1.3 32 32 1.3×10374.8
FQ-ViT [24] Model-wise 5.7 5.7 1.3 8 8 80.6 71.6
Q-ViT [20] Head-wise 5.7 - - 4-8 4-8 - 72.8
QUASAR-S (ours) Row-wise 5.9 4.1 1.4 4 & 8 6 45.6 74.9
PVT [51] - 24.5 98.0 3.8 32 32 3.9×10379.8
DeiT-S [42] - 22.9 91.6 4.6 32 32 4.8×10379.9
Swin-T [26] - 28 112.0 4.5 32 32 4.7×10381.2
BossNAS [18] - - - 3.4 32 32 3.5×10380.5
PTQ [27] Layer-wise 22.9 16.6 4.6 6-10 6-10 - 75.1
FQ-ViT [24] Model-wise 22.9 22.9 4.6 8 8 294.4 79.1
Q-ViT [20] Head-wise 22.9 - - 4-8 4-8 - 80.1
QUASAR-L1 (ours) Row-wise 14.7 9.8 3.2 4 & 8 6 103.8 78.6
QUASAR-L2 (ours) Row-wise 22.6 15.8 4.8 4 & 8 6 163.2 80.4
Table 6: Comparison between different settings of QUASAR-
Small with and without knowledge distillation (KD) and su-
pernet layer scaling (SLS) on ImageNet dataset.
ModelSetting #Params Quantization Top-1 Acc.
KD SLS (M) Scheme (%)
DeiT-T [42] No No 5.7 W32A32 72.2
DeiT-T (quant) No No 5.7 W8A8 71.5
Ours No No 5.9 W8A8 74.1
Ours Yes No 5.9 W8A8 75.6
Ours No Yes 5.9 W8A8 74.9
Ours Yes Yes 5.9 W8A8 76.1
Table 7: Comparison between different settings of 8-bit quan-
tization mixed-ratio and quantization schemes.
Scheme Model Size (MB) 8-bit mixed-ratio (%) Acc. (%)
Fixed row-wise 3.6 23 73.5
Flexible row-wise 3.6 23 74.2
Fixed row-wise 4.1 39 74.1
Flexible row-wise 4.1 39 74.9
As shown in Table 5, we present three Quasar models for dif-
ferent accuracy levels: QUASAR-S searched within the QUASAR-
Small supernet, and QUASAR-L1, QUASAR-L2 searched within the
QUASAR-Large supernet.
Our QUASAR-S achieves 74.9% top-1 accuracy with only 4.1 MB
model size and 1.4 GMACs, Compared with the representative ViT-
based model LocalViT-T [ 21] under a similar accuracy, our model
size is only 17.4% of that in LocalViT-T; although the GMACs num-
bers are similar, our MAC unit is much more hardware efficient
as it is for a 4-bit/8-bit weight and a 6-bit activation instead of a
32-bit floating-point MAC unit in LocalViT-T. For a higher modelTable 8: Comparisons of FPGA implementations for ViTs
on ImageNet, including DeiT-S and Auto-ViT-Acc from [ 22],
and our Quasar-ViT, all running at 150MHz on the same
AMD/Xilinx ZCU102 embedded FPGA platform.
DeiT-SAuto-ViT Quasar-ViT
-Acc L2 L1 S
Quant. NoMixed Mixed Mixed Mixed
Scheme Precision Precision Precision
Weight 32 4 & 8 4 & 8 4 & 8 4 & 8
Act. 32 8 6 6 6
Top-1 Acc. 79.9 78.7 80.4 78.6 74.9
kLUT 47% 67% 66% 66% 65%
FF - - 31% 31% 30%
DSP 69% 62% 69% 69% 69%
BRAM - - 44% 44% 44%
accuracy level, our QUASAR-L1 and QUASAR-L2 achieve 78.5%
and 80.4% top-1 accuracy, respectively. Among them, QUASAR-L2
only has a 15.8 MB model size with a computation volume of 4.8
GMACs, which obtains the smallest BOPs with a similar level of
accuracy compared with other baselines. Specifically, compared
with PTQ [ 27] (16.6 MB, top-1 75.1%), QUASAR-L2 achieves a simi-
lar model size and GMACs with 5.2% higher accuracy. Compared
with ViT NAS framework BossNAS [ 18], we additionally achieve
low-bit quantization with a much smaller BOPS and similar ac-
curacy. Compared with quantization-aware training framework
Q-ViT [ 20] using multiple quantization bit-widths in the range of 4
to 8, which incurs inefficiency and hardware under-utilization, our
results show better accuracy with a more unified and hardware-
friendly quantization scheme.
ICS ’24, June 4–7, 2024, Kyoto, Japan
5.3 Comparison of Hardware Results on FPGA
We implement a proof-of-concept hardware accelerator for our
Quasar-ViT on the AMD/Xilinx ZCU102 embedded FPGA platform.
We also compare our results to Auto-ViT-Acc [ 22], the state-of-
the-art FPGA accelerator for ViT with mixed-scheme quantization
(without NAS). We retrieve the hardware results for Auto-ViT-Acc
(which is quantized from DeiT-S) and the original DeiT-S on the
same Xilinx ZCU102 FPGA platform from [22].
Power (W)02.557.510
DeiT-SAuto-ViT-AccQuasar-ViT-L2Quasar-ViT-L1Quasar-ViT-SmallFPS075150225300
FPS/W07.51522.530
Accuracy (%)6066727884
Figure 9: Comparisons between DeiT-S, Auto-ViT-Acc
from [22], and our Quasar-ViT.
As shown in Table 8 and Figure 9, our approach consistently
outperforms the previous work. Specifically, compared with DeiT-
S [42], our QUASAR-L2 achieves 2.6 ×higher inference frames per
second (FPS) with 0.5% better accuracy. Compared with Auto-ViT-
Acc [ 22], our QUASAR-L1 achieves 1.6 ×higher FPS (159.6) with
a similar model accuracy level, and our QUASAR-L2 achieves a
similar level of FPS with 1.7% better top-1 accuracy.
The improvement in model accuracy and inference performance
within our framework is attributed to two key factors. Firstly, our
approach involves the training and search for a customized network
architecture, specifically tailored for both the mixed-precision quan-
tization schemes and the targeted inference latency. This strategy
enhances adaptability and efficiency, surpassing the achievements
of previous methodologies.
Secondly, our novel supernet training algorithm, coupled with
the proposed hybrid DSP packing design, allows for distinct quanti-
zation mixed ratios across various model layers. This fine-grained
model achieves better flexibility than the previous approaches, un-
leashing the full potential of mixed-precision quantization.
With regard to the efficiency of our hardware accelerator de-
sign, the performance is mainly limited by DSP, LUT, and off-chip
memory bandwidth. On par with Auto-ViT-Acc [ 22], our design
achieves 150MHz frequency with about 66% usage of LUTs and
69% DSPs without timing violations. Note a typical FPGA design
usually utilizes approximately 60% to 70% of the available FPGA
resources; otherwise, it may fail during the placement and routing
phase due to congestion or result in a lower operating frequency.
Without considering the timing violation, the maximum theoretical
expected performance is based on the 100% utilization ratio for bothDSP, LUTs, and bandwidth, which can achieve about 1.47x of our
reached FPS for the same model.
5.4 Other Transformer-based Model Accuracy
Results
To demonstrate the scalability and versatility of our methods, we
applied them across various datasets and applications, notably de-
ploying them on a large language model (LLM). This choice is mo-
tivated by two key factors. Firstly, LLM shares a transformer-based
architecture similar to that of Vision Transformer (ViT), aligning
with the framework that we propose. Secondly, LLM is frequently
integrated with ViT in text-to-image/video applications, making
it an ideal candidate to showcase the scalability of our approach
across both models and its potential for real-world applications.
Our comparative analysis, presented in Table 9, utilizes the
renowned LLM model, LLaMA, as the foundation for our supernet.
We juxtapose our optimized results with those of LLaMA-7B [ 44] on
the commonly used WikiText-2 dataset for LLMs, with perplexity
score (PPL) serving as the evaluation metric, where lower scores
indicate superior performance. According to the comparison results,
our method shows a constant pattern, achieving a similar level of
PPL with a much smaller model size.
Table 9: Result comparison on large language model.
Model Model Size (GB) W # Bits A # Bits PPL
LLaMA-7B [44] 26.8 FP32 FP32 5.68
Ours 6.7 INT8 INT8 5.73
Ours 4.8 INT4 & 8 INT8 5.91
5.5 Training Cost Comparison
Prior co-design frameworks, such as APQ [ 50], have also delved into
the integration of neural architecture search (NAS) and quantiza-
tion techniques. Please note that APQ is based on the convolutional
neural network (CNN) and BitFusion platform [ 50]. To the best of
our knowledge, we compare our Quasar-ViT models (both small
and large variants) and the APQ result. As detailed in Table 10,
our approach demonstrates superior FPS performance while main-
taining comparable or even higher model accuracy, achieved at a
reduced training cost. Compared with the 2,400 GPU hours training
cost of APQ [ 50], our approach only consumes 768 and 1,344 GPU
hours for the small and large versions of Quasar-ViT, respectively.
Our training setting has been illustrated in Section 5.1.
Table 10: Training cost and accuracy comparison with other
NAS and quantization co-design.
Method Training cost (GPU hours) FPS Acc.(%)
APQ [50] 2400 82.2 75.1
QUASAR-S 768 101.5 74.9
QUASAR-L 1344 251.6 80.4
Quasar-ViT: Hardware-Oriented Qu antization-Aware A rchitecture S earch for Vi sion T ransformers ICS ’24, June 4–7, 2024, Kyoto, Japan
6 CONCLUSION
In this work, we propose Quasar-ViT, a hardware-oriented quantization-
aware network architecture search framework to enable efficient
ViT deployment on resource-constrained edge devices. First, we
proposed hardware-friendly quantization techniques including flex-
ible row-wise mixed-precision quantization scheme and intra-layer
mixed-precision weight entanglement in architecture search to-
wards high accuracy and low training cost for efficient implemen-
tation. Second, we propose 4-bit weight atomic computation and
hybrid signed/unsigned DSP packing for FPGA implementation,
then incorporate latency/resource modeling to enable the hardware-
oriented architecture search. Third, we extend the supernet layer
scaling technique to further improve the training convergence and
supernet accuracy. We also demonstrate the compatibility of our
proposed framework with knowledge distillation during super-
net training. Finally, we developed an efficient hardware-oriented
search algorithm—integrated with hardware latency and resource
modeling—to search the efficient subnet with high accuracy under
a given inference latency target and implemented the searched
model on real FPGA hardware for validation. From the experiment
evaluation results, our approach achieves 101.5, 159.6, and 251.6
FPS on the AMD/Xilinx ZCU102 FPGA board with 80.4%, 78.6%,
and 74.9% top-1 accuracy for ImageNet, respectively, consistently
outperforming prior works.
ACKNOWLEDGMENTS
This work was supported in part by NSERC Discovery Grant RGPIN-
2019-04613, DGECR-2019-00120, Alliance Grant ALLRP-552042-
2020; CFI John R. Evans Leaders Fund; BC Knowledge Development
Fund; Army Research Office/Army Research Laboratory via grant
W911-NF-20-1-0167 to Northeastern University; National Science
Foundation CCF-1937500, CNS-1909172, and IIS-2310254. No exter-
nal funding support to CD and MS for this project.
REFERENCES
[1]Haoli Bai, Wei Zhang, Lu Hou, Lifeng Shang, Jing Jin, Xin Jiang, Qun Liu, Michael
Lyu, and Irwin King. 2021. BinaryBERT: Pushing the Limit of BERT Quantization.
InProceedings of the 59th Annual Meeting of the Association for Computational Lin-
guistics and the 11th International Joint Conference on Natural Language Processing
(Volume 1: Long Papers) .
[2]Bowen Baker, Otkrist Gupta, Nikhil Naik, and Ramesh Raskar. 2017. Designing
Neural Network Architectures using Reinforcement Learning. In International
Conference on Learning Representations (ICLR) .
[3]Gabriel Bender, Pieter-Jan Kindermans, Barret Zoph, Vijay Vasudevan, and Quoc
Le. 2018. Understanding and simplifying one-shot architecture search. In Pro-
ceedings of the International Conference on Machine Learning (ICML) . 550–559.
[4]Han Cai, Tianyao Chen, Weinan Zhang, Yong Yu, and Jun Wang. 2018. Effi-
cient architecture search by network transformation. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 32.
[5]Sung-En Chang, Yanyu Li, Mengshu Sun, Runbin Shi, Hayden K-H So, Xuehai
Qian, Yanzhi Wang, and Xue Lin. 2021. Mix and Match: A novel FPGA-centric deep
neural network quantization framework. In 2021 IEEE International Symposium
on High-Performance Computer Architecture (HPCA) . 208–220.
[6]Minghao Chen, Houwen Peng, Jianlong Fu, and Haibin Ling. 2021. Autoformer:
Searching transformers for visual recognition. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 12270–12280.
[7]Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang,
Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. 2018. Pact: Parameterized
clipping activation for quantized neural networks. arXiv:1805.06085 (2018).
[8]Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. 2015. Binarycon-
nect: Training deep neural networks with binary weights during propagations.
InAdvances in Neural Information Processing Systems (NeurIPS) . 3123–3131.[9]Zhen Dong, Zhewei Yao, Amir Gholami, Michael W Mahoney, and Kurt Keutzer.
2019. Hawq: Hessian aware quantization of neural networks with mixed-
precision. In Proceedings of the IEEE/CVF International Conference on Computer
Vision (ICCV) .
[10] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xi-
aohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg
Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. 2021. An Image is
Worth 16x16 Words: Transformers for Image Recognition at Scale. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=YicbFdNTTy
[11] Zichao Guo, Xiangyu Zhang, Haoyuan Mu, Wen Heng, Zechun Liu, Yichen Wei,
and Jian Sun. 2020. Single path one-shot neural architecture search with uniform
sampling. In Proceedings of the European Conference on Computer Vision (ECCV) .
Springer, 544–560.
[12] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 2016. Deep residual
learning for image recognition. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 770–778.
[13] Zhezhi He and Deliang Fan. 2019. Simultaneously optimizing weight and quan-
tizer of ternary neural network using truncated gaussian approximation. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recogni-
tion (CVPR) .
[14] Byeongho Heo, Sangdoo Yun, Dongyoon Han, Sanghyuk Chun, Junsuk Choe,
and Seong Joon Oh. 2021. Rethinking spatial dimensions of vision transformers.
arXiv:2103.16302 (2021).
[15] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. 2015. Distilling the knowledge in
a neural network. arXiv:1503.02531 (2015).
[16] Intel. 2024. Intel ®Xeon®Silver 4214 Processor. https://ark.intel.com/content/
www/us/en/ark/products/193385/intel-xeon-silver-4214-processor-16-5m-
cache-2-20-ghz.html. Last accessed Jan. 18, 2024.
[17] Cong Leng, Zesheng Dou, Hao Li, Shenghuo Zhu, and Rong Jin. 2018. Extremely
low bit neural network: Squeeze the last bit out with admm. In Proceedings of the
AAAI Conference on Artificial Intelligence .
[18] Changlin Li, Tao Tang, Guangrun Wang, Jiefeng Peng, Bing Wang, Xiaodan
Liang, and Xiaojun Chang. 2021. Bossnas: Exploring hybrid cnn-transformers
with block-wisely self-supervised neural architecture search. In Proceedings of
the IEEE/CVF International Conference on Computer Vision (ICCV) . 12281–12291.
[19] Yuhang Li, Xin Dong, and Wei Wang. 2020. Additive Powers-of-Two Quantization:
An Efficient Non-uniform Discretization for Neural Networks. In International
Conference on Learning Representations (ICLR) . https://openreview.net/forum?
id=BkgXT24tDS
[20] Yanjing Li, Sheng Xu, Baochang Zhang, Xianbin Cao, Peng Gao, and Guodong
Guo. 2022. Q-ViT: Accurate and Fully Quantized Low-bit Vision Transformer. In
Advances in Neural Information Processing Systems (NeurIPS) . https://openreview.
net/forum?id=fU-m9kQe0ke
[21] Yawei Li, Kai Zhang, Jiezhang Cao, Radu Timofte, and Luc Van Gool. 2021.
LocalViT: Bringing Locality to Vision Transformers. arXiv:2104.05707 [cs.CV]
[22] Zhengang Li, Mengshu Sun, Alec Lu, Haoyu Ma, Geng Yuan, Yanyue Xie, Hao
Tang, Yanyu Li, Miriam Leeser, Zhangyang Wang, Xue Lin, and Zhenman Fang.
2022. Auto-vit-acc: An fpga-aware automatic acceleration framework for vi-
sion transformer with mixed-scheme quantization. In 2022 32nd International
Conference on Field-Programmable Logic and Applications (FPL) . IEEE, 109–116.
[23] Zhengang Li, Geng Yuan, Wei Niu, Pu Zhao, Yanyu Li, Yuxuan Cai, Xuan Shen,
Zheng Zhan, Zhenglun Kong, Qing Jin, et al .2021. NPAS: A Compiler-aware
Framework of Unified Network Pruning and Architecture Search for Beyond
Real-Time Mobile Acceleration. In Proceedings of the IEEE/CVF Conference on
Computer Vision and Pattern Recognition (CVPR) . 14255–14266.
[24] Yang Lin, Tianyu Zhang, Peiqin Sun, Zheng Li, and Shuchang Zhou. 2022. FQ-ViT:
Post-Training Quantization for Fully Quantized Vision Transformer. In Proceed-
ings of the Thirty-First International Joint Conference on Artificial Intelligence,
IJCAI-22 . 1173–1179.
[25] Chenxi Liu, Barret Zoph, Maxim Neumann, Jonathon Shlens, Wei Hua, Li-Jia Li,
Li Fei-Fei, Alan Yuille, Jonathan Huang, and Kevin Murphy. 2018. Progressive
neural architecture search. In Proceedings of the European conference on computer
vision (ECCV) . 19–34.
[26] Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin,
and Baining Guo. 2021. Swin transformer: Hierarchical vision transformer using
shifted windows. In Proceedings of the IEEE International Conference on Computer
Vision (ICCV) .
[27] Zhenhua Liu, Yunhe Wang, Kai Han, Siwei Ma, and Wen Gao. 2021. Post-Training
Quantization for Vision Transformer. In Advances in Neural Information Processing
Systems (NeurIPS) .
[28] Ilya Loshchilov and Frank Hutter. 2019. Decoupled Weight Decay Regular-
ization. In International Conference on Learning Representations (ICLR) . https:
//openreview.net/forum?id=Bkg6RiCqY7
[29] Qian Lou, Feng Guo, Minje Kim, Lantao Liu, and Lei Jiang. 2019. AutoQ: Auto-
mated Kernel-Wise Neural Network Quantization. In International Conference on
Learning Representations (ICLR) .
ICS ’24, June 4–7, 2024, Kyoto, Japan
[30] Risto Miikkulainen, Jason Liang, Elliot Meyerson, Aditya Rawal, Dan Fink, Olivier
Francon, Bala Raju, Hormoz Shahrzad, Arshak Navruzyan, Nigel Duffy, et al .
2019. Evolving deep neural networks. In Artificial Intelligence in the Age of Neural
Networks and Brain Computing . Elsevier, 293–312.
[31] Bowen Pan, Rameswar Panda, Yifan Jiang, Zhangyang Wang, Rogerio Feris, and
Aude Oliva. 2021. IA-RED2: Interpretability-Aware Redundancy Reduction for
Vision Transformers. Advances in Neural Information Processing Systems (NeurIPS)
34 (2021), 24898–24911.
[32] Hieu Pham, Melody Guan, Barret Zoph, Quoc Le, and Jeff Dean. 2018. Effi-
cient neural architecture search via parameters sharing. In Proceedings of the
International Conference on Machine Learning (ICML) . 4095–4104.
[33] PyTorch. 2024. PYTORCH PROFILER. https://pytorch.org/tutorials/recipes/
recipes/profiler_recipe.html. Last accessed Jan. 18, 2024.
[34] Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, and Piotr
Dollár. 2020. Designing network design spaces. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 10428–10436.
[35] Maithra Raghu, Thomas Unterthiner, Simon Kornblith, Chiyuan Zhang, and
Alexey Dosovitskiy. 2021. Do Vision Transformers See Like Convolutional Neural
Networks?. In Advances in Neural Information Processing Systems (NeurIPS) .
[36] Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. 2016.
Xnor-net: Imagenet classification using binary convolutional neural networks.
InProceedings of the European Conference on Computer Vision (ECCV) . 525–542.
[37] Esteban Real, Alok Aggarwal, Yanping Huang, and Quoc V Le. 2019. Regularized
evolution for image classifier architecture search. In Proceedings of the AAAI
Conference on Artificial Intelligence , Vol. 33. 4780–4789.
[38] Manas Sahni, Shreya Varshini, Alind Khare, and Alexey Tumanov. 2021. Com-
pOFA: Compound Once-For-All Networks for Faster Multi-Platform Deployment.
arXiv preprint arXiv:2104.12642 (2021).
[39] Sheng Shen, Zhen Dong, Jiayu Ye, Linjian Ma, Zhewei Yao, Amir Gholami,
Michael W Mahoney, and Kurt Keutzer. 2020. Q-bert: Hessian based ultra low
precision quantization of bert. In Proceedings of the AAAI Conference on Artificial
Intelligence , Vol. 34:05. 8815–8821.
[40] Mengshu Sun, Zhengang Li, Alec Lu, Yanyu Li, Sung-En Chang, Xiaolong Ma,
Xue Lin, and Zhenman Fang. 2022. Film-qnn: Efficient fpga acceleration of deep
neural networks with intra-layer, mixed-precision quantization. In Proceedings
of the 2022 ACM/SIGDA International Symposium on Field-Programmable Gate
Arrays . 134–145.
[41] Mingxing Tan, Bo Chen, Ruoming Pang, Vijay Vasudevan, Mark Sandler, Andrew
Howard, and Quoc V Le. 2019. Mnasnet: Platform-aware neural architecture
search for mobile. In Proceedings of the IEEE/CVF Conference on Computer Vision
and Pattern Recognition (CVPR) . 2820–2828.
[42] Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre
Sablayrolles, and Hervé Jégou. 2021. Training data-efficient image transformers
& distillation through attention. In Proceedings of the International Conference on
Machine Learning (ICML) . PMLR, 10347–10357.
[43] Hugo Touvron, Matthieu Cord, Alexandre Sablayrolles, Gabriel Synnaeve, and
Hervé Jégou. 2021. Going deeper with image transformers. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) . 32–42.
[44] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne
Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
Azhar, et al .2023. Llama: Open and efficient foundation language models. arXiv
preprint arXiv:2302.13971 (2023).
[45] Stefan Uhlich, Lukas Mauch, Fabien Cardinaux, Kazuki Yoshiyama, Javier Alonso
Garcia, Stephen Tiedemann, Thomas Kemp, and Akira Nakamura. 2020. Mixed
Precision DNNs: All you need is a good parametrization. In International Confer-
ence on Learning Representations (ICLR) .
[46] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,
Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you
need. In Advances in Neural Information Processing Systems (NeurIPS) . 5998–6008.
[47] Dilin Wang, Meng Li, Chengyue Gong, and Vikas Chandra. 2021. Attentivenas:
Improving neural architecture search via attentive sampling. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
6418–6427.
[48] Hanrui Wang, Zhanghao Wu, Zhijian Liu, Han Cai, Ligeng Zhu, Chuang Gan,
and Song Han. 2020. Hat: Hardware-aware transformers for efficient natural
language processing. arXiv:2005.14187 (2020).
[49] Kuan Wang, Zhijian Liu, Yujun Lin, Ji Lin, and Song Han. 2019. HAQ: Hardware-
Aware Automated Quantization with Mixed Precision. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[50] Tianzhe Wang, Kuan Wang, Han Cai, Ji Lin, Zhijian Liu, Hanrui Wang, Yujun
Lin, and Song Han. 2020. Apq: Joint search for network architecture, pruning
and quantization policy. In Proceedings of the IEEE/CVF Conference on Computer
Vision and Pattern Recognition . 2078–2087.
[51] Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan, Kaitao Song, Ding Liang,
Tong Lu, Ping Luo, and Ling Shao. 2021. Pyramid Vision Transformer: A Versa-
tile Backbone for Dense Prediction without Convolutions. In Proceedings of the
IEEE/CVF International Conference on Computer Vision (ICCV) .[52] Yuke Wang, Boyuan Feng, and Yufei Ding. 2022. QGTC: accelerating quantized
graph neural networks via GPU tensor core. In Proceedings of the 27th ACM
SIGPLAN Symposium on Principles and Practice of Parallel Programming . 107–119.
[53] Bichen Wu, Xiaoliang Dai, Peizhao Zhang, Yanghan Wang, Fei Sun, Yiming
Wu, Yuandong Tian, Peter Vajda, Yangqing Jia, and Kurt Keutzer. 2019. Fbnet:
Hardware-aware efficient convnet design via differentiable neural architecture
search. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern
Recognition (CVPR) . 10734–10742.
[54] Bichen Wu, Yanghan Wang, Peizhao Zhang, Yuandong Tian, Peter Vajda, and
Kurt Keutzer. 2018. Mixed precision quantization of convnets via differentiable
neural architecture search. arXiv:1812.00090 (2018).
[55] Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, and
Lei Zhang. 2021. Cvt: Introducing convolutions to vision transformers. arXiv
preprint arXiv:2103.15808 (2021).
[56] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, and Kaiming He. 2017.
Aggregated residual transformations for deep neural networks. In Proceedings of
the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .
[57] Xilinx. 2017. Deep Learning with INT8 Optimization on Xilinx Devices. https:
//docs.xilinx.com/v/u/en-US/wp486-deep-learning-int8. Last accessed Mar. 28,
2022.
[58] Xilinx. 2020. Convolutional Neural Network with INT4 Optimization on Xilinx
Devices. https://docs.xilinx.com/v/u/en-US/wp521-4bit-optimization. Last
accessed Mar. 28, 2022.
[59] Xilinx. 2020. Vivado Design Suite. https://www.xilinx.com/products/design-
tools/vivado.html. Last accessed Aug. 28, 2022.
[60] Shan You, Tao Huang, Mingmin Yang, Fei Wang, Chen Qian, and Changshui
Zhang. 2020. GreedyNAS: Towards Fast One-Shot NAS with Greedy Supernet. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition
(CVPR) . 1999–2008.
[61] Jiahui Yu, Pengchong Jin, Hanxiao Liu, Gabriel Bender, Pieter-Jan Kindermans,
Mingxing Tan, Thomas Huang, Xiaodan Song, Ruoming Pang, and Quoc Le. 2020.
Bignas: Scaling up neural architecture search with big single-stage models. In
Proceedings of the European Conference on Computer Vision (ECCV) . 702–717.
[62] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[63] Li Yuan, Yunpeng Chen, Tao Wang, Weihao Yu, Yujun Shi, Zi-Hang Jiang, Fran-
cis E.H. Tay, Jiashi Feng, and Shuicheng Yan. 2021. Tokens-to-Token ViT: Training
Vision Transformers From Scratch on ImageNet. In Proceedings of the IEEE/CVF
International Conference on Computer Vision (ICCV) . 558–567.
[64] Ofir Zafrir, Guy Boudoukh, Peter Izsak, and Moshe Wasserblat. 2019. Q8bert:
Quantized 8bit bert. In 2019 Fifth Workshop on Energy Efficient Machine Learning
and Cognitive Computing-NeurIPS Edition (EMC2-NIPS) . 36–39.
[65] Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, and Qun
Liu. 2020. Ternarybert: Distillation-aware ultra-low bit bert. In Proceedings of the
2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) .
[66] Yiyang Zhao, Linnan Wang, Yuandong Tian, Rodrigo Fonseca, and Tian Guo.
2021. Few-shot neural architecture search. In Proceedings of the International
Conference on Machine Learning (ICML) . PMLR, 12707–12718.
[67] Zhao Zhong, Junjie Yan, Wei Wu, Jing Shao, and Cheng-Lin Liu. 2018. Practical
block-wise neural network architecture generation. In Proceedings of the IEEE/CVF
Conference on Computer Vision and Pattern Recognition (CVPR) . 2423–2432.
[68] Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou.
2016. Dorefa-net: Training low bitwidth convolutional neural networks with low
bitwidth gradients. arXiv:1606.06160 (2016).
[69] Barret Zoph and Quoc V. Le. 2017. Neural Architecture Search with Reinforcement
Learning. In International Conference on Learning Representations (ICLR) .
[70] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, and Quoc V Le. 2018. Learning
transferable architectures for scalable image recognition. In Proceedings of the
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) . 8697–
8710. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18184v1 | http://arxiv.org/pdf/2407.18184v1 | AsEP: Benchmarking Deep Learning Methods for Antibody-specific Epitope Prediction | Chunan Liu, Lilian Denzler, Yihong Chen, Andrew Martin, Brooks Paige | 2024-07-25 | Abstract
Epitope identification is vital for antibody design yet challenging due to the in-
herent variability in antibodies. While many deep learning methods have been
developed for general protein binding site prediction tasks, whether they work
for epitope prediction remains an understudied research question. The challenge
is also heightened by the lack of a consistent evaluation pipeline with sufficient
dataset size and epitope diversity. We introduce a filtered antibody-antigen com-
plex structure dataset, AsEP (Antibody-specific Epitope Prediction). AsEP is the
largest of its kind and provides clustered epitope groups, allowing the commu-
nity to develop and test novel epitope prediction methods. AsEP comes with
an easy-to-use interface in Python and pre-built graph representations of each
antibody-antigen complex while also supporting customizable embedding meth-
ods. Based on this new dataset, we benchmarked various representative general
protein-binding site prediction methods and find that their performances are not
satisfactory as expected for epitope prediction. We thus propose a new method,
WALLE , that leverages both protein language models and graph neural networks.
WALLE demonstrate about 5X performance gain over existing methods. Our
empirical findings evidence that epitope prediction benefits from combining se-
quential embeddings provided by language models and geometrical information
from graph representations, providing a guideline for future method design. In
addition, we reformulate the task as bipartite link prediction, allowing easy model
performance attribution and interpretability. We open-source our data and code at
https://github.com/biochunan/AsEP-dataset .
∗Address correspondence to: [email protected], [email protected], [email protected]
†Equal contributionarXiv:2407.18184v1 [cs.LG] 25 Jul 2024
1 | Introduction
Antibodies are specialized proteins produced by our immune system to combat foreign substances
called antigens. Their unique ability to bind with high affinity and specificity sets them apart
from regular proteins and small-molecule drugs, making them increasingly popular in therapeutic
engineering.
While the community is shifting toward computational antibody design given a pre-determined
epitope (Jin et al., 2022; Zhou et al., 2024; Bennett et al., 2024), accurate prediction of epitopes
remains underexplored. Accurate identification of epitopes is beneficial for understanding antibody-
antigen interactions, antibody function, and streamlining antibody engineering. This task remains
challenging due to multiple factors (Akbar et al., 2022; Hummer et al., 2022), such as, the lack of
comprehensive datasets, limited interpretability and generalizability. Available datasets are limited
in size, up to 582 complexes from Bepipred-3.0 (Clifford et al., 2022), and feature disproportionate
representation among various epitopes.
Existing methods perform poorly on epitope prediction task (Cia et al., 2023), with a ceiling
MCC (Matthew’s Correlation Coefficient) of 0.06. However, recent advancements in graph-based
learning, coupled with an increase in available antibody structures in the Protein Data Bank
(PDB) (Berman et al., 2003), highlight the need to reevaluate current methods and establish a
benchmark dataset for predicting antibody-antigen interactions.
We approach the problem as a bipartite graph link prediction task. Traditionally, graph link prediction
focuses on identifying connections within the same graph, such as in protein-protein interaction
networks. Our research extends this concept to bipartite graphs at the molecular level and proposes
our own model, WALLE. Because existing methods generally predict protein binding sites or epitopes
in antibody-antigen complexes rather than residue-residue interactions, we focus on benchmarking
the node classification task while providing WALLE’s performance on the bipartite link prediction
task as a baseline.
2 Previous Work
Accurate epitope prediction for antibody design remains challenging due to the complexity of
antibody-antigen interactions and limitations of existing datasets and methods. Several computational
approaches have been developed, but they often fall short in terms of accuracy and applicability. Here,
we present a representative set of state-of-the-art methods.
EpiPred (Krawczyk et al., 2014) implements a graph-based antibody-antigen specific scoring func-
tion that considers all possible residue-residue pairs at the interface between anybody and antigen
structures. It samples surface patches from the antigen structure surface and selects the highest-ranked
patch with the highest score as the predicted set of epitope residues.
ESMFold (Lin et al., 2023) is a protein language model based on ESM2 (Lin et al., 2023), and its
folding head was trained on over 325 thousand protein structures. It achieves comparable performance
to AlphaFold2 (Jumper et al., 2021) and is included in our benchmarking due to its faster processing.
We also include methods that consider only antigens:
ESMBind (Schreiber, 2023) is a language model that predicts protein binding sites for single protein
sequence inputs. It is fine-tuned based on ESM2 (Lin et al., 2023) using Low-Rank Adaptation (Hu
et al., 2021) on a dataset composed of more than 200 thousand protein sequences with annotated
binding sites.
MaSIF-site (Gainza et al., 2020) is a geometric deep learning method that predicts binding sites on
the surface of an input protein structure. It converts antigen surfaces into mesh graphs, with each
mesh vertex encoded with geometric and physicochemical descriptors, and predicts binding sites as a
set of mesh vertices.
PECAN and EPMP (Pittala & Bailey-Kellogg, 2020; Vecchio et al., 2021) are graph neural networks
that predict epitope residues taken antibody-antigen structure pairs as input. They use position-
specific scoring matrices (PSSM) as node embeddings and graph attention networks to predict the
binary labels of nodes in the antigen graph. For details, we refer readers to Appendix A.1.
2
Two Complementary Surveys are notable:
Zhao et al. (2024) benchmarked docking methods like ZDOCK (Pierce et al., 2011), ClusPro (Kozakov
et al., 2017), and HDOCK (Yan et al., 2017), and Alphafold-Multimer (Evans et al., 2022) on a set of
112antibody-antigen complexes. They showed that all docking methods gave a success rate of 8.0%
at most if using the top 5 decoys; Alphafold-Multimer showed a better performance with a 15.3%
success rate.
Cia et al. (2023) focused on epitope prediction using a dataset of 268complexes, defining epitope
residues as having at least a 5%change in relative solvent accessibility upon complex formation. They
benchmarked various methods, finding existing methods insufficient for accurate epitope prediction.
3 Problem Formulation
Antibody-antigen interaction is important for analyzing protein structures. The problem can be
formulated as a bipartite graph link prediction task. The inputs are two disjoint graphs, an antibody
graph GA= (VA, EA)and an antigen graph GB= (VB, EB), where Vxis the vertice set for graph
xandExis the edge set for graph x. Since the neural networks only take continuous values as
input, we also have a function hto encode each vertex into a vector h:V→RD. The design of
the encoding function depends on the methods. For example, hcan be a one-hot encoding layer or
pretrained embeddings given by a protein language model. We use different encoding functions for
antibodies and antigens: hA:VA→RDA, andhB:VB→RDB.
In addition, EA∈ {0,1}|VA|×|VA|andEB∈ {0,1}|VB|×|VB|denote the adjacency matrices for the
antibody and antigen graphs, respectively. In this work, the adjacency matrices are calculated based
on the distance matrix of the residues. Each entry eijdenotes the proximity between residue iand
residue j;eij= 1if the Euclidean distance between any non-hydrogen atoms of residue iand residue
jis less than 4.5Å, and eij= 0 otherwise. The antibody graph GAis constructed by combining
the CDR residues from the heavy and light chains of the antibody, and the antigen graph GBis
constructed by combining the surface residues of the antigen. The antibody and antigen graphs are
disjoint, i.e., VA∩VB=∅.
Figure 1: An example to illustrate interacting residues. The two dashed lines denote the distance
between non-hydrogen atoms from different interacting residues from two different protein chains.
We consider two subtasks based on these inputs.
Epitope Prediction Epitopes are the regions on the antigen surface recognized by antibodies; in
other words, they are a set of antigen residues in contact with the antibody and are determined from
the complex structures using the same distance cutoff of 4.5Åas aforementioned. For a node in the
antigen graph v∈VB, if there exists a node in the antibody graph u∈VAsuch that the distance
between them is less than 4.5Å, then vis an epitope node. Epitope nodes and the remaining nodes in
GBare assigned labels of 1and0, respectively. The first task is then a node classification within the
antigen graph GBgiven the antibody graph GA.
This classification takes into account the structure of the antibody graph, GA, mirroring the specificity
of antibody-antigen binding interactions. Different antibodies can bind to various antigen locations,
3
corresponding to varying subsets of epitope nodes in GB. This question differs from conventional
epitope prediction methods that do not consider the antibody structure and end up predicting the
likelihood of the subset of antigen nodes serving as epitopes, such as ScanNet (Tubiana et al., 2022),
MaSIF (Gainza et al., 2020).
The task is to develop a binary classifier f:VB→ {0,1}that takes both the antibody and antigen
graphs as input and predicts the label for antigen nodes as formulated below:
f(v;GB, GA) =1ifvis an epitope ;
0otherwise .(1)
Bipartite Link Prediction The second task takes it further by predicting concrete interactions
between nodes in GAandGB, resulting in a bipartite graph that represents these antibody-antigen
interactions. Moreover, this helps attribute the model performance to specific interactions at the
molecular level and provide more interpretability. Accurately predicting these interactions is critical
for understanding the binding mechanisms and for guiding antibody engineering.
We model the antibody-antigen interaction as a bipartite graph:
Km,n= (VA, VB, E)
where m=|VA|andn=|VB|denote the number of nodes in the two graphs, respectively, and
Edenotes all possible inter-graph links. In this bipartite graph, a node from the antibody graph
is connected to each node in the antigen graph via an edge e∈E. The task is then to predict the
label of each bipartite edge. If the residues of a pair of nodes are located within 4.5Åof each other,
referred to as in contact , the edge is labeled as 1; otherwise, 0. For any pair of nodes, denoted as
(va, vb)∀va∈VA, vb∈VB, the binary classifier g:Km,n→ {0,1}is formulated as below:
g(va, vb;Km,n) =1ifvaandvbare in contact
0otherwise .(2)
4 AsEP dataset
We present our dataset AsEP of filtered, cleaned and processed antibody-antigen complex structures.
It is the largest collection of antibody-antigen complex structures to our knowledge. Antibodies
are composed of two heavy chains and two light chains, each of which contains a variable domain
(areas of high sequence variability) composed of a variable heavy (VH) and a variable light (VL)
domain responsible for antigen recognition and binding (Chothia & Lesk, 1987). These domains
have complementarity-determining regions (CDR, Figure 2 top blue, yellow, and red regions), which
are the primary parts of antibodies responsible for antigen recognition and binding.
4.1 Antibody-antigen complexes
We sourced our initial dataset from the Antibody Database (AbDb) (Ferdous & Martin, 2018), dated
2022/09/26, which contains 11,767antibody files originally collected from the Protein Data Bank
(PDB) (Berman et al., 2003). We extracted conventional antibody-antigen complexes that have a
VH and a VL domain with a single-chain protein antigen, and there are no unresolved CDR residues
due to experimental errors, yielding 4,081antibody-antigen complexes. To ensure data balance,
we removed identical complexes using an adapted version of the method described in Krawczyk
et al. (2014). We clustered the complexes by antibody heavy and light chains followed by antigen
sequences using MMseqs2 (Steinegger & Söding, 2017). We retained only one representative complex
for each unique cluster, leading to a refined dataset of 1,725unique complexes. Two additional
complexes were manually removed; CDR residues in the complex 6jmr_1P are unknown (labeled as
‘UNK’) and it is thus impossible to build graph representations upon this complex; 7sgm_0P was also
removed because of non-canonical residues in its CDR loops. The final dataset consists of 1,723
antibody-antigen complexes. For detailed setup and processing steps, please refer to Appendix A.3.
4
Figure 2: Graph visualization of an antibody-antigen complex. Top: the molecular structure of an
antibody complexed with the receptor binding domain of SARS-Cov-2 virus (PDB code: 7KFW), the
antigen. Spheres indicate the alpha carbon atoms of each amino acid. Color scheme: the antigen is
colored in magenta, the framework region of the heavy and light chains is colored in green and cyan
and CDR 1-3 loops are colored in blue, yellow, and red, respectively. Bottom : the corresponding
graph. Green vertices are antibody CDR residues and pink vertices are antigen surface residues.
4.2 Convert antibody-antigen complexes to graphs
These 1,723files were then converted into graph representations, which are used as input for WALLE.
In these graphs, each protein residue is modeled as a vertex. Edges are drawn between pairs of
residues if any of their non-hydrogen atoms are within 4.5Åof each other, adhering to the same
distance criterion used in PECAN (Pittala & Bailey-Kellogg, 2020).
Exclude buried residues In order to utilize structural information effectively, we focused on surface
residues, as only these can interact with another protein. Consequently, we excluded buried residues,
those with a solvent-accessible surface area of zero, from the antigen graphs. The solvent-accessible
surface areas were calculated using DSSP (Kabsch & Sander, 1983) via Graphein (Jamasb et al.,
2021). It is important to note that the number of interface nodes are much smaller than the number of
non-interface nodes in the antigen, making the classification task more challenging.
Exclude non-CDR residues We also excluded non-CDR residues from the antibody graph, as these
are typically not involved in antigen recognition and binding. This is in line with the approach
adopted by PECAN (Pittala & Bailey-Kellogg, 2020) and EPMP (Vecchio et al., 2021). Figure 2
provides a visualization of the processed graphs.
Node embeddings To leverage the state-of-the-art protein language models, we generated node em-
beddings for each residue in the antibody and antigen graphs using AntiBERTy (Ruffolo et al., 2021)
(via IgFold (Ruffolo et al., 2023) package) and ESM2 (Lin et al., 2022) ( esm2_t12_35M_UR50D )
models, respectively. In our dataset interface package, we also provide a simple embedding method
using one-hot encoding for amino acid residues. Other node embedding methods can be easily
incorporated into our dataset interface.
4.3 Dataset split
We propose two types of dataset split settings. The first is a random split based on the ratio of epitope
to antigen surface residues,#epitope nodes
#antigen nodes; the second is a more challenging setting where we split the
5
dataset by epitope groups. The first setting is straightforward and used by previous methods. The
second setting is more challenging because it requires the model to generalize to unseen epitope
groups.
Split by epitope to antigen surface ratio As aforementioned, the number of non-interface nodes
in the antigen graph is much larger than the number of interface nodes. While epitopes usually
have a limited number of residues, typically around 14.6±4.9amino acids (Reis et al., 2022), the
antigen surface may extend to several hundred or more residues. The complexity of the classification
task therefore increases with the antigen surface size. To ensure similar complexity among train,
validation, and test sets, we stratified the dataset to include a similar distribution of epitope to non-
epitope nodes in each set. Table S3 shows the distribution of epitope-to-antigen surface ratios in each
set. This led to 1383 antibody-antigen complexes for the training set and 170complexes each for the
validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-ratio.csv .
Split by epitope groups This is motivated by the fact that antibodies are highly diverse in the CDR
loops and by changing the CDR sequences it is possible to engineer novel antibodies to bind different
sites on the same antigen. This was previously observed in the EpiPred dataset where Krawczyk et al.
(2014) tested the specificity of their method on five antibodies associated with three epitopes on the
same antigen, hen egg white lysozyme.
We inlcude 641unique antigens and 973epitope groups in our dataset. We include multi-epitope
antigens. For example, there are 64distinct antibodies that bind to coronavirus spike protein.
We can see that different antibodies bind to different locations on the same antigen. Details of
all epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv . We then
split the dataset into train, validation, and test sets such that the epitopes in the test set are not
found in either train or validation sets. We followed an 80%/10%/10% split for the number of
complexes in each set. This resulted in 1383 complexes for the training set and 170complexes for
the validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-group.csv .
User-friendly Dataset Interface We implemented a Python package interface for our dataset using
PyTorch Geometric (Fey & Lenssen, 2019). Users can load the dataset as a PyTorch Geometric
dataset object and use it with PyTorch Geometric’s data loaders. We provide an option to load node
embeddings derived from AntiBERTy and ESM2 or simply one-hot embeddings. Each data object in
the dataset is a pair of antibody and antigen graphs; both node- and edge-level labels are provided,
and the node-level labels are used for the epitope prediction task.
5 WALLE: a graph-based method for epitope prediction
Alongside our dataset interface, we also provide a graph-based model named WALLE. It takes as
input a pair of antibody and antigen graphs, constructed as detailed above for the AsEP dataset, and
makes node- and edge-level predictions.
Graph Modules The architecture of WALLE incorporates graph modules that process the input
graphs of antibody and antigen structures, as depicted in Figure 3). Inspired by PECAN and EPMP,
our model treats the antibody and antigen graphs separately, with distinct pathways for each. The
antibody graph is represented by node embeddings XAwith a shape of (M,512) and an adjacency
matrix EA, while the antigen graph is described by node embeddings XBwith a shape of (N,480)
and its corresponding adjacency matrix EB. The embedding sizes are consistent with AntiBERTy
and ESM2 ( esm2_t12_35M_UR50D ).
Both antibody and antigen graph nodes are first projected into the dimensionality of 128using fully
connected layers. The resulting embeddings are then passed through two Graph Convolutional
Network (GCN) modules consecutively to refine the features and yield updated node embeddings X′
A
andX′
Bwith a reduced dimensionality of (M,64). The output from the first GCN layer is passed
through a ReLU activate function. Outputs from the second GCN layer are directly fed into the
Decoder module. These GCNs operate independently, each with its own parameters, ensuring that
the learned representations are specific to the antibody or the antigen.
6
GCN (128) GCN (128)
DecoderGCN (64) GCN (64)
Antigen Graph
Node
Edge index Antibody CDR Graph
Node
Edge index Preprocessing
AntibodyPreprocessing
AntigenAbAg
complex
structureFigure 3: A schematic of the preprocessing step that turns an input antibody-antigen complex structure
into a graph pair and the model architecture of WALLE.
The use of separate GCN modules for the antibody and antigen allows for the capture of unique
structural and functional characteristics pertinent to each molecule before any interaction analysis.
This design choice aligns with the understanding that the antibody and antigen have distinct roles in
their interactions and their molecular features should be processed separately.
Decoder
We used a simple decoder to predict the binary labels of edges between the antibody and antigen
graphs, which takes a pair of node embeddings output by the graph modules as input and predicts the
probability of each edge. An edge is assigned a binary label of 1if the predicted probability is greater
than0.5or0otherwise. This is shown as the Decoder module in Figure 3. For the epitope prediction
task, we convert edge-level predictions to node-level by summing the predicted probabilities of all
edges connected to an antigen node; we assign the antigen node a label of 1if the number of connected
edges is greater than a threshold or 0otherwise. The threshold is treated as a hyperparameter and is
optimized in the experiments.
Implementation
We used PyTorch Geometric (Fey & Lenssen, 2019) framework to build our model. The graph
modules are implemented using the GCNConv module from PyTorch Geometric. We trained the
model to minimize a loss function consisting of two parts: a weighted binary cross-entropy loss
for the bipartite graph link reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph. We used the same set of hyperparameters and loss functions for both
dataset settings. The loss function and hyperparameters are described in detail in Appendix A.6.
Experiment results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1).
References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A Appendix-A
A.1 | Section not found | Related work
Comparison of Previous Datasets We would like to highlight our dataset, AsEP, is the largest
curated AbAg benchmarking dataset to date. Existing ones either focus on general protein-protein
complexes designed to develop general docking | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Methods for
Antibody-specific Epitope Prediction
Chu’nan Liu∗
Structural Molecular Biology
University College LondonLilian Denzler†
Structural Molecular Biology
University College LondonYihong Chen†
Computer Science
University College London
Andrew Martin∗
Structural Molecular Biology
University College LondonBrooks Paige∗
Computer Science
University College London
Abstract
Epitope identification is vital for antibody design yet challenging due to the in-
herent variability in antibodies. While many deep learning methods have been
developed for general protein binding site prediction tasks, whether they work
for epitope prediction remains an understudied research question. The challenge
is also heightened by the lack of a consistent evaluation pipeline with sufficient
dataset size and epitope diversity. We introduce a filtered antibody-antigen com-
plex structure dataset, AsEP (Antibody-specific Epitope Prediction). AsEP is the
largest of its kind and provides clustered epitope groups, allowing the commu-
nity to develop and test novel epitope prediction methods. AsEP comes with
an easy-to-use interface in Python and pre-built graph representations of each
antibody-antigen complex while also supporting customizable embedding meth-
ods. Based on this new dataset, we benchmarked various representative general
protein-binding site prediction methods and find that their performances are not
satisfactory as expected for epitope prediction. We thus propose a new method,
WALLE , that leverages both protein language models and graph neural networks.
WALLE demonstrate about 5X performance gain over existing methods. Our
empirical findings evidence that epitope prediction benefits from combining se-
quential embeddings provided by language models and geometrical information
from graph representations, providing a guideline for future method design. In
addition, we reformulate the task as bipartite link prediction, allowing easy model
performance attribution and interpretability. We open-source our data and code at
https://github.com/biochunan/AsEP-dataset .
∗Address correspondence to: [email protected], [email protected], [email protected]
†Equal contributionarXiv:2407.18184v1 [cs.LG] 25 Jul 2024
1 Introduction
Antibodies are specialized proteins produced by our immune system to combat foreign substances
called antigens. Their unique ability to bind with high affinity and specificity sets them apart
from regular proteins and small-molecule drugs, making them increasingly popular in therapeutic
engineering.
While the community is shifting toward computational antibody design given a pre-determined
epitope (Jin et al., 2022; Zhou et al., 2024; Bennett et al., 2024), accurate prediction of epitopes
remains underexplored. Accurate identification of epitopes is beneficial for understanding antibody-
antigen interactions, antibody function, and streamlining antibody engineering. This task remains
challenging due to multiple factors (Akbar et al., 2022; Hummer et al., 2022), such as, the lack of
comprehensive datasets, limited interpretability and generalizability. Available datasets are limited
in size, up to 582 complexes from Bepipred-3.0 (Clifford et al., 2022), and feature disproportionate
representation among various epitopes.
Existing methods perform poorly on epitope prediction task (Cia et al., 2023), with a ceiling
MCC (Matthew’s Correlation Coefficient) of 0.06. However, recent advancements in graph-based
learning, coupled with an increase in available antibody structures in the Protein Data Bank
(PDB) (Berman et al., 2003), highlight the need to reevaluate current methods and establish a
benchmark dataset for predicting antibody-antigen interactions.
We approach the problem as a bipartite graph link prediction task. Traditionally, graph link prediction
focuses on identifying connections within the same graph, such as in protein-protein interaction
networks. Our research extends this concept to bipartite graphs at the molecular level and proposes
our own model, WALLE. Because existing methods generally predict protein binding sites or epitopes
in antibody-antigen complexes rather than residue-residue interactions, we focus on benchmarking
the node classification task while providing WALLE’s performance on the bipartite link prediction
task as a baseline.
2 Previous Work
Accurate epitope prediction for antibody design remains challenging due to the complexity of
antibody-antigen interactions and limitations of existing datasets and methods. Several computational
approaches have been developed, but they often fall short in terms of accuracy and applicability. Here,
we present a representative set of state-of-the-art methods.
EpiPred (Krawczyk et al., 2014) implements a graph-based antibody-antigen specific scoring func-
tion that considers all possible residue-residue pairs at the interface between anybody and antigen
structures. It samples surface patches from the antigen structure surface and selects the highest-ranked
patch with the highest score as the predicted set of epitope residues.
ESMFold (Lin et al., 2023) is a protein language model based on ESM2 (Lin et al., 2023), and its
folding head was trained on over 325 thousand protein structures. It achieves comparable performance
to AlphaFold2 (Jumper et al., 2021) and is included in our benchmarking due to its faster processing.
We also include methods that consider only antigens:
ESMBind (Schreiber, 2023) is a language model that predicts protein binding sites for single protein
sequence inputs. It is fine-tuned based on ESM2 (Lin et al., 2023) using Low-Rank Adaptation (Hu
et al., 2021) on a dataset composed of more than 200 thousand protein sequences with annotated
binding sites.
MaSIF-site (Gainza et al., 2020) is a geometric deep learning method that predicts binding sites on
the surface of an input protein structure. It converts antigen surfaces into mesh graphs, with each
mesh vertex encoded with geometric and physicochemical descriptors, and predicts binding sites as a
set of mesh vertices.
PECAN and EPMP (Pittala & Bailey-Kellogg, 2020; Vecchio et al., 2021) are graph neural networks
that predict epitope residues taken antibody-antigen structure pairs as input. They use position-
specific scoring matrices (PSSM) as node embeddings and graph attention networks to predict the
binary labels of nodes in the antigen graph. For details, we refer readers to Appendix A.1.
2
Two Complementary Surveys are notable:
Zhao et al. (2024) benchmarked docking methods like ZDOCK (Pierce et al., 2011), ClusPro (Kozakov
et al., 2017), and HDOCK (Yan et al., 2017), and Alphafold-Multimer (Evans et al., 2022) on a set of
112antibody-antigen complexes. They showed that all docking methods gave a success rate of 8.0%
at most if using the top 5 decoys; Alphafold-Multimer showed a better performance with a 15.3%
success rate.
Cia et al. (2023) focused on epitope prediction using a dataset of 268complexes, defining epitope
residues as having at least a 5%change in relative solvent accessibility upon complex formation. They
benchmarked various methods, finding existing methods insufficient for accurate epitope prediction.
3 Problem Formulation
Antibody-antigen interaction is important for analyzing protein structures. The problem can be
formulated as a bipartite graph link prediction task. The inputs are two disjoint graphs, an antibody
graph GA= (VA, EA)and an antigen graph GB= (VB, EB), where Vxis the vertice set for graph
xandExis the edge set for graph x. Since the neural networks only take continuous values as
input, we also have a function hto encode each vertex into a vector h:V→RD. The design of
the encoding function depends on the methods. For example, hcan be a one-hot encoding layer or
pretrained embeddings given by a protein language model. We use different encoding functions for
antibodies and antigens: hA:VA→RDA, andhB:VB→RDB.
In addition, EA∈ {0,1}|VA|×|VA|andEB∈ {0,1}|VB|×|VB|denote the adjacency matrices for the
antibody and antigen graphs, respectively. In this work, the adjacency matrices are calculated based
on the distance matrix of the residues. Each entry eijdenotes the proximity between residue iand
residue j;eij= 1if the Euclidean distance between any non-hydrogen atoms of residue iand residue
jis less than 4.5Å, and eij= 0 otherwise. The antibody graph GAis constructed by combining
the CDR residues from the heavy and light chains of the antibody, and the antigen graph GBis
constructed by combining the surface residues of the antigen. The antibody and antigen graphs are
disjoint, i.e., VA∩VB=∅.
Figure 1: An example to illustrate interacting residues. The two dashed lines denote the distance
between non-hydrogen atoms from different interacting residues from two different protein chains.
We consider two subtasks based on these inputs.
Epitope Prediction Epitopes are the regions on the antigen surface recognized by antibodies; in
other words, they are a set of antigen residues in contact with the antibody and are determined from
the complex structures using the same distance cutoff of 4.5Åas aforementioned. For a node in the
antigen graph v∈VB, if there exists a node in the antibody graph u∈VAsuch that the distance
between them is less than 4.5Å, then vis an epitope node. Epitope nodes and the remaining nodes in
GBare assigned labels of 1and0, respectively. The first task is then a node classification within the
antigen graph GBgiven the antibody graph GA.
This classification takes into account the structure of the antibody graph, GA, mirroring the specificity
of antibody-antigen binding interactions. Different antibodies can bind to various antigen locations,
3
corresponding to varying subsets of epitope nodes in GB. This question differs from conventional
epitope prediction methods that do not consider the antibody structure and end up predicting the
likelihood of the subset of antigen nodes serving as epitopes, such as ScanNet (Tubiana et al., 2022),
MaSIF (Gainza et al., 2020).
The task is to develop a binary classifier f:VB→ {0,1}that takes both the antibody and antigen
graphs as input and predicts the label for antigen nodes as formulated below:
f(v;GB, GA) =1ifvis an epitope ;
0otherwise .(1)
Bipartite Link Prediction The second task takes it further by predicting concrete interactions
between nodes in GAandGB, resulting in a bipartite graph that represents these antibody-antigen
interactions. Moreover, this helps attribute the model performance to specific interactions at the
molecular level and provide more interpretability. Accurately predicting these interactions is critical
for understanding the binding mechanisms and for guiding antibody engineering.
We model the antibody-antigen interaction as a bipartite graph:
Km,n= (VA, VB, E)
where m=|VA|andn=|VB|denote the number of nodes in the two graphs, respectively, and
Edenotes all possible inter-graph links. In this bipartite graph, a node from the antibody graph
is connected to each node in the antigen graph via an edge e∈E. The task is then to predict the
label of each bipartite edge. If the residues of a pair of nodes are located within 4.5Åof each other,
referred to as in contact , the edge is labeled as 1; otherwise, 0. For any pair of nodes, denoted as
(va, vb)∀va∈VA, vb∈VB, the binary classifier g:Km,n→ {0,1}is formulated as below:
g(va, vb;Km,n) =1ifvaandvbare in contact
0otherwise .(2)
4 AsEP dataset
We present our dataset AsEP of filtered, cleaned and processed antibody-antigen complex structures.
It is the largest collection of antibody-antigen complex structures to our knowledge. Antibodies
are composed of two heavy chains and two light chains, each of which contains a variable domain
(areas of high sequence variability) composed of a variable heavy (VH) and a variable light (VL)
domain responsible for antigen recognition and binding (Chothia & Lesk, 1987). These domains
have complementarity-determining regions (CDR, Figure 2 top blue, yellow, and red regions), which
are the primary parts of antibodies responsible for antigen recognition and binding.
4.1 Antibody-antigen complexes
We sourced our initial dataset from the Antibody Database (AbDb) (Ferdous & Martin, 2018), dated
2022/09/26, which contains 11,767antibody files originally collected from the Protein Data Bank
(PDB) (Berman et al., 2003). We extracted conventional antibody-antigen complexes that have a
VH and a VL domain with a single-chain protein antigen, and there are no unresolved CDR residues
due to experimental errors, yielding 4,081antibody-antigen complexes. To ensure data balance,
we removed identical complexes using an adapted version of the method described in Krawczyk
et al. (2014). We clustered the complexes by antibody heavy and light chains followed by antigen
sequences using MMseqs2 (Steinegger & Söding, 2017). We retained only one representative complex
for each unique cluster, leading to a refined dataset of 1,725unique complexes. Two additional
complexes were manually removed; CDR residues in the complex 6jmr_1P are unknown (labeled as
‘UNK’) and it is thus impossible to build graph representations upon this complex; 7sgm_0P was also
removed because of non-canonical residues in its CDR loops. The final dataset consists of 1,723
antibody-antigen complexes. For detailed setup and processing steps, please refer to Appendix A.3.
4
Figure 2: Graph visualization of an antibody-antigen complex. Top: the molecular structure of an
antibody complexed with the receptor binding domain of SARS-Cov-2 virus (PDB code: 7KFW), the
antigen. Spheres indicate the alpha carbon atoms of each amino acid. Color scheme: the antigen is
colored in magenta, the framework region of the heavy and light chains is colored in green and cyan
and CDR 1-3 loops are colored in blue, yellow, and red, respectively. Bottom : the corresponding
graph. Green vertices are antibody CDR residues and pink vertices are antigen surface residues.
4.2 Convert antibody-antigen complexes to graphs
These 1,723files were then converted into graph representations, which are used as input for WALLE.
In these graphs, each protein residue is modeled as a vertex. Edges are drawn between pairs of
residues if any of their non-hydrogen atoms are within 4.5Åof each other, adhering to the same
distance criterion used in PECAN (Pittala & Bailey-Kellogg, 2020).
Exclude buried residues In order to utilize structural information effectively, we focused on surface
residues, as only these can interact with another protein. Consequently, we excluded buried residues,
those with a solvent-accessible surface area of zero, from the antigen graphs. The solvent-accessible
surface areas were calculated using DSSP (Kabsch & Sander, 1983) via Graphein (Jamasb et al.,
2021). It is important to note that the number of interface nodes are much smaller than the number of
non-interface nodes in the antigen, making the classification task more challenging.
Exclude non-CDR residues We also excluded non-CDR residues from the antibody graph, as these
are typically not involved in antigen recognition and binding. This is in line with the approach
adopted by PECAN (Pittala & Bailey-Kellogg, 2020) and EPMP (Vecchio et al., 2021). Figure 2
provides a visualization of the processed graphs.
Node embeddings To leverage the state-of-the-art protein language models, we generated node em-
beddings for each residue in the antibody and antigen graphs using AntiBERTy (Ruffolo et al., 2021)
(via IgFold (Ruffolo et al., 2023) package) and ESM2 (Lin et al., 2022) ( esm2_t12_35M_UR50D )
models, respectively. In our dataset interface package, we also provide a simple embedding method
using one-hot encoding for amino acid residues. Other node embedding methods can be easily
incorporated into our dataset interface.
4.3 Dataset split
We propose two types of dataset split settings. The first is a random split based on the ratio of epitope
to antigen surface residues,#epitope nodes
#antigen nodes; the second is a more challenging setting where we split the
5
dataset by epitope groups. The first setting is straightforward and used by previous methods. The
second setting is more challenging because it requires the model to generalize to unseen epitope
groups.
Split by epitope to antigen surface ratio As aforementioned, the number of non-interface nodes
in the antigen graph is much larger than the number of interface nodes. While epitopes usually
have a limited number of residues, typically around 14.6±4.9amino acids (Reis et al., 2022), the
antigen surface may extend to several hundred or more residues. The complexity of the classification
task therefore increases with the antigen surface size. To ensure similar complexity among train,
validation, and test sets, we stratified the dataset to include a similar distribution of epitope to non-
epitope nodes in each set. Table S3 shows the distribution of epitope-to-antigen surface ratios in each
set. This led to 1383 antibody-antigen complexes for the training set and 170complexes each for the
validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-ratio.csv .
Split by epitope groups This is motivated by the fact that antibodies are highly diverse in the CDR
loops and by changing the CDR sequences it is possible to engineer novel antibodies to bind different
sites on the same antigen. This was previously observed in the EpiPred dataset where Krawczyk et al.
(2014) tested the specificity of their method on five antibodies associated with three epitopes on the
same antigen, hen egg white lysozyme.
We inlcude 641unique antigens and 973epitope groups in our dataset. We include multi-epitope
antigens. For example, there are 64distinct antibodies that bind to coronavirus spike protein.
We can see that different antibodies bind to different locations on the same antigen. Details of
all epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv . We then
split the dataset into train, validation, and test sets such that the epitopes in the test set are not
found in either train or validation sets. We followed an 80%/10%/10% split for the number of
complexes in each set. This resulted in 1383 complexes for the training set and 170complexes for
the validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-group.csv .
User-friendly Dataset Interface We implemented a Python package interface for our dataset using
PyTorch Geometric (Fey & Lenssen, 2019). Users can load the dataset as a PyTorch Geometric
dataset object and use it with PyTorch Geometric’s data loaders. We provide an option to load node
embeddings derived from AntiBERTy and ESM2 or simply one-hot embeddings. Each data object in
the dataset is a pair of antibody and antigen graphs; both node- and edge-level labels are provided,
and the node-level labels are used for the epitope prediction task.
5 WALLE: a graph-based method for epitope prediction
Alongside our dataset interface, we also provide a graph-based model named WALLE. It takes as
input a pair of antibody and antigen graphs, constructed as detailed above for the AsEP dataset, and
makes node- and edge-level predictions.
Graph Modules The architecture of WALLE incorporates graph modules that process the input
graphs of antibody and antigen structures, as depicted in Figure 3). Inspired by PECAN and EPMP,
our model treats the antibody and antigen graphs separately, with distinct pathways for each. The
antibody graph is represented by node embeddings XAwith a shape of (M,512) and an adjacency
matrix EA, while the antigen graph is described by node embeddings XBwith a shape of (N,480)
and its corresponding adjacency matrix EB. The embedding sizes are consistent with AntiBERTy
and ESM2 ( esm2_t12_35M_UR50D ).
Both antibody and antigen graph nodes are first projected into the dimensionality of 128using fully
connected layers. The resulting embeddings are then passed through two Graph Convolutional
Network (GCN) modules consecutively to refine the features and yield updated node embeddings X′
A
andX′
Bwith a reduced dimensionality of (M,64). The output from the first GCN layer is passed
through a ReLU activate function. Outputs from the second GCN layer are directly fed into the
Decoder module. These GCNs operate independently, each with its own parameters, ensuring that
the learned representations are specific to the antibody or the antigen.
6
GCN (128) GCN (128)
DecoderGCN (64) GCN (64)
Antigen Graph
Node
Edge index Antibody CDR Graph
Node
Edge index Preprocessing
AntibodyPreprocessing
AntigenAbAg
complex
structureFigure 3: A schematic of the preprocessing step that turns an input antibody-antigen complex structure
into a graph pair and the model architecture of WALLE.
The use of separate GCN modules for the antibody and antigen allows for the capture of unique
structural and functional characteristics pertinent to each molecule before any interaction analysis.
This design choice aligns with the understanding that the antibody and antigen have distinct roles in
their interactions and their molecular features should be processed separately.
Decoder
We used a simple decoder to predict the binary labels of edges between the antibody and antigen
graphs, which takes a pair of node embeddings output by the graph modules as input and predicts the
probability of each edge. An edge is assigned a binary label of 1if the predicted probability is greater
than0.5or0otherwise. This is shown as the Decoder module in Figure 3. For the epitope prediction
task, we convert edge-level predictions to node-level by summing the predicted probabilities of all
edges connected to an antigen node; we assign the antigen node a label of 1if the number of connected
edges is greater than a threshold or 0otherwise. The threshold is treated as a hyperparameter and is
optimized in the experiments.
Implementation
We used PyTorch Geometric (Fey & Lenssen, 2019) framework to build our model. The graph
modules are implemented using the GCNConv module from PyTorch Geometric. We trained the
model to minimize a loss function consisting of two parts: a weighted binary cross-entropy loss
for the bipartite graph link reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph. We used the same set of hyperparameters and loss functions for both
dataset settings. The loss function and hyperparameters are described in detail in Appendix A.6.
Experiment results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1).
References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A Appendix-A
A.1 Related work
Comparison of Previous Datasets We would like to highlight our dataset, AsEP, is the largest
curated AbAg benchmarking dataset to date. Existing ones either focus on general protein-protein
complexes designed to develop general docking methods or are way smaller than AsEP if designed
for AbAg interaction research. We summarized the sizes of existing datasets in the following table.
Table S1: Comparison of Dataset Sizes Across Different Methods
Method Dataset Size
WALLE (AsEP) 1723 AbAg complexes
Gao et al. 2022 Gao et al. (2022) 258 AbAg complexes
CSM-AB Myung et al. (2021) 472 AbAg complexes
SAGERank Sun et al. (2023) 287 AbAg complexes
Bepipred3.0 Clifford et al. (2022) 582 AbAg complexes
SCEptRe Mahajan et al. (2019) is a related dataset that keeps a weekly updated collection of 3D
complexes of epitope and receptor pairs, for example, antibody-antigen, TCR-pMHC, and MHC-
ligand complexes derived from the Immune Epitope Database (IEDB). Our approach for clustering
antibody-antigen complexes regarding their epitopes is similar to theirs, with the difference in the
clustering strategy. We cluster by antigen, then epitope group, and we allow mutated amino acids
in the same epitope region because we turn the epitope sites into columns in the multiple sequence
alignment. In contrast, SCEptRe clusters by antibody and then compares epitope similarity by
epitope conformation using atom-pair distances via PocketMatch Yeturu & Chandra (2008), which is
beneficial for comparing the function of various paratopes but is less suitable for our task of predicting
epitope residues.
Sequence-based epitope predictor We also tested purely sequence-based epitope prediction tool,
for example, Bepipred3.0 Clifford et al. (2022) on our dataset. Bepipred3.0 uses ESM2 model,
esm2_t33_650M_UR50D to generate sequence embeddings and was trained on a smaller dataset
of 582 antibody-antigen structures and evaluated on 15 antibody-antigen complexes. The authors
provided a relatively larger evaluation of linear B-cell epitopes derived from the Immune Epitope
Database and reported an AUC-ROC of 0.693on the top 10% of the predicted epitopes. We tested
Bepipred3.0 on our dataset and found its performance degenerates significantly, as shown in the table
below. This is not surprising because linear epitopes are consecutive positions in an antigen sequence,
and this task fits better with language model design. Additionally, as pointed out by the authors,
approximately 90% of epitopes (B-cell) fall into the conformational category Clifford et al. (2022),
which highlights the importance of the present benchmark dataset composed of conformational
epitopes derived from filtered antibody-antigen structures. We believe these results underline the
findings in our paper, showing that large language models alone, even if specialized for antibody-
antigen interactions, do not encompass all the relevant information needed for epitope prediction.
13
Confidence Threshold Top 10% Top 30% Top 50% Top 70% Top 90%
AUC 0.693392 0.693392 0.693392 0.693392 0.693392
Balanced Accuracy 0.573132 0.636365 0.638755 0.604556 0.542274
MCC 0.109817 0.140183 0.134689 0.113372 0.071876
Precision-Recall AUC 0.176429 0.176429 0.176429 0.176429 0.176429
Accuracy 0.850178 0.701202 0.536947 0.362489 0.179051
Precision 0.169202 0.141361 0.120547 0.104286 0.090441
Recall 0.236760 0.553204 0.756607 0.892628 0.977723
F1-Score 0.173370 0.208366 0.197153 0.179294 0.160151
Table S2: Bepipred3.0 results for the presented AsEP dataset. The distance cutoff was changed to
4.0Å, as this is the threshold used by Bepipred3.0. Results are shown for five confidence thresholds
as described in the BepiPred-3.0 paper. Across all stringency settings and metrics, Bepipred scored
lower than Walle. Furthermore, it is possible that some of the structures within the dataset are
contained within the Bepipred3.0 dataset, artificially increasing scores.
A.2 Evaluation
In this work, we focus on the epitope prediction task. We evaluate the performance of each method
using consistent metrics. Matthew’s Correlation Coefficient (MCC) is highly recommended for binary
classification assessments Matthews (1975) and is especially advocated for its ability to provide equal
weighting to all four values in the confusion matrix, making it a more informative metric about the
classifier’s performance at a given threshold than other metrics Chicco & Jurman (2020, 2023). We
encourage the community to adopt MCC for the epitope prediction task as it takes into account true
and false positives, as well as true and false negatives, offering a comprehensive measure of the
performance. It is considered superior to the AUC-ROC, which is evaluated over all thresholds. For
consistency, we also included Precision and Recall from prior studies EpiPred Krawczyk et al. (2014)
and PECAN Pittala & Bailey-Kellogg (2020), and we added Area Under the Receiver Operating
Characteristic Curve (AUC-ROC) and F1 score, both are typical binary classification metrics. For
methods that predict antibody-antigen complex structures, we determine the epitopes using the same
distance criterion as aforementioned.
A.3 Steps to build antibody-antigen complex dataset
We sourced our initial dataset from AbDb (version dated September 26, 2022), containing 11,767
antibody files originally collected from the Protein Data Bank (PDB). We collected complexes
numbered in Martin scheme Raghavan & Martin (2008) and used AbM CDR definition Martin et al.
(1991) to identify CDR residues from the heavy and light chains of antibodies.
We extracted antibody-antigen complexes that met the following criteria: (1) both VH and VL
domains are present in the antibody; (2) the antigen is a single-chain protein consisting of at least 50
amino acids; and (3) there are no unresolved CDR residues, yielding 4,081 files.
To deduplicate complexes, we used MMseqs2 Steinegger & Söding (2017) to cluster the complexes
by heavy and light chains in antibodies and antigen sequences. We used the easy-linclust mode with
the–cov-mode 0 option to cluster sequences; we used the default setting for coverage of aligned
cutoff at 80%; we used different –min-seq-id cutoffs for antibodies and antigens because the antibody
framework regions are more conserved than the CDR regions. We cluster heavy and light chains at
–min-seq-id cutoff of 100% and70%, respectively. We retained only one representative file for each
unique set of identifiers, leading to a refined dataset of 1,725 files.
Two additional files were manually removed. File 6jmr_1P was removed because its CDR residues
are masked with ‘UNK’ labels and the residue identities are unknown; file 7sgm_0P was removed
because of a non-canonical residue ‘DV7’ in its CDR-L3 loop.
The final dataset consists of 1,723 antibody-antigen complexes.
14
A.4 Pipeline to build graph dataset from AbDb
Prepare Graph Dataset
Raw Structure Files
AbDb Complex
antigenOriginal PDB filePDB id
AbDb PDB
Y es
[U, F]Coordinates, Sequences
Antigen Structure
Atom
Chain
ResidueSEQRES (U) ATMSEQ (V)
len(seq) > thr Processing Modules
Calculate
ASA
(DSSP)Calculate
distance
matrix Residue
CheckingSequence
AlignmentSequence
Embedding
(ESM)Intermediate Data
ATMSEQ2NODES
Mask (V -> N)SEQRES2A TMSEQ
Mask (U -> V)residue-residue
distance matrix
(V, V)Pre Node
Labels (V , 1)MasksApply Mask I
(V --> N)Apply Mask I
(V --> N)Apply Mask I & II
(U --> V --> N)[V, ] [V, V]Output Graph
Label
(N, 1)Edge
(2, E)Node
Embeddings
(N, C)
Figure S1: Pipeline to convert an antibody-antigen complex structure into a graph representation.
•Row 1 : given an AbAg complex PDB ID, retrieve ‘AbAg complex’ from AbDb and ‘raw
structure’ file from PDB as input, ‘AbDb complex antigen’ and ‘Original PDB file’ in the
top lane.
•Row 2 : They are then parsed as hierarchical coordinates (Antigen Structure), and extract
ATMSEQ and SEQRES sequences.
•Row 3 : these are then passed to a set of in-house modules for calculating solvent access
surface area (ASA), distance matrix, and filtering out problematic residues, which generates
an ATMSEQ2NODES mask. The sequence alignment module aligns ATMSEQ with
SEQRES sequences to generate a mask mapping from SEQRES to ATMSEQ. The
Sequence Embedding module passes SEQERS through the ESM module to generate
embeddings. ESM requires input sequence length and therefore filters out sequences longer
than 1021 amino acids.
•Row 4 : holds intermediate data that we apply masks to generate graph data in Row 5 .
•Row 6 : Apply the masks to map SEQRES node embeddings to nodes in the graphs and
calculate the edges between the graph nodes.
U,VandNdenote the number of residues in the SEQRES sequence, ATMSEQ sequence and the
graph, respectively. thr(at 50 residues) is the cutoff for antigen SEQRES length. We only include
antigen sequences with lengths of at least 50 residues. SEQRES andATMSEQ are two different
sequence representations of a protein structure. SEQRES is the sequence of residues in the protein
chain as defined in the header section of a PDB file, and it is the complete sequence of the protein
chain. ATMSEQ is the sequence of residues in the protein chain as defined in the ATOM section of a
PDB file. In other words, it is read from the structure, and any residues in a PDB file are not resolved
due to experimental issues that will be missing in the ATMSEQ sequence. Since we are building
graph representations using structures, we used ATMSEQ . However, the input to the language models
15
require a complete sequence, therefore we used SEQRES to generate node embeddings, and mapped
the node embeddings to the graph nodes. We performed two pairwise sequence alignments to map
such embeddings to graph vertices for a protein chain with Clustal Omega Sievers et al. (2011). We
first align the SEQRES sequence with the atom sequence (residues collected from the ATOM records
in a PDB file) and assign residue embeddings to matched residues. Because we excluded buried
residues from the graph, we aligned the sequence formed by the filtered graph vertices with the atom
sequence to assign residue embeddings to vertices. ASA is the solvent-accessible surface area of a
residue. If a residue has an ASA value of zero, it is considered buried and will be removed from the
graph.
A.5 Dataset split
Table S3: Distribution of epitope to antigen surface nodes in each set.
Epi/Surf Training Validation/Test
0, 5% 320 (23% ) 40 (24%)
5% , 10% 483 (35% ) 60 (35%)
10%, 15% 305 (22% ) 38 (22%)
15%, 20% 193 (14% ) 24 (14%)
20%, 25% 53 (4% ) 6 (4% )
25%, 30% 19 (1% ) 2 (1% )
30%, 35% 8 (0.6%) 0 (- )
35%, 40% 2 (0.1%) 0 (- )
sum 1383 170
A.6 Implementation details
Exploratory | Section not found | Section not found | Data Analysis We performed exploratory data analysis on the training dataset to
understand the distribution of the number of residue-residue contacts in the antibody-antigen interface.
We found that the number of contacts is approximately normally distributed with a mean of 43.42
and a standard deviation of 11.22 (Figure S2). We used this information to set the regularizer in the
loss function to penalize the model for predicting too many or too few positive edges.
0 20 40 60 80 100
Number of contacts0.0000.0050.0100.0150.0200.0250.0300.035Density
Mean: 43.42 Median: 44.00
HDI Left: 34.00 HDI Right: 49.00Number of contacts (bipartite graph edges) per AbAg complex
Mean
Median
50.0% HDI
Fitted Normal
Distribution
( = 43.42, = 11.22)
Figure S2: Blue line: distribution of the number of residue-residue contacts in antibody-antigen
interface across the dataset with a mean and median of 43.27 and 43.00, respectively. Red line: fitted
normal distribution with mean and standard deviation of 43.27 and 10.80, respectively.
16
Loss function Our loss function is a weighted sum of two parts: a binary cross-entropy loss for
the bipartite graph linkage reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph.
Loss =Lr+λNX
ˆe−c(3)
Lr=−1
NNX
i=1(wpos·ye·log( ˆye) +wneg·(1−ye)·log(1−ˆye)) (4)
The binary cross-entropy loss Lris weighted by wposandwnegfor positive and negative edges,
respectively. During hyperparameter tuning, we kept wnegfixed at 1.0and tuned wpos.Nis the
total number of edges in the bipartite graph, yedenotes the true label of edge e, and ˆyedenotes the
predicted probability of edge e. The regularizerPNˆe−cis the L1 norm of the difference between
the sum of the predicted probabilities of all edges of the reconstructed bipartite graph and the mean
positive edges in the training set, i.e., cset to 43. This aims to prevent an overly high false positive
rate, given the fact that the number of positive edges is far less than positive edges. The regularizer
weight λis tuned during hyperparameter tuning.
Hyperparameters We carried out hyperparameter search within a predefined space that included:
•Weights for positive edges in bipartite graph reconstruction loss, sampled uniformly between 50
and 150.
•Weights for the sum of bipartite graph positive links , where values were drawn from a log-
uniform distribution spanning 1e−7to1e−4.
•Edge cutoff (x) , defining an epitope node as any antigen node with more than x edges, with x
sampled following a normal distribution with a mean of 3 and a standard deviation of 1.
•Number of graph convolutional layers in the encoder, we tested using 2 and 3 layers.
•Decoder type was varied between two configurations:
–A fully connected layer, equipped with a bias term and a dropout rate of 0.1.
–An inner product decoder.
Computing resources All experiments were performed on a single Linux machine (Ubuntu 22.04)
with one NVIDIA RTX3090 GPU card, and it took on average 3 hours for a single hyper-parameter
sweeping experiment.
A.7 Antibody-antigen complex examples
To compare the epitopes of antibodies in AsEP, we first clustered these complexes by antigen
sequences to group together antibodies targeting the same antigen via MMseqs2 Steinegger & Söding
(2017). Specifically, we ran MMseqs2 on antigen SEQRES sequences and using the following setup:
•easy-linclust mode
•cov-mode set to 0with the default coverage of 80%: this means a sequence is considered a cluster
member if it aligns at least 80% of its length with the cluster representative;
•min-seq-id set to 0.7: this means a sequence is considered a cluster member if it shares at least
70% sequence identity with the cluster representative.
We encourage the reader to refer to the MMseqs2 documentation https://github.com/
soedinglab/mmseqs2/wiki for more details on the parameters used.
We then identify epitopes using a distance cut-off of 4.5 Å. An antigen residue is identified as epitope
if any of its heavy atoms are located within 4.5 Å of any heavy atoms from the antibody.
To compare epitopes of antibodies sharing the same antigen cluster, we aligned the antigen SEQRES
sequences using Clustal Omega Sievers et al. (2011) (download from: http://www.clustal.org/
omega/ ) to obtain a Multiple Sequence Alignment (MSA). Epitopes are mapped to and denoted as
the MSA column indices. The epitope similarity between a pair of epitopes is then calculated as
17
the fraction of identical columns. Two epitopes are identified as identical if they share over 0.7of
identical columns.
Table S4: Antibody-Antigen Complex Examples
(a) Antigen Group Information
abdbid repr size epitope_group
7eam_1P 7sn2_0P 183 0
5kvf_0P 5kvd_0P 9 1
5kvg_0P 5kvd_0P 9 2
(b) CDR Sequences (Heavy Chain)
abdbid H1 H2 H3
7eam_1P GFNIKDTYIH RIDPGDGDTE FYDYVDYGMDY
5kvf_0P GYTFTSSWMH MIHPNSGSTN YYYDYDGMDY
5kvg_0P GYTFTSYGIS VIYPRSGNTY ENYGSVY
(c) CDR Sequences (Light Chain)
abdbid L1 L2 L3
7zf4_1P RASGNIHNYLA NAKTLAD QHFWSTPPWT
7zbu_0P KSSQSLLYSSNQKNYLA WASTRES QQYYTYPYT
7xxl_0P KASQNVGTA V A SASNRYT QQFSSYPYT
(d) Structure Titles
abdbid resolution title repr_title
7zf4_1P 1.4 immune complex of SARS-CoV-2
RBD and cross-neutralizing antibody
7D6SARS-CoV-2 Omicron variant spike
protein in complex with Fab XGv265
7zbu_0P 1.4 Zika specific antibody, ZV-64, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
7xxl_0P 1.4 Zika specific antibody, ZV-67, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
Here we provide three example antibody-antigen complexes from the same antigen group, meaning
the antigen sequences from each member complex share sequence identity of the aligned region at
least 70%. Due to space limitation, we have broken the rows into four parts: Antigen group
information, CDR sequences, and structure titles.
•abdbid : AbDb ID of the group member;
•repr: AbDb ID of the antigen representative;
•size: the number of complexes in the group;
•epitope_group : A categorical identifier of the epitope group the antibody-antigen complex
belongs to;
•H1,H2,H3,L1,L2,L3: CDR sequences of the heavy and light chains;
•resolution : Structure resolution;
•title: Structure title of the member;
•repr_title : Structure title of the antigen representative.
18
A.8 Multi-epitope Antigens
We include 641unique antigens and 973epitope groups in our dataset. Figure S3 shows two examples
of multi-epitope antigens in our dataset, hen egg white lysozyme (Figure S3a) and spike protein
(Figure S3b). Specifically, there are 52and64distinct antibodies in our dataset that bind to hen egg
white lysozyme and spike protein, respectively. For visual clarity, we only show five and sixteen
antibodies in Figure S3a and Figure S3b.
We can see that different antibodies bind to different locations on the same antigen. Details of all
epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv with annotation
provided in Appendix A.7.
(a) Five different antibodies bound to hen egg white lysozyme. Complexes are superimposed on the antigen
structure (magenta). AbDb IDs of the complexes and their color: 1g7i_0P (green), 2yss_0P (cyan), 1dzb_1P
(yellow), 4tsb_0P (orange), 2iff_0P (wheat). Antigens are colored in magenta.
(b) Sixteen different antibodies bound to coronavirus spike protein. Complexes are superimposed on the antigen
structure (magenta) and antibodies are in different colors. AbDb IDs of the complexes: 7k8s_0P, 7m7w_1P,
7d0b_0P, 7dzy_0P, 7ey5_1P, 7jv4_0P, 7k8v_1P, 7kn4_1P, 7lqw_0P, 7n8i_0P, 7q9i_0P, 7rq6_0P, 7s0e_0P, 7upl_1P,
7wk8_0P, 7wpd_0P.
Figure S3: Examples of different antibodies binding to the same antigen.
19
A.9 Metrics definition
MCC =(TP×TN−FP×FN)p
(TP+FP)(TP+FN)(TN+FP)(TN+FN)
Precision =TP
TP+FP
Recall =TP
TP+FN
F1 =2×Precision ×Recall
Precision +Recall
TP: True Positive
FP: False Positive
TN: True Negative
FN: False Negative
A.10 Fine-tuning ESMBind on AsEP
The performance reported in the main text for ESMBind is derived by fine-tuning ESM2 on general
protein binding sites. We performed a further fine-tuning experiment, fine-tuning it on the presented
AsEP dataset and evaluating it on the AsEP test set to enable a more direct comparison of ESMBind
to WALLE. Fine-tuning of ESMBind on AsEP was done using the Low-Rank Adaptation method Hu
et al. (2021).
Table S5: Performance Metrics
Metric Value
MCC 0.103923
Accuracy 0.504478
AUC-ROC 0.584497
Precision 0.128934
Recall 0.707731
F1 0.213829
20
B Appendix: Link prediction baseline
While the majority of existing studies focus on node-level prediction, i.e., predicting which residues
are likely to be the epitope residues, we are interested in predicting the interactions between epitope
and antigen residues. We argue that, on the one hand, this would provide a more comprehensive
understanding of the interaction between epitopes and antigens, and on the other hand, it would be
good in terms of model interpretability. Existing methods for predicting epitope residues are mostly
based on sequence information, which is not directly interpretable in terms of the interaction between
epitopes and antigens.
Our hyperparameter search was conducted within a predefined space as defined in Appendix A.6.
We used the Bayesian optimization strategy implemented through Weights & Biases, targeting the
maximization of the average bipartite graph link Matthew’s Correlation Coefficient (MCC).
The optimization process was managed using the early termination functionality provided by the
Weights & Biases’ Hyperband method Falkner et al. (2018), with a range of minimum to maximum
iterations set from 3 to 27.
The best set of hyperparameters is 2GCNConv layers, a batch size of 32, a weight for positive edges
of54.7, a weight for the sum of positive links at approximately 5.75e−7, and an edge cutoff of 2.38.
The resulting MCC evaluated on the test set was 0.072(standard error: 0.009) for the bipartite graph
link prediction task.
Table S6: Evaluation of WALLE on the bipartite graph link prediction task
Metric Mean (Standard Error)
MCC 0.072 (0.009)
ROC-AUC 0.582 (0.011)
Precision 0.049 (0.008)
Recall 0.167 (0.023)
F1 0.053 (0.007)
21
C Appendix: Ablation Studies
To investigate the impact of different components on WALLE’s performance, we carried out ablation
studies and described them in this section. For each model variant, we performed hyperparameter
tuning and reported the evaluation performance using the model with the best performance on the
validation set.
C.1 Ablation study: replace graph component with linear layers
To investigate whether the graph component within the WALLE framework is essential for its
predictive performance, we conducted an ablation study in which the graph component was replaced
with two linear layers. We refer to the model as ‘WALLE-L’. The first linear layer was followed by a
ReLu activation function. Logits output by the second linear layer were used as input to the decoder.
The rest of the model architecture remained the same.
It differs from the original WALLE model in that the input to the first linear layer is simply the
concatenation of the embeddings of the antibody and antigen nodes, and the linear layers do not
consider the graph structure, i.e., the spatial arrangement of either antibody or antigen residues. The
model was trained using the same hyperparameters as the original WALLE model. The performance
of WALLE-L was evaluated on the test set using the same metrics as the original WALLE model.
C.2 Ablation study: WALLE with simple node encoding
The presented WALLE model utilizes embeddings from large language models, including ESM2 Lin
et al. (2022) or IgFoldRuffolo et al. (2023) for representing amino acid sequences, as these models
are able to capture the sequential and structural information inherent in protein sequences, providing
a rich, context-aware representation of amino acids. To test the effectiveness of such embeddings
in this downstream task, we conducted an ablation study where we replaced the embeddings from
language models with simple node encodings. Specifically, we evaluated the performance of WALLE
when using ‘one-hot’ encoding and ‘BLOSUM62’ encoding for amino acids in both antibody and
antigen sequences.
C.3 Ablation study: WALLE with ESM2 embeddings for both antibodies and antigens
We also investigated whether the choice of language models can impact the predictive performance
of WALLE; we conducted an ablation study to evaluate the performance of WALLE when both
antibodies and antigens are represented using embeddings from the ESM2 language model Lin et al.
(2022) while the original model uses AntiBERTy Ruffolo et al. (2023) for antibodies as it is trained
exclusively on antibody sequences. This also tests whether a language model trained on general
protein sequences can be used for a downstream task like antibody-antigen interaction prediction.
One-hot encoding
One-hot encoding is a method where each residue is represented as a binary vector. Each position in
the vector corresponds to a possible residue type, and the position corresponding to the residue present
is marked with a 1, while all other positions are set to 0. This encoding scheme is straightforward and
does not incorporate any information about the physical or chemical properties of the residues. This
method tests the model’s capability to leverage structural and relational information from the graph
component without any assumptions introduced by more complex encoding schemes.
BLOSUM62 encoding
BLOSUM62 Henikoff & Henikoff (1992) encoding involves using the BLOSUM62 matrix, which
is a substitution matrix used for sequence alignment of proteins. In this encoding, each residue
is represented by its corresponding row in the BLOSUM62 matrix. This method provides a more
nuanced representation of residues, reflecting evolutionary relationships and substitution frequencies.
22
C.4 Hyperparameter tuning
We used the same hyperparameter search space defined in Appendix A.6 and performed a hyperpa-
rameter search as defined in Appendix B for each model variant in the ablation studies. We report the
evaluation performance of the tuned model for each variant in Table S7.
Table S7: Performance of WALLE without graph component and simple node encodings on test set
from dataset split by epitope to antigen surface ratio.
Algorithm Encoding MCC AUCROC Precision Recall F1
WALLE Both 0.2097 (0.0195) 0.6351 (0.0126) 0.2346 (0.0183) 0.4217 (0.0279) 0.2580 (0.0178)
WALLE-L Both 0.1593 (0.0155) 0.6124 (0.0109) 0.1750 (0.0109) 0.4696 (0.0243) 0.2371 (0.0137)
WALLE ESM2 0.1955 (0.0212) 0.6219 (0.0137) 0.2280 (0.0188) 0.4103 (0.0291) 0.2553 (0.0188)
WALLE-L ESM2 0.1445 (0.0138) 0.6100 (0.0097) 0.1598 (0.0102) 0.5355 (0.0216) 0.2266 (0.0125)
WALLE One-hot 0.0968 (0.0094) 0.5830 (0.0076) 0.1185 (0.0052) 0.8923 (0.0118) 0.2026 (0.0081)
WALLE BLOSUM 0.0848 (0.010) 0.5739 (0.0081) 0.1182 (0.0055) 0.8401 (0.0151) 0.1993 (0.0083)
The values in parentheses represent the standard error of the mean; ‘WALLE-L’ refers to WALLE
with the graph component replaced by two linear layers. ‘ESM2’ refers to the embeddings from the
ESM2 language model esm2_t12_35M_UR50D . ‘One-Hot’ refers to one-hot encoding of amino
acids. ‘BLOSUM62’ refers to the BLOSUM62 encoding of amino acids. ‘Both’ refers to embedding
antibodies and antigens using the esm2_t12_35M_UR50D ESM2 model and AntiBERTy (via IgFold)
language model, respectively. The best performing model is highlighted in bold.
We observed that WALLE’s performance with simple node encodings (‘one-hot’ and ‘BLOSUM62’)
is considerably lower than when using advanced embeddings from language models. This indicates
that the embeddings derived from language models capture more nuanced information about the
amino acids, enabling the model to better predict epitope-antigen interactions.
The degenerated performance of WALLE with simple encodings can be attributed to the lack of
contextual information and structural features in these representations. The high recall but low
precision values suggest that the model is unable to distinguish between true and false interactions,
leading to a high number of false positives. This highlights the importance of using meaningful
embeddings that capture the rich structural and sequential information present in protein sequences.
When comparing WALLE with WALLE-L (without the graph components), we observe that the
model’s performance drops considerably when the graph component is replaced with fully connected
linear layers. This indicates that the topological information captured by the graph component also
contributes to the model’s predictive performance.
We also observed that WALLE with ESM2 embeddings for both antibodies and antigens achieved
similar performance to WALLE with AntiBERTy and ESM2 embeddings for antibodies and antigens,
respectively. This suggests that the ESM2 embeddings somehow provide effective information for
both antibodies and antigens without training exclusively on antibody sequences.
D Impact Statement
This work extends to the optimization of antibody drug development, offering a more efficient and
accurate method for predicting where antibodies bind on antigens, a crucial challenge of developing
therapeutic antibodies. The potential impact of this advancement is underscored by the recent
approval of 136 antibody-based drugs in the United States or European Union, with 17 novel
antibody therapeutics approved since January 2023 and 18 more currently under review (Antibody
Society, Antibody therapeutics approved or in regulatory review in the EU or US, https://www.
antibodysociety.org/resources/approved-antibodies/ , 24 January 2024). These figures
show the transformative impact that antibody design innovation can have on transforming the
landscape of therapeutic development, offering new avenues for targeted, effective treatments that
can be developed in a more time- and cost-effective manner. Such advancements hold immense
potential in accelerating the creation of targeted therapies and implicitly support the broader goals of
personalized medicine. Fast-tracking antibody design through in silico epitope prediction can enable
quicker responses to emerging health threats like pandemics or rapidly mutating pathogens. However,
23
in silico predictions should not be blindly trusted and should merely guide and streamline research
and diligent testing, not replace it.
This paper presents work whose goal is to highlight antibody-specific epitope prediction as a major
challenge that has not been widely studied to date, which is presented as a bipartite graph connectivity
prediction task. This research stands out primarily for its development of a novel benchmarking
dataset for antibody-specific epitope prediction - a resource previously unavailable in the scientific
community with the potential to set a new standard in the field.
Existing methods are compared using uniform metrics and a vast room for improvement can be
demonstrated across the board. A novel model is presented, which surpasses its counterparts by
an order of magnitude, outperforming them by a factor of ten, validating its graph-based approach
utilizing antibody and antigen structural information as well as leveraging protein language models.
We provide a foundational framework that invites other researchers to further build upon and refine
this baseline model, which we have demonstrated to be a highly effective approach for this task.
Open availability of the dataset and model facilitates further research and exploration in this domain,
expediting the development of more advanced models. Highlighting types of antibody-antigen
interactions that are disregarded in existing datasets and methods encourages the examination of
shortcoming of current models. The focus on conventional antibodies in this work lays the groundwork
for future exploration into epitope prediction for novel antibodies, such as nanobodies, expanding
upon potential applications.
24
Supplementary Materials
Dataset Documentation and Intended Uses
We provide a data card for this dataset, DataCard-AsEP.md , which can be downloaded using this
link: https://drive.google.com/file/d/1fc5kFcmUdKhyt3WmS30oLLPgnkyEeUjJ/view?
usp=drive_link
This dataset provides a unified benchmark for researchers to develop new machine-learning-based
methods for the epitope prediction task.
Access to the Dataset
There are two alternative sources where users can download the dataset:
•The dataset can be downloaded using the Python interface provided by our GitHub Reposi-
tory AsEP-dataset. Detailed instructions on how to download the dataset are provided in the
README file. Briefly, after installing the provided Python module, asep , the dataset can
be downloaded by running the following command in the terminal:
download - asep / path /to/ directory AsEP
# For example , to download the dataset to the current
,→directory , run
# download - asep . AsEP
•The dataset and benchmark are provided through Zenodo at https://doi.org/10.5281/
zenodo.11495514 .
• Code and Dataset interface is provided in our GitHub Repository AsEP-dataset athttps:
//github.com/biochunan/AsEP-dataset .
Author Statement
The authors affirm that they bear all responsibility in case of violation of rights, etc., and confirm the
data license. The dataset is licensed under the CC BY 4.0 License ( https://creativecommons.
org/licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License (https://opensource.org/licenses/MIT ).
Hosting, Licensing, and Maintenance Plan
The dataset is hosted on Zenodo, which provides a DOI (10.5281/zenodo.11495514) for the dataset.
It also comes with a Python interface provided in our GitHub Repository, AsEP-dataset at https:
//github.com/biochunan/AsEP-dataset , where users can submit issues and ask questions.
Future releases and updates will be made available through the same channels. As discussed in the
main text, the future plan includes expanding the dataset to include novel types of antibodies, such as
single-domain antibodies, and providing more sophisticated features for graph representations. The
dataset will be maintained by the authors and will be available for a long time.
Links to Access the Dataset and Its Metadata
The dataset, benchmark, and metadata are provided through Zenodo.
25
The Dataset
The dataset is constructed using pytorch-geometric Dataset module. The dataset can be loaded
using the following code:
from asep . data . asepv1_dataset import AsEPv1Evaluator
evaluator = AsEPv1Evaluator ()
# example
torch . manual_seed (0)
y_pred = torch . rand (1000)
y_true = torch . randint (0, 2, (1000 ,) )
input_dict = {’y_pred ’: y_pred , ’y_true ’: y_true }
result_dict = evaluator . eval ( input_dict )
print ( result_dict ) # got {’auc - prc ’: tensor (0.5565) }
We also provide detailed documentation of the dataset content on Zenodo and include a description
below:
•asepv1-AbDb-IDs.txt : A text file containing the AbDb identifiers of the 1723 antibody-
antigen pairs in the dataset.
•asepv1_interim_graphs.tar.gz : Contains 1723 .ptfiles, where each file is a dictio-
nary with structured data:
abdbid A string representing the antibody AbDb identifier.
seqres A dictionary containing:
abAn OrderedDict mapping string chain labels HandLto their corresponding se-
quence strings, representing heavy and light chains respectively.
agA dictionary mapping string chain labels to their corresponding sequence strings.
mapping Includes:
abContains:
seqres2cdr A binary numpy array indicating the CDR positions in the antibody
sequence.
agContains:
seqres2surf A binary numpy array indicating the surface residues in the antigen
sequence.
seqres2epitope A binary numpy array indicating the epitope residues in the
antigen sequence.
embedding Comprises:
abIncludes embeddings computed using the AntiBERTy model and ESM2 model for
the antibody sequences.
agIncludes embeddings for the antigen sequences computed using the ESM2 model.
edges Describes the interactions:
abA sparse coo tensor representing the binary edges between the CDR residues.
agA sparse coo tensor representing the binary edges between the surface residues.
stats Metadata about each antibody-antigen pair, including counts of CDR, surface, and
epitope residues, and the epitope-to-surface ratio.
•structures.tar.gz : Contains 1723 pdb structures, each named using the AbDb identi-
fier.
•split_dict.pt : Contains the train /val/test splits of the dataset, with splits based on
the epitope ratio and epitope group of the antigen.
Long-term Preservation
The current version of the dataset and benchmark are provided through Zenodo, which provides
long-term storage. Future versions will be made available through the same channel and users are
encouraged to submit queries and issues through the issues channel on the GitHub repository.
26
Explicit License
The dataset is licensed under the CC BY 4.0 license ( https://creativecommons.org/
licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License https://opensource.org/licenses/MIT .
Benchmarks
Detailed benchmark experiments and | results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1).
References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A Appendix-A
A.1 Related work
Comparison of Previous Datasets We would like to highlight our dataset, AsEP, is the largest
curated AbAg benchmarking dataset to date. Existing ones either focus on general protein-protein
complexes designed to develop general docking methods or are way smaller than AsEP if designed
for AbAg interaction research. We summarized the sizes of existing datasets in the following table.
Table S1: Comparison of Dataset Sizes Across Different Methods
Method Dataset Size
WALLE (AsEP) 1723 AbAg complexes
Gao et al. 2022 Gao et al. (2022) 258 AbAg complexes
CSM-AB Myung et al. (2021) 472 AbAg complexes
SAGERank Sun et al. (2023) 287 AbAg complexes
Bepipred3.0 Clifford et al. (2022) 582 AbAg complexes
SCEptRe Mahajan et al. (2019) is a related dataset that keeps a weekly updated collection of 3D
complexes of epitope and receptor pairs, for example, antibody-antigen, TCR-pMHC, and MHC-
ligand complexes derived from the Immune Epitope Database (IEDB). Our approach for clustering
antibody-antigen complexes regarding their epitopes is similar to theirs, with the difference in the
clustering strategy. We cluster by antigen, then epitope group, and we allow mutated amino acids
in the same epitope region because we turn the epitope sites into columns in the multiple sequence
alignment. In contrast, SCEptRe clusters by antibody and then compares epitope similarity by
epitope conformation using atom-pair distances via PocketMatch Yeturu & Chandra (2008), which is
beneficial for comparing the function of various paratopes but is less suitable for our task of predicting
epitope residues.
Sequence-based epitope predictor We also tested purely sequence-based epitope prediction tool,
for example, Bepipred3.0 Clifford et al. (2022) on our dataset. Bepipred3.0 uses ESM2 model,
esm2_t33_650M_UR50D to generate sequence embeddings and was trained on a smaller dataset
of 582 antibody-antigen structures and evaluated on 15 antibody-antigen complexes. The authors
provided a relatively larger evaluation of linear B-cell epitopes derived from the Immune Epitope
Database and reported an AUC-ROC of 0.693on the top 10% of the predicted epitopes. We tested
Bepipred3.0 on our dataset and found its performance degenerates significantly, as shown in the table
below. This is not surprising because linear epitopes are consecutive positions in an antigen sequence,
and this task fits better with language model design. Additionally, as pointed out by the authors,
approximately 90% of epitopes (B-cell) fall into the conformational category Clifford et al. (2022),
which highlights the importance of the present benchmark dataset composed of conformational
epitopes derived from filtered antibody-antigen structures. We believe these results underline the | findings evidence that epitope prediction benefits from combining se-
quential embeddings provided by language models and geometrical information
from graph representations, providing a guideline for future method design. In
addition, we reformulate the task as bipartite link prediction, allowing easy model
performance attribution and interpretability. We open-source our data and code at
https://github.com/biochunan/AsEP-dataset .
∗Address correspondence to: [email protected], [email protected], [email protected]
†Equal contributionarXiv:2407.18184v1 [cs.LG] 25 Jul 2024
1 Introduction
Antibodies are specialized proteins produced by our immune system to combat foreign substances
called antigens. Their unique ability to bind with high affinity and specificity sets them apart
from regular proteins and small-molecule drugs, making them increasingly popular in therapeutic
engineering.
While the community is shifting toward computational antibody design given a pre-determined
epitope (Jin et al., 2022; Zhou et al., 2024; Bennett et al., 2024), accurate prediction of epitopes
remains underexplored. Accurate identification of epitopes is beneficial for understanding antibody-
antigen interactions, antibody function, and streamlining antibody engineering. This task remains
challenging due to multiple factors (Akbar et al., 2022; Hummer et al., 2022), such as, the lack of
comprehensive datasets, limited interpretability and generalizability. Available datasets are limited
in size, up to 582 complexes from Bepipred-3.0 (Clifford et al., 2022), and feature disproportionate
representation among various epitopes.
Existing methods perform poorly on epitope prediction task (Cia et al., 2023), with a ceiling
MCC (Matthew’s Correlation Coefficient) of 0.06. However, recent advancements in graph-based
learning, coupled with an increase in available antibody structures in the Protein Data Bank
(PDB) (Berman et al., 2003), highlight the need to reevaluate current methods and establish a
benchmark dataset for predicting antibody-antigen interactions.
We approach the problem as a bipartite graph link prediction task. Traditionally, graph link prediction
focuses on identifying connections within the same graph, such as in protein-protein interaction
networks. Our research extends this concept to bipartite graphs at the molecular level and proposes
our own model, WALLE. Because existing methods generally predict protein binding sites or epitopes
in antibody-antigen complexes rather than residue-residue interactions, we focus on benchmarking
the node classification task while providing WALLE’s performance on the bipartite link prediction
task as a baseline.
2 Previous Work
Accurate epitope prediction for antibody design remains challenging due to the complexity of
antibody-antigen interactions and | Section not found | Section not found | Section not found | limitations of existing datasets and methods. Several computational
approaches have been developed, but they often fall short in terms of accuracy and applicability. Here,
we present a representative set of state-of-the-art methods.
EpiPred (Krawczyk et al., 2014) implements a graph-based antibody-antigen specific scoring func-
tion that considers all possible residue-residue pairs at the interface between anybody and antigen
structures. It samples surface patches from the antigen structure surface and selects the highest-ranked
patch with the highest score as the predicted set of epitope residues.
ESMFold (Lin et al., 2023) is a protein language model based on ESM2 (Lin et al., 2023), and its
folding head was trained on over 325 thousand protein structures. It achieves comparable performance
to AlphaFold2 (Jumper et al., 2021) and is included in our benchmarking due to its faster processing.
We also include methods that consider only antigens:
ESMBind (Schreiber, 2023) is a language model that predicts protein binding sites for single protein
sequence inputs. It is fine-tuned based on ESM2 (Lin et al., 2023) using Low-Rank Adaptation (Hu
et al., 2021) on a dataset composed of more than 200 thousand protein sequences with annotated
binding sites.
MaSIF-site (Gainza et al., 2020) is a geometric deep learning method that predicts binding sites on
the surface of an input protein structure. It converts antigen surfaces into mesh graphs, with each
mesh vertex encoded with geometric and physicochemical descriptors, and predicts binding sites as a
set of mesh vertices.
PECAN and EPMP (Pittala & Bailey-Kellogg, 2020; Vecchio et al., 2021) are graph neural networks
that predict epitope residues taken antibody-antigen structure pairs as input. They use position-
specific scoring matrices (PSSM) as node embeddings and graph attention networks to predict the
binary labels of nodes in the antigen graph. For details, we refer readers to Appendix A.1.
2
Two Complementary Surveys are notable:
Zhao et al. (2024) benchmarked docking methods like ZDOCK (Pierce et al., 2011), ClusPro (Kozakov
et al., 2017), and HDOCK (Yan et al., 2017), and Alphafold-Multimer (Evans et al., 2022) on a set of
112antibody-antigen complexes. They showed that all docking methods gave a success rate of 8.0%
at most if using the top 5 decoys; Alphafold-Multimer showed a better performance with a 15.3%
success rate.
Cia et al. (2023) focused on epitope prediction using a dataset of 268complexes, defining epitope
residues as having at least a 5%change in relative solvent accessibility upon complex formation. They
benchmarked various methods, finding existing methods insufficient for accurate epitope prediction.
3 Problem Formulation
Antibody-antigen interaction is important for analyzing protein structures. The problem can be
formulated as a bipartite graph link prediction task. The inputs are two disjoint graphs, an antibody
graph GA= (VA, EA)and an antigen graph GB= (VB, EB), where Vxis the vertice set for graph
xandExis the edge set for graph x. Since the neural networks only take continuous values as
input, we also have a function hto encode each vertex into a vector h:V→RD. The design of
the encoding function depends on the methods. For example, hcan be a one-hot encoding layer or
pretrained embeddings given by a protein language model. We use different encoding functions for
antibodies and antigens: hA:VA→RDA, andhB:VB→RDB.
In addition, EA∈ {0,1}|VA|×|VA|andEB∈ {0,1}|VB|×|VB|denote the adjacency matrices for the
antibody and antigen graphs, respectively. In this work, the adjacency matrices are calculated based
on the distance matrix of the residues. Each entry eijdenotes the proximity between residue iand
residue j;eij= 1if the Euclidean distance between any non-hydrogen atoms of residue iand residue
jis less than 4.5Å, and eij= 0 otherwise. The antibody graph GAis constructed by combining
the CDR residues from the heavy and light chains of the antibody, and the antigen graph GBis
constructed by combining the surface residues of the antigen. The antibody and antigen graphs are
disjoint, i.e., VA∩VB=∅.
Figure 1: An example to illustrate interacting residues. The two dashed lines denote the distance
between non-hydrogen atoms from different interacting residues from two different protein chains.
We consider two subtasks based on these inputs.
Epitope Prediction Epitopes are the regions on the antigen surface recognized by antibodies; in
other words, they are a set of antigen residues in contact with the antibody and are determined from
the complex structures using the same distance cutoff of 4.5Åas aforementioned. For a node in the
antigen graph v∈VB, if there exists a node in the antibody graph u∈VAsuch that the distance
between them is less than 4.5Å, then vis an epitope node. Epitope nodes and the remaining nodes in
GBare assigned labels of 1and0, respectively. The first task is then a node classification within the
antigen graph GBgiven the antibody graph GA.
This classification takes into account the structure of the antibody graph, GA, mirroring the specificity
of antibody-antigen binding interactions. Different antibodies can bind to various antigen locations,
3
corresponding to varying subsets of epitope nodes in GB. This question differs from conventional
epitope prediction methods that do not consider the antibody structure and end up predicting the
likelihood of the subset of antigen nodes serving as epitopes, such as ScanNet (Tubiana et al., 2022),
MaSIF (Gainza et al., 2020).
The task is to develop a binary classifier f:VB→ {0,1}that takes both the antibody and antigen
graphs as input and predicts the label for antigen nodes as formulated below:
f(v;GB, GA) =1ifvis an epitope ;
0otherwise .(1)
Bipartite Link Prediction The second task takes it further by predicting concrete interactions
between nodes in GAandGB, resulting in a bipartite graph that represents these antibody-antigen
interactions. Moreover, this helps attribute the model performance to specific interactions at the
molecular level and provide more interpretability. Accurately predicting these interactions is critical
for understanding the binding mechanisms and for guiding antibody engineering.
We model the antibody-antigen interaction as a bipartite graph:
Km,n= (VA, VB, E)
where m=|VA|andn=|VB|denote the number of nodes in the two graphs, respectively, and
Edenotes all possible inter-graph links. In this bipartite graph, a node from the antibody graph
is connected to each node in the antigen graph via an edge e∈E. The task is then to predict the
label of each bipartite edge. If the residues of a pair of nodes are located within 4.5Åof each other,
referred to as in contact , the edge is labeled as 1; otherwise, 0. For any pair of nodes, denoted as
(va, vb)∀va∈VA, vb∈VB, the binary classifier g:Km,n→ {0,1}is formulated as below:
g(va, vb;Km,n) =1ifvaandvbare in contact
0otherwise .(2)
4 AsEP dataset
We present our dataset AsEP of filtered, cleaned and processed antibody-antigen complex structures.
It is the largest collection of antibody-antigen complex structures to our knowledge. Antibodies
are composed of two heavy chains and two light chains, each of which contains a variable domain
(areas of high sequence variability) composed of a variable heavy (VH) and a variable light (VL)
domain responsible for antigen recognition and binding (Chothia & Lesk, 1987). These domains
have complementarity-determining regions (CDR, Figure 2 top blue, yellow, and red regions), which
are the primary parts of antibodies responsible for antigen recognition and binding.
4.1 Antibody-antigen complexes
We sourced our initial dataset from the Antibody Database (AbDb) (Ferdous & Martin, 2018), dated
2022/09/26, which contains 11,767antibody files originally collected from the Protein Data Bank
(PDB) (Berman et al., 2003). We extracted conventional antibody-antigen complexes that have a
VH and a VL domain with a single-chain protein antigen, and there are no unresolved CDR residues
due to experimental errors, yielding 4,081antibody-antigen complexes. To ensure data balance,
we removed identical complexes using an adapted version of the method described in Krawczyk
et al. (2014). We clustered the complexes by antibody heavy and light chains followed by antigen
sequences using MMseqs2 (Steinegger & Söding, 2017). We retained only one representative complex
for each unique cluster, leading to a refined dataset of 1,725unique complexes. Two additional
complexes were manually removed; CDR residues in the complex 6jmr_1P are unknown (labeled as
‘UNK’) and it is thus impossible to build graph representations upon this complex; 7sgm_0P was also
removed because of non-canonical residues in its CDR loops. The final dataset consists of 1,723
antibody-antigen complexes. For detailed setup and processing steps, please refer to Appendix A.3.
4
Figure 2: Graph visualization of an antibody-antigen complex. Top: the molecular structure of an
antibody complexed with the receptor binding domain of SARS-Cov-2 virus (PDB code: 7KFW), the
antigen. Spheres indicate the alpha carbon atoms of each amino acid. Color scheme: the antigen is
colored in magenta, the framework region of the heavy and light chains is colored in green and cyan
and CDR 1-3 loops are colored in blue, yellow, and red, respectively. Bottom : the corresponding
graph. Green vertices are antibody CDR residues and pink vertices are antigen surface residues.
4.2 Convert antibody-antigen complexes to graphs
These 1,723files were then converted into graph representations, which are used as input for WALLE.
In these graphs, each protein residue is modeled as a vertex. Edges are drawn between pairs of
residues if any of their non-hydrogen atoms are within 4.5Åof each other, adhering to the same
distance criterion used in PECAN (Pittala & Bailey-Kellogg, 2020).
Exclude buried residues In order to utilize structural information effectively, we focused on surface
residues, as only these can interact with another protein. Consequently, we excluded buried residues,
those with a solvent-accessible surface area of zero, from the antigen graphs. The solvent-accessible
surface areas were calculated using DSSP (Kabsch & Sander, 1983) via Graphein (Jamasb et al.,
2021). It is important to note that the number of interface nodes are much smaller than the number of
non-interface nodes in the antigen, making the classification task more challenging.
Exclude non-CDR residues We also excluded non-CDR residues from the antibody graph, as these
are typically not involved in antigen recognition and binding. This is in line with the approach
adopted by PECAN (Pittala & Bailey-Kellogg, 2020) and EPMP (Vecchio et al., 2021). Figure 2
provides a visualization of the processed graphs.
Node embeddings To leverage the state-of-the-art protein language models, we generated node em-
beddings for each residue in the antibody and antigen graphs using AntiBERTy (Ruffolo et al., 2021)
(via IgFold (Ruffolo et al., 2023) package) and ESM2 (Lin et al., 2022) ( esm2_t12_35M_UR50D )
models, respectively. In our dataset interface package, we also provide a simple embedding method
using one-hot encoding for amino acid residues. Other node embedding methods can be easily
incorporated into our dataset interface.
4.3 Dataset split
We propose two types of dataset split settings. The first is a random split based on the ratio of epitope
to antigen surface residues,#epitope nodes
#antigen nodes; the second is a more challenging setting where we split the
5
dataset by epitope groups. The first setting is straightforward and used by previous methods. The
second setting is more challenging because it requires the model to generalize to unseen epitope
groups.
Split by epitope to antigen surface ratio As aforementioned, the number of non-interface nodes
in the antigen graph is much larger than the number of interface nodes. While epitopes usually
have a limited number of residues, typically around 14.6±4.9amino acids (Reis et al., 2022), the
antigen surface may extend to several hundred or more residues. The complexity of the classification
task therefore increases with the antigen surface size. To ensure similar complexity among train,
validation, and test sets, we stratified the dataset to include a similar distribution of epitope to non-
epitope nodes in each set. Table S3 shows the distribution of epitope-to-antigen surface ratios in each
set. This led to 1383 antibody-antigen complexes for the training set and 170complexes each for the
validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-ratio.csv .
Split by epitope groups This is motivated by the fact that antibodies are highly diverse in the CDR
loops and by changing the CDR sequences it is possible to engineer novel antibodies to bind different
sites on the same antigen. This was previously observed in the EpiPred dataset where Krawczyk et al.
(2014) tested the specificity of their method on five antibodies associated with three epitopes on the
same antigen, hen egg white lysozyme.
We inlcude 641unique antigens and 973epitope groups in our dataset. We include multi-epitope
antigens. For example, there are 64distinct antibodies that bind to coronavirus spike protein.
We can see that different antibodies bind to different locations on the same antigen. Details of
all epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv . We then
split the dataset into train, validation, and test sets such that the epitopes in the test set are not
found in either train or validation sets. We followed an 80%/10%/10% split for the number of
complexes in each set. This resulted in 1383 complexes for the training set and 170complexes for
the validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-group.csv .
User-friendly Dataset Interface We implemented a Python package interface for our dataset using
PyTorch Geometric (Fey & Lenssen, 2019). Users can load the dataset as a PyTorch Geometric
dataset object and use it with PyTorch Geometric’s data loaders. We provide an option to load node
embeddings derived from AntiBERTy and ESM2 or simply one-hot embeddings. Each data object in
the dataset is a pair of antibody and antigen graphs; both node- and edge-level labels are provided,
and the node-level labels are used for the epitope prediction task.
5 WALLE: a graph-based method for epitope prediction
Alongside our dataset interface, we also provide a graph-based model named WALLE. It takes as
input a pair of antibody and antigen graphs, constructed as detailed above for the AsEP dataset, and
makes node- and edge-level predictions.
Graph Modules The architecture of WALLE incorporates graph modules that process the input
graphs of antibody and antigen structures, as depicted in Figure 3). Inspired by PECAN and EPMP,
our model treats the antibody and antigen graphs separately, with distinct pathways for each. The
antibody graph is represented by node embeddings XAwith a shape of (M,512) and an adjacency
matrix EA, while the antigen graph is described by node embeddings XBwith a shape of (N,480)
and its corresponding adjacency matrix EB. The embedding sizes are consistent with AntiBERTy
and ESM2 ( esm2_t12_35M_UR50D ).
Both antibody and antigen graph nodes are first projected into the dimensionality of 128using fully
connected layers. The resulting embeddings are then passed through two Graph Convolutional
Network (GCN) modules consecutively to refine the features and yield updated node embeddings X′
A
andX′
Bwith a reduced dimensionality of (M,64). The output from the first GCN layer is passed
through a ReLU activate function. Outputs from the second GCN layer are directly fed into the
Decoder module. These GCNs operate independently, each with its own parameters, ensuring that
the learned representations are specific to the antibody or the antigen.
6
GCN (128) GCN (128)
DecoderGCN (64) GCN (64)
Antigen Graph
Node
Edge index Antibody CDR Graph
Node
Edge index Preprocessing
AntibodyPreprocessing
AntigenAbAg
complex
structureFigure 3: A schematic of the preprocessing step that turns an input antibody-antigen complex structure
into a graph pair and the model architecture of WALLE.
The use of separate GCN modules for the antibody and antigen allows for the capture of unique
structural and functional characteristics pertinent to each molecule before any interaction analysis.
This design choice aligns with the understanding that the antibody and antigen have distinct roles in
their interactions and their molecular features should be processed separately.
Decoder
We used a simple decoder to predict the binary labels of edges between the antibody and antigen
graphs, which takes a pair of node embeddings output by the graph modules as input and predicts the
probability of each edge. An edge is assigned a binary label of 1if the predicted probability is greater
than0.5or0otherwise. This is shown as the Decoder module in Figure 3. For the epitope prediction
task, we convert edge-level predictions to node-level by summing the predicted probabilities of all
edges connected to an antigen node; we assign the antigen node a label of 1if the number of connected
edges is greater than a threshold or 0otherwise. The threshold is treated as a hyperparameter and is
optimized in the experiments.
Implementation
We used PyTorch Geometric (Fey & Lenssen, 2019) framework to build our model. The graph
modules are implemented using the GCNConv module from PyTorch Geometric. We trained the
model to minimize a loss function consisting of two parts: a weighted binary cross-entropy loss
for the bipartite graph link reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph. We used the same set of hyperparameters and loss functions for both
dataset settings. The loss function and hyperparameters are described in detail in Appendix A.6.
Experiment results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For | future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 | Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 | Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 | Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1). | References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A | Appendix A.1.
2
Two Complementary Surveys are notable:
Zhao et al. (2024) benchmarked docking methods like ZDOCK (Pierce et al., 2011), ClusPro (Kozakov
et al., 2017), and HDOCK (Yan et al., 2017), and Alphafold-Multimer (Evans et al., 2022) on a set of
112antibody-antigen complexes. They showed that all docking methods gave a success rate of 8.0%
at most if using the top 5 decoys; Alphafold-Multimer showed a better performance with a 15.3%
success rate.
Cia et al. (2023) focused on epitope prediction using a dataset of 268complexes, defining epitope
residues as having at least a 5%change in relative solvent accessibility upon complex formation. They
benchmarked various methods, finding existing methods insufficient for accurate epitope prediction.
3 Problem Formulation
Antibody-antigen interaction is important for analyzing protein structures. The problem can be
formulated as a bipartite graph link prediction task. The inputs are two disjoint graphs, an antibody
graph GA= (VA, EA)and an antigen graph GB= (VB, EB), where Vxis the vertice set for graph
xandExis the edge set for graph x. Since the neural networks only take continuous values as
input, we also have a function hto encode each vertex into a vector h:V→RD. The design of
the encoding function depends on the methods. For example, hcan be a one-hot encoding layer or
pretrained embeddings given by a protein language model. We use different encoding functions for
antibodies and antigens: hA:VA→RDA, andhB:VB→RDB.
In addition, EA∈ {0,1}|VA|×|VA|andEB∈ {0,1}|VB|×|VB|denote the adjacency matrices for the
antibody and antigen graphs, respectively. In this work, the adjacency matrices are calculated based
on the distance matrix of the residues. Each entry eijdenotes the proximity between residue iand
residue j;eij= 1if the Euclidean distance between any non-hydrogen atoms of residue iand residue
jis less than 4.5Å, and eij= 0 otherwise. The antibody graph GAis constructed by combining
the CDR residues from the heavy and light chains of the antibody, and the antigen graph GBis
constructed by combining the surface residues of the antigen. The antibody and antigen graphs are
disjoint, i.e., VA∩VB=∅.
Figure 1: An example to illustrate interacting residues. The two dashed lines denote the distance
between non-hydrogen atoms from different interacting residues from two different protein chains.
We consider two subtasks based on these inputs.
Epitope Prediction Epitopes are the regions on the antigen surface recognized by antibodies; in
other words, they are a set of antigen residues in contact with the antibody and are determined from
the complex structures using the same distance cutoff of 4.5Åas aforementioned. For a node in the
antigen graph v∈VB, if there exists a node in the antibody graph u∈VAsuch that the distance
between them is less than 4.5Å, then vis an epitope node. Epitope nodes and the remaining nodes in
GBare assigned labels of 1and0, respectively. The first task is then a node classification within the
antigen graph GBgiven the antibody graph GA.
This classification takes into account the structure of the antibody graph, GA, mirroring the specificity
of antibody-antigen binding interactions. Different antibodies can bind to various antigen locations,
3
corresponding to varying subsets of epitope nodes in GB. This question differs from conventional
epitope prediction methods that do not consider the antibody structure and end up predicting the
likelihood of the subset of antigen nodes serving as epitopes, such as ScanNet (Tubiana et al., 2022),
MaSIF (Gainza et al., 2020).
The task is to develop a binary classifier f:VB→ {0,1}that takes both the antibody and antigen
graphs as input and predicts the label for antigen nodes as formulated below:
f(v;GB, GA) =1ifvis an epitope ;
0otherwise .(1)
Bipartite Link Prediction The second task takes it further by predicting concrete interactions
between nodes in GAandGB, resulting in a bipartite graph that represents these antibody-antigen
interactions. Moreover, this helps attribute the model performance to specific interactions at the
molecular level and provide more interpretability. Accurately predicting these interactions is critical
for understanding the binding mechanisms and for guiding antibody engineering.
We model the antibody-antigen interaction as a bipartite graph:
Km,n= (VA, VB, E)
where m=|VA|andn=|VB|denote the number of nodes in the two graphs, respectively, and
Edenotes all possible inter-graph links. In this bipartite graph, a node from the antibody graph
is connected to each node in the antigen graph via an edge e∈E. The task is then to predict the
label of each bipartite edge. If the residues of a pair of nodes are located within 4.5Åof each other,
referred to as in contact , the edge is labeled as 1; otherwise, 0. For any pair of nodes, denoted as
(va, vb)∀va∈VA, vb∈VB, the binary classifier g:Km,n→ {0,1}is formulated as below:
g(va, vb;Km,n) =1ifvaandvbare in contact
0otherwise .(2)
4 AsEP dataset
We present our dataset AsEP of filtered, cleaned and processed antibody-antigen complex structures.
It is the largest collection of antibody-antigen complex structures to our knowledge. Antibodies
are composed of two heavy chains and two light chains, each of which contains a variable domain
(areas of high sequence variability) composed of a variable heavy (VH) and a variable light (VL)
domain responsible for antigen recognition and binding (Chothia & Lesk, 1987). These domains
have complementarity-determining regions (CDR, Figure 2 top blue, yellow, and red regions), which
are the primary parts of antibodies responsible for antigen recognition and binding.
4.1 Antibody-antigen complexes
We sourced our initial dataset from the Antibody Database (AbDb) (Ferdous & Martin, 2018), dated
2022/09/26, which contains 11,767antibody files originally collected from the Protein Data Bank
(PDB) (Berman et al., 2003). We extracted conventional antibody-antigen complexes that have a
VH and a VL domain with a single-chain protein antigen, and there are no unresolved CDR residues
due to experimental errors, yielding 4,081antibody-antigen complexes. To ensure data balance,
we removed identical complexes using an adapted version of the method described in Krawczyk
et al. (2014). We clustered the complexes by antibody heavy and light chains followed by antigen
sequences using MMseqs2 (Steinegger & Söding, 2017). We retained only one representative complex
for each unique cluster, leading to a refined dataset of 1,725unique complexes. Two additional
complexes were manually removed; CDR residues in the complex 6jmr_1P are unknown (labeled as
‘UNK’) and it is thus impossible to build graph representations upon this complex; 7sgm_0P was also
removed because of non-canonical residues in its CDR loops. The final dataset consists of 1,723
antibody-antigen complexes. For detailed setup and processing steps, please refer to Appendix A.3.
4
Figure 2: Graph visualization of an antibody-antigen complex. Top: the molecular structure of an
antibody complexed with the receptor binding domain of SARS-Cov-2 virus (PDB code: 7KFW), the
antigen. Spheres indicate the alpha carbon atoms of each amino acid. Color scheme: the antigen is
colored in magenta, the framework region of the heavy and light chains is colored in green and cyan
and CDR 1-3 loops are colored in blue, yellow, and red, respectively. Bottom : the corresponding
graph. Green vertices are antibody CDR residues and pink vertices are antigen surface residues.
4.2 Convert antibody-antigen complexes to graphs
These 1,723files were then converted into graph representations, which are used as input for WALLE.
In these graphs, each protein residue is modeled as a vertex. Edges are drawn between pairs of
residues if any of their non-hydrogen atoms are within 4.5Åof each other, adhering to the same
distance criterion used in PECAN (Pittala & Bailey-Kellogg, 2020).
Exclude buried residues In order to utilize structural information effectively, we focused on surface
residues, as only these can interact with another protein. Consequently, we excluded buried residues,
those with a solvent-accessible surface area of zero, from the antigen graphs. The solvent-accessible
surface areas were calculated using DSSP (Kabsch & Sander, 1983) via Graphein (Jamasb et al.,
2021). It is important to note that the number of interface nodes are much smaller than the number of
non-interface nodes in the antigen, making the classification task more challenging.
Exclude non-CDR residues We also excluded non-CDR residues from the antibody graph, as these
are typically not involved in antigen recognition and binding. This is in line with the approach
adopted by PECAN (Pittala & Bailey-Kellogg, 2020) and EPMP (Vecchio et al., 2021). Figure 2
provides a visualization of the processed graphs.
Node embeddings To leverage the state-of-the-art protein language models, we generated node em-
beddings for each residue in the antibody and antigen graphs using AntiBERTy (Ruffolo et al., 2021)
(via IgFold (Ruffolo et al., 2023) package) and ESM2 (Lin et al., 2022) ( esm2_t12_35M_UR50D )
models, respectively. In our dataset interface package, we also provide a simple embedding method
using one-hot encoding for amino acid residues. Other node embedding methods can be easily
incorporated into our dataset interface.
4.3 Dataset split
We propose two types of dataset split settings. The first is a random split based on the ratio of epitope
to antigen surface residues,#epitope nodes
#antigen nodes; the second is a more challenging setting where we split the
5
dataset by epitope groups. The first setting is straightforward and used by previous methods. The
second setting is more challenging because it requires the model to generalize to unseen epitope
groups.
Split by epitope to antigen surface ratio As aforementioned, the number of non-interface nodes
in the antigen graph is much larger than the number of interface nodes. While epitopes usually
have a limited number of residues, typically around 14.6±4.9amino acids (Reis et al., 2022), the
antigen surface may extend to several hundred or more residues. The complexity of the classification
task therefore increases with the antigen surface size. To ensure similar complexity among train,
validation, and test sets, we stratified the dataset to include a similar distribution of epitope to non-
epitope nodes in each set. Table S3 shows the distribution of epitope-to-antigen surface ratios in each
set. This led to 1383 antibody-antigen complexes for the training set and 170complexes each for the
validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-ratio.csv .
Split by epitope groups This is motivated by the fact that antibodies are highly diverse in the CDR
loops and by changing the CDR sequences it is possible to engineer novel antibodies to bind different
sites on the same antigen. This was previously observed in the EpiPred dataset where Krawczyk et al.
(2014) tested the specificity of their method on five antibodies associated with three epitopes on the
same antigen, hen egg white lysozyme.
We inlcude 641unique antigens and 973epitope groups in our dataset. We include multi-epitope
antigens. For example, there are 64distinct antibodies that bind to coronavirus spike protein.
We can see that different antibodies bind to different locations on the same antigen. Details of
all epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv . We then
split the dataset into train, validation, and test sets such that the epitopes in the test set are not
found in either train or validation sets. We followed an 80%/10%/10% split for the number of
complexes in each set. This resulted in 1383 complexes for the training set and 170complexes for
the validation and test sets. The list of complexes in each set is provided in the Supplementary Table
SI-split-epitope-group.csv .
User-friendly Dataset Interface We implemented a Python package interface for our dataset using
PyTorch Geometric (Fey & Lenssen, 2019). Users can load the dataset as a PyTorch Geometric
dataset object and use it with PyTorch Geometric’s data loaders. We provide an option to load node
embeddings derived from AntiBERTy and ESM2 or simply one-hot embeddings. Each data object in
the dataset is a pair of antibody and antigen graphs; both node- and edge-level labels are provided,
and the node-level labels are used for the epitope prediction task.
5 WALLE: a graph-based method for epitope prediction
Alongside our dataset interface, we also provide a graph-based model named WALLE. It takes as
input a pair of antibody and antigen graphs, constructed as detailed above for the AsEP dataset, and
makes node- and edge-level predictions.
Graph Modules The architecture of WALLE incorporates graph modules that process the input
graphs of antibody and antigen structures, as depicted in Figure 3). Inspired by PECAN and EPMP,
our model treats the antibody and antigen graphs separately, with distinct pathways for each. The
antibody graph is represented by node embeddings XAwith a shape of (M,512) and an adjacency
matrix EA, while the antigen graph is described by node embeddings XBwith a shape of (N,480)
and its corresponding adjacency matrix EB. The embedding sizes are consistent with AntiBERTy
and ESM2 ( esm2_t12_35M_UR50D ).
Both antibody and antigen graph nodes are first projected into the dimensionality of 128using fully
connected layers. The resulting embeddings are then passed through two Graph Convolutional
Network (GCN) modules consecutively to refine the features and yield updated node embeddings X′
A
andX′
Bwith a reduced dimensionality of (M,64). The output from the first GCN layer is passed
through a ReLU activate function. Outputs from the second GCN layer are directly fed into the
Decoder module. These GCNs operate independently, each with its own parameters, ensuring that
the learned representations are specific to the antibody or the antigen.
6
GCN (128) GCN (128)
DecoderGCN (64) GCN (64)
Antigen Graph
Node
Edge index Antibody CDR Graph
Node
Edge index Preprocessing
AntibodyPreprocessing
AntigenAbAg
complex
structureFigure 3: A schematic of the preprocessing step that turns an input antibody-antigen complex structure
into a graph pair and the model architecture of WALLE.
The use of separate GCN modules for the antibody and antigen allows for the capture of unique
structural and functional characteristics pertinent to each molecule before any interaction analysis.
This design choice aligns with the understanding that the antibody and antigen have distinct roles in
their interactions and their molecular features should be processed separately.
Decoder
We used a simple decoder to predict the binary labels of edges between the antibody and antigen
graphs, which takes a pair of node embeddings output by the graph modules as input and predicts the
probability of each edge. An edge is assigned a binary label of 1if the predicted probability is greater
than0.5or0otherwise. This is shown as the Decoder module in Figure 3. For the epitope prediction
task, we convert edge-level predictions to node-level by summing the predicted probabilities of all
edges connected to an antigen node; we assign the antigen node a label of 1if the number of connected
edges is greater than a threshold or 0otherwise. The threshold is treated as a hyperparameter and is
optimized in the experiments.
Implementation
We used PyTorch Geometric (Fey & Lenssen, 2019) framework to build our model. The graph
modules are implemented using the GCNConv module from PyTorch Geometric. We trained the
model to minimize a loss function consisting of two parts: a weighted binary cross-entropy loss
for the bipartite graph link reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph. We used the same set of hyperparameters and loss functions for both
dataset settings. The loss function and hyperparameters are described in detail in Appendix A.6.
Experiment results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1).
References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A Appendix-A
A.1 Related work
Comparison of Previous Datasets We would like to highlight our dataset, AsEP, is the largest
curated AbAg benchmarking dataset to date. Existing ones either focus on general protein-protein
complexes designed to develop general docking methods or are way smaller than AsEP if designed
for AbAg interaction research. We summarized the sizes of existing datasets in the following table.
Table S1: Comparison of Dataset Sizes Across Different Methods
Method Dataset Size
WALLE (AsEP) 1723 AbAg complexes
Gao et al. 2022 Gao et al. (2022) 258 AbAg complexes
CSM-AB Myung et al. (2021) 472 AbAg complexes
SAGERank Sun et al. (2023) 287 AbAg complexes
Bepipred3.0 Clifford et al. (2022) 582 AbAg complexes
SCEptRe Mahajan et al. (2019) is a related dataset that keeps a weekly updated collection of 3D
complexes of epitope and receptor pairs, for example, antibody-antigen, TCR-pMHC, and MHC-
ligand complexes derived from the Immune Epitope Database (IEDB). Our approach for clustering
antibody-antigen complexes regarding their epitopes is similar to theirs, with the difference in the
clustering strategy. We cluster by antigen, then epitope group, and we allow mutated amino acids
in the same epitope region because we turn the epitope sites into columns in the multiple sequence
alignment. In contrast, SCEptRe clusters by antibody and then compares epitope similarity by
epitope conformation using atom-pair distances via PocketMatch Yeturu & Chandra (2008), which is
beneficial for comparing the function of various paratopes but is less suitable for our task of predicting
epitope residues.
Sequence-based epitope predictor We also tested purely sequence-based epitope prediction tool,
for example, Bepipred3.0 Clifford et al. (2022) on our dataset. Bepipred3.0 uses ESM2 model,
esm2_t33_650M_UR50D to generate sequence embeddings and was trained on a smaller dataset
of 582 antibody-antigen structures and evaluated on 15 antibody-antigen complexes. The authors
provided a relatively larger evaluation of linear B-cell epitopes derived from the Immune Epitope
Database and reported an AUC-ROC of 0.693on the top 10% of the predicted epitopes. We tested
Bepipred3.0 on our dataset and found its performance degenerates significantly, as shown in the table
below. This is not surprising because linear epitopes are consecutive positions in an antigen sequence,
and this task fits better with language model design. Additionally, as pointed out by the authors,
approximately 90% of epitopes (B-cell) fall into the conformational category Clifford et al. (2022),
which highlights the importance of the present benchmark dataset composed of conformational
epitopes derived from filtered antibody-antigen structures. We believe these results underline the
findings in our paper, showing that large language models alone, even if specialized for antibody-
antigen interactions, do not encompass all the relevant information needed for epitope prediction.
13
Confidence Threshold Top 10% Top 30% Top 50% Top 70% Top 90%
AUC 0.693392 0.693392 0.693392 0.693392 0.693392
Balanced Accuracy 0.573132 0.636365 0.638755 0.604556 0.542274
MCC 0.109817 0.140183 0.134689 0.113372 0.071876
Precision-Recall AUC 0.176429 0.176429 0.176429 0.176429 0.176429
Accuracy 0.850178 0.701202 0.536947 0.362489 0.179051
Precision 0.169202 0.141361 0.120547 0.104286 0.090441
Recall 0.236760 0.553204 0.756607 0.892628 0.977723
F1-Score 0.173370 0.208366 0.197153 0.179294 0.160151
Table S2: Bepipred3.0 results for the presented AsEP dataset. The distance cutoff was changed to
4.0Å, as this is the threshold used by Bepipred3.0. Results are shown for five confidence thresholds
as described in the BepiPred-3.0 paper. Across all stringency settings and metrics, Bepipred scored
lower than Walle. Furthermore, it is possible that some of the structures within the dataset are
contained within the Bepipred3.0 dataset, artificially increasing scores.
A.2 Evaluation
In this work, we focus on the epitope prediction task. We evaluate the performance of each method
using consistent metrics. Matthew’s Correlation Coefficient (MCC) is highly recommended for binary
classification assessments Matthews (1975) and is especially advocated for its ability to provide equal
weighting to all four values in the confusion matrix, making it a more informative metric about the
classifier’s performance at a given threshold than other metrics Chicco & Jurman (2020, 2023). We
encourage the community to adopt MCC for the epitope prediction task as it takes into account true
and false positives, as well as true and false negatives, offering a comprehensive measure of the
performance. It is considered superior to the AUC-ROC, which is evaluated over all thresholds. For
consistency, we also included Precision and Recall from prior studies EpiPred Krawczyk et al. (2014)
and PECAN Pittala & Bailey-Kellogg (2020), and we added Area Under the Receiver Operating
Characteristic Curve (AUC-ROC) and F1 score, both are typical binary classification metrics. For
methods that predict antibody-antigen complex structures, we determine the epitopes using the same
distance criterion as aforementioned.
A.3 Steps to build antibody-antigen complex dataset
We sourced our initial dataset from AbDb (version dated September 26, 2022), containing 11,767
antibody files originally collected from the Protein Data Bank (PDB). We collected complexes
numbered in Martin scheme Raghavan & Martin (2008) and used AbM CDR definition Martin et al.
(1991) to identify CDR residues from the heavy and light chains of antibodies.
We extracted antibody-antigen complexes that met the following criteria: (1) both VH and VL
domains are present in the antibody; (2) the antigen is a single-chain protein consisting of at least 50
amino acids; and (3) there are no unresolved CDR residues, yielding 4,081 files.
To deduplicate complexes, we used MMseqs2 Steinegger & Söding (2017) to cluster the complexes
by heavy and light chains in antibodies and antigen sequences. We used the easy-linclust mode with
the–cov-mode 0 option to cluster sequences; we used the default setting for coverage of aligned
cutoff at 80%; we used different –min-seq-id cutoffs for antibodies and antigens because the antibody
framework regions are more conserved than the CDR regions. We cluster heavy and light chains at
–min-seq-id cutoff of 100% and70%, respectively. We retained only one representative file for each
unique set of identifiers, leading to a refined dataset of 1,725 files.
Two additional files were manually removed. File 6jmr_1P was removed because its CDR residues
are masked with ‘UNK’ labels and the residue identities are unknown; file 7sgm_0P was removed
because of a non-canonical residue ‘DV7’ in its CDR-L3 loop.
The final dataset consists of 1,723 antibody-antigen complexes.
14
A.4 Pipeline to build graph dataset from AbDb
Prepare Graph Dataset
Raw Structure Files
AbDb Complex
antigenOriginal PDB filePDB id
AbDb PDB
Y es
[U, F]Coordinates, Sequences
Antigen Structure
Atom
Chain
ResidueSEQRES (U) ATMSEQ (V)
len(seq) > thr Processing Modules
Calculate
ASA
(DSSP)Calculate
distance
matrix Residue
CheckingSequence
AlignmentSequence
Embedding
(ESM)Intermediate Data
ATMSEQ2NODES
Mask (V -> N)SEQRES2A TMSEQ
Mask (U -> V)residue-residue
distance matrix
(V, V)Pre Node
Labels (V , 1)MasksApply Mask I
(V --> N)Apply Mask I
(V --> N)Apply Mask I & II
(U --> V --> N)[V, ] [V, V]Output Graph
Label
(N, 1)Edge
(2, E)Node
Embeddings
(N, C)
Figure S1: Pipeline to convert an antibody-antigen complex structure into a graph representation.
•Row 1 : given an AbAg complex PDB ID, retrieve ‘AbAg complex’ from AbDb and ‘raw
structure’ file from PDB as input, ‘AbDb complex antigen’ and ‘Original PDB file’ in the
top lane.
•Row 2 : They are then parsed as hierarchical coordinates (Antigen Structure), and extract
ATMSEQ and SEQRES sequences.
•Row 3 : these are then passed to a set of in-house modules for calculating solvent access
surface area (ASA), distance matrix, and filtering out problematic residues, which generates
an ATMSEQ2NODES mask. The sequence alignment module aligns ATMSEQ with
SEQRES sequences to generate a mask mapping from SEQRES to ATMSEQ. The
Sequence Embedding module passes SEQERS through the ESM module to generate
embeddings. ESM requires input sequence length and therefore filters out sequences longer
than 1021 amino acids.
•Row 4 : holds intermediate data that we apply masks to generate graph data in Row 5 .
•Row 6 : Apply the masks to map SEQRES node embeddings to nodes in the graphs and
calculate the edges between the graph nodes.
U,VandNdenote the number of residues in the SEQRES sequence, ATMSEQ sequence and the
graph, respectively. thr(at 50 residues) is the cutoff for antigen SEQRES length. We only include
antigen sequences with lengths of at least 50 residues. SEQRES andATMSEQ are two different
sequence representations of a protein structure. SEQRES is the sequence of residues in the protein
chain as defined in the header section of a PDB file, and it is the complete sequence of the protein
chain. ATMSEQ is the sequence of residues in the protein chain as defined in the ATOM section of a
PDB file. In other words, it is read from the structure, and any residues in a PDB file are not resolved
due to experimental issues that will be missing in the ATMSEQ sequence. Since we are building
graph representations using structures, we used ATMSEQ . However, the input to the language models
15
require a complete sequence, therefore we used SEQRES to generate node embeddings, and mapped
the node embeddings to the graph nodes. We performed two pairwise sequence alignments to map
such embeddings to graph vertices for a protein chain with Clustal Omega Sievers et al. (2011). We
first align the SEQRES sequence with the atom sequence (residues collected from the ATOM records
in a PDB file) and assign residue embeddings to matched residues. Because we excluded buried
residues from the graph, we aligned the sequence formed by the filtered graph vertices with the atom
sequence to assign residue embeddings to vertices. ASA is the solvent-accessible surface area of a
residue. If a residue has an ASA value of zero, it is considered buried and will be removed from the
graph.
A.5 Dataset split
Table S3: Distribution of epitope to antigen surface nodes in each set.
Epi/Surf Training Validation/Test
0, 5% 320 (23% ) 40 (24%)
5% , 10% 483 (35% ) 60 (35%)
10%, 15% 305 (22% ) 38 (22%)
15%, 20% 193 (14% ) 24 (14%)
20%, 25% 53 (4% ) 6 (4% )
25%, 30% 19 (1% ) 2 (1% )
30%, 35% 8 (0.6%) 0 (- )
35%, 40% 2 (0.1%) 0 (- )
sum 1383 170
A.6 Implementation details
Exploratory Data Analysis We performed exploratory data analysis on the training dataset to
understand the distribution of the number of residue-residue contacts in the antibody-antigen interface.
We found that the number of contacts is approximately normally distributed with a mean of 43.42
and a standard deviation of 11.22 (Figure S2). We used this information to set the regularizer in the
loss function to penalize the model for predicting too many or too few positive edges.
0 20 40 60 80 100
Number of contacts0.0000.0050.0100.0150.0200.0250.0300.035Density
Mean: 43.42 Median: 44.00
HDI Left: 34.00 HDI Right: 49.00Number of contacts (bipartite graph edges) per AbAg complex
Mean
Median
50.0% HDI
Fitted Normal
Distribution
( = 43.42, = 11.22)
Figure S2: Blue line: distribution of the number of residue-residue contacts in antibody-antigen
interface across the dataset with a mean and median of 43.27 and 43.00, respectively. Red line: fitted
normal distribution with mean and standard deviation of 43.27 and 10.80, respectively.
16
Loss function Our loss function is a weighted sum of two parts: a binary cross-entropy loss for
the bipartite graph linkage reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph.
Loss =Lr+λNX
ˆe−c(3)
Lr=−1
NNX
i=1(wpos·ye·log( ˆye) +wneg·(1−ye)·log(1−ˆye)) (4)
The binary cross-entropy loss Lris weighted by wposandwnegfor positive and negative edges,
respectively. During hyperparameter tuning, we kept wnegfixed at 1.0and tuned wpos.Nis the
total number of edges in the bipartite graph, yedenotes the true label of edge e, and ˆyedenotes the
predicted probability of edge e. The regularizerPNˆe−cis the L1 norm of the difference between
the sum of the predicted probabilities of all edges of the reconstructed bipartite graph and the mean
positive edges in the training set, i.e., cset to 43. This aims to prevent an overly high false positive
rate, given the fact that the number of positive edges is far less than positive edges. The regularizer
weight λis tuned during hyperparameter tuning.
Hyperparameters We carried out hyperparameter search within a predefined space that included:
•Weights for positive edges in bipartite graph reconstruction loss, sampled uniformly between 50
and 150.
•Weights for the sum of bipartite graph positive links , where values were drawn from a log-
uniform distribution spanning 1e−7to1e−4.
•Edge cutoff (x) , defining an epitope node as any antigen node with more than x edges, with x
sampled following a normal distribution with a mean of 3 and a standard deviation of 1.
•Number of graph convolutional layers in the encoder, we tested using 2 and 3 layers.
•Decoder type was varied between two configurations:
–A fully connected layer, equipped with a bias term and a dropout rate of 0.1.
–An inner product decoder.
Computing resources All experiments were performed on a single Linux machine (Ubuntu 22.04)
with one NVIDIA RTX3090 GPU card, and it took on average 3 hours for a single hyper-parameter
sweeping experiment.
A.7 Antibody-antigen complex examples
To compare the epitopes of antibodies in AsEP, we first clustered these complexes by antigen
sequences to group together antibodies targeting the same antigen via MMseqs2 Steinegger & Söding
(2017). Specifically, we ran MMseqs2 on antigen SEQRES sequences and using the following setup:
•easy-linclust mode
•cov-mode set to 0with the default coverage of 80%: this means a sequence is considered a cluster
member if it aligns at least 80% of its length with the cluster representative;
•min-seq-id set to 0.7: this means a sequence is considered a cluster member if it shares at least
70% sequence identity with the cluster representative.
We encourage the reader to refer to the MMseqs2 documentation https://github.com/
soedinglab/mmseqs2/wiki for more details on the parameters used.
We then identify epitopes using a distance cut-off of 4.5 Å. An antigen residue is identified as epitope
if any of its heavy atoms are located within 4.5 Å of any heavy atoms from the antibody.
To compare epitopes of antibodies sharing the same antigen cluster, we aligned the antigen SEQRES
sequences using Clustal Omega Sievers et al. (2011) (download from: http://www.clustal.org/
omega/ ) to obtain a Multiple Sequence Alignment (MSA). Epitopes are mapped to and denoted as
the MSA column indices. The epitope similarity between a pair of epitopes is then calculated as
17
the fraction of identical columns. Two epitopes are identified as identical if they share over 0.7of
identical columns.
Table S4: Antibody-Antigen Complex Examples
(a) Antigen Group Information
abdbid repr size epitope_group
7eam_1P 7sn2_0P 183 0
5kvf_0P 5kvd_0P 9 1
5kvg_0P 5kvd_0P 9 2
(b) CDR Sequences (Heavy Chain)
abdbid H1 H2 H3
7eam_1P GFNIKDTYIH RIDPGDGDTE FYDYVDYGMDY
5kvf_0P GYTFTSSWMH MIHPNSGSTN YYYDYDGMDY
5kvg_0P GYTFTSYGIS VIYPRSGNTY ENYGSVY
(c) CDR Sequences (Light Chain)
abdbid L1 L2 L3
7zf4_1P RASGNIHNYLA NAKTLAD QHFWSTPPWT
7zbu_0P KSSQSLLYSSNQKNYLA WASTRES QQYYTYPYT
7xxl_0P KASQNVGTA V A SASNRYT QQFSSYPYT
(d) Structure Titles
abdbid resolution title repr_title
7zf4_1P 1.4 immune complex of SARS-CoV-2
RBD and cross-neutralizing antibody
7D6SARS-CoV-2 Omicron variant spike
protein in complex with Fab XGv265
7zbu_0P 1.4 Zika specific antibody, ZV-64, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
7xxl_0P 1.4 Zika specific antibody, ZV-67, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
Here we provide three example antibody-antigen complexes from the same antigen group, meaning
the antigen sequences from each member complex share sequence identity of the aligned region at
least 70%. Due to space limitation, we have broken the rows into four parts: Antigen group
information, CDR sequences, and structure titles.
•abdbid : AbDb ID of the group member;
•repr: AbDb ID of the antigen representative;
•size: the number of complexes in the group;
•epitope_group : A categorical identifier of the epitope group the antibody-antigen complex
belongs to;
•H1,H2,H3,L1,L2,L3: CDR sequences of the heavy and light chains;
•resolution : Structure resolution;
•title: Structure title of the member;
•repr_title : Structure title of the antigen representative.
18
A.8 Multi-epitope Antigens
We include 641unique antigens and 973epitope groups in our dataset. Figure S3 shows two examples
of multi-epitope antigens in our dataset, hen egg white lysozyme (Figure S3a) and spike protein
(Figure S3b). Specifically, there are 52and64distinct antibodies in our dataset that bind to hen egg
white lysozyme and spike protein, respectively. For visual clarity, we only show five and sixteen
antibodies in Figure S3a and Figure S3b.
We can see that different antibodies bind to different locations on the same antigen. Details of all
epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv with annotation
provided in Appendix A.7.
(a) Five different antibodies bound to hen egg white lysozyme. Complexes are superimposed on the antigen
structure (magenta). AbDb IDs of the complexes and their color: 1g7i_0P (green), 2yss_0P (cyan), 1dzb_1P
(yellow), 4tsb_0P (orange), 2iff_0P (wheat). Antigens are colored in magenta.
(b) Sixteen different antibodies bound to coronavirus spike protein. Complexes are superimposed on the antigen
structure (magenta) and antibodies are in different colors. AbDb IDs of the complexes: 7k8s_0P, 7m7w_1P,
7d0b_0P, 7dzy_0P, 7ey5_1P, 7jv4_0P, 7k8v_1P, 7kn4_1P, 7lqw_0P, 7n8i_0P, 7q9i_0P, 7rq6_0P, 7s0e_0P, 7upl_1P,
7wk8_0P, 7wpd_0P.
Figure S3: Examples of different antibodies binding to the same antigen.
19
A.9 Metrics definition
MCC =(TP×TN−FP×FN)p
(TP+FP)(TP+FN)(TN+FP)(TN+FN)
Precision =TP
TP+FP
Recall =TP
TP+FN
F1 =2×Precision ×Recall
Precision +Recall
TP: True Positive
FP: False Positive
TN: True Negative
FN: False Negative
A.10 Fine-tuning ESMBind on AsEP
The performance reported in the main text for ESMBind is derived by fine-tuning ESM2 on general
protein binding sites. We performed a further fine-tuning experiment, fine-tuning it on the presented
AsEP dataset and evaluating it on the AsEP test set to enable a more direct comparison of ESMBind
to WALLE. Fine-tuning of ESMBind on AsEP was done using the Low-Rank Adaptation method Hu
et al. (2021).
Table S5: Performance Metrics
Metric Value
MCC 0.103923
Accuracy 0.504478
AUC-ROC 0.584497
Precision 0.128934
Recall 0.707731
F1 0.213829
20
B Appendix: Link prediction baseline
While the majority of existing studies focus on node-level prediction, i.e., predicting which residues
are likely to be the epitope residues, we are interested in predicting the interactions between epitope
and antigen residues. We argue that, on the one hand, this would provide a more comprehensive
understanding of the interaction between epitopes and antigens, and on the other hand, it would be
good in terms of model interpretability. Existing methods for predicting epitope residues are mostly
based on sequence information, which is not directly interpretable in terms of the interaction between
epitopes and antigens.
Our hyperparameter search was conducted within a predefined space as defined in Appendix A.6.
We used the Bayesian optimization strategy implemented through Weights & Biases, targeting the
maximization of the average bipartite graph link Matthew’s Correlation Coefficient (MCC).
The optimization process was managed using the early termination functionality provided by the
Weights & Biases’ Hyperband method Falkner et al. (2018), with a range of minimum to maximum
iterations set from 3 to 27.
The best set of hyperparameters is 2GCNConv layers, a batch size of 32, a weight for positive edges
of54.7, a weight for the sum of positive links at approximately 5.75e−7, and an edge cutoff of 2.38.
The resulting MCC evaluated on the test set was 0.072(standard error: 0.009) for the bipartite graph
link prediction task.
Table S6: Evaluation of WALLE on the bipartite graph link prediction task
Metric Mean (Standard Error)
MCC 0.072 (0.009)
ROC-AUC 0.582 (0.011)
Precision 0.049 (0.008)
Recall 0.167 (0.023)
F1 0.053 (0.007)
21
C Appendix: Ablation Studies
To investigate the impact of different components on WALLE’s performance, we carried out ablation
studies and described them in this section. For each model variant, we performed hyperparameter
tuning and reported the evaluation performance using the model with the best performance on the
validation set.
C.1 Ablation study: replace graph component with linear layers
To investigate whether the graph component within the WALLE framework is essential for its
predictive performance, we conducted an ablation study in which the graph component was replaced
with two linear layers. We refer to the model as ‘WALLE-L’. The first linear layer was followed by a
ReLu activation function. Logits output by the second linear layer were used as input to the decoder.
The rest of the model architecture remained the same.
It differs from the original WALLE model in that the input to the first linear layer is simply the
concatenation of the embeddings of the antibody and antigen nodes, and the linear layers do not
consider the graph structure, i.e., the spatial arrangement of either antibody or antigen residues. The
model was trained using the same hyperparameters as the original WALLE model. The performance
of WALLE-L was evaluated on the test set using the same metrics as the original WALLE model.
C.2 Ablation study: WALLE with simple node encoding
The presented WALLE model utilizes embeddings from large language models, including ESM2 Lin
et al. (2022) or IgFoldRuffolo et al. (2023) for representing amino acid sequences, as these models
are able to capture the sequential and structural information inherent in protein sequences, providing
a rich, context-aware representation of amino acids. To test the effectiveness of such embeddings
in this downstream task, we conducted an ablation study where we replaced the embeddings from
language models with simple node encodings. Specifically, we evaluated the performance of WALLE
when using ‘one-hot’ encoding and ‘BLOSUM62’ encoding for amino acids in both antibody and
antigen sequences.
C.3 Ablation study: WALLE with ESM2 embeddings for both antibodies and antigens
We also investigated whether the choice of language models can impact the predictive performance
of WALLE; we conducted an ablation study to evaluate the performance of WALLE when both
antibodies and antigens are represented using embeddings from the ESM2 language model Lin et al.
(2022) while the original model uses AntiBERTy Ruffolo et al. (2023) for antibodies as it is trained
exclusively on antibody sequences. This also tests whether a language model trained on general
protein sequences can be used for a downstream task like antibody-antigen interaction prediction.
One-hot encoding
One-hot encoding is a method where each residue is represented as a binary vector. Each position in
the vector corresponds to a possible residue type, and the position corresponding to the residue present
is marked with a 1, while all other positions are set to 0. This encoding scheme is straightforward and
does not incorporate any information about the physical or chemical properties of the residues. This
method tests the model’s capability to leverage structural and relational information from the graph
component without any assumptions introduced by more complex encoding schemes.
BLOSUM62 encoding
BLOSUM62 Henikoff & Henikoff (1992) encoding involves using the BLOSUM62 matrix, which
is a substitution matrix used for sequence alignment of proteins. In this encoding, each residue
is represented by its corresponding row in the BLOSUM62 matrix. This method provides a more
nuanced representation of residues, reflecting evolutionary relationships and substitution frequencies.
22
C.4 Hyperparameter tuning
We used the same hyperparameter search space defined in Appendix A.6 and performed a hyperpa-
rameter search as defined in Appendix B for each model variant in the ablation studies. We report the
evaluation performance of the tuned model for each variant in Table S7.
Table S7: Performance of WALLE without graph component and simple node encodings on test set
from dataset split by epitope to antigen surface ratio.
Algorithm Encoding MCC AUCROC Precision Recall F1
WALLE Both 0.2097 (0.0195) 0.6351 (0.0126) 0.2346 (0.0183) 0.4217 (0.0279) 0.2580 (0.0178)
WALLE-L Both 0.1593 (0.0155) 0.6124 (0.0109) 0.1750 (0.0109) 0.4696 (0.0243) 0.2371 (0.0137)
WALLE ESM2 0.1955 (0.0212) 0.6219 (0.0137) 0.2280 (0.0188) 0.4103 (0.0291) 0.2553 (0.0188)
WALLE-L ESM2 0.1445 (0.0138) 0.6100 (0.0097) 0.1598 (0.0102) 0.5355 (0.0216) 0.2266 (0.0125)
WALLE One-hot 0.0968 (0.0094) 0.5830 (0.0076) 0.1185 (0.0052) 0.8923 (0.0118) 0.2026 (0.0081)
WALLE BLOSUM 0.0848 (0.010) 0.5739 (0.0081) 0.1182 (0.0055) 0.8401 (0.0151) 0.1993 (0.0083)
The values in parentheses represent the standard error of the mean; ‘WALLE-L’ refers to WALLE
with the graph component replaced by two linear layers. ‘ESM2’ refers to the embeddings from the
ESM2 language model esm2_t12_35M_UR50D . ‘One-Hot’ refers to one-hot encoding of amino
acids. ‘BLOSUM62’ refers to the BLOSUM62 encoding of amino acids. ‘Both’ refers to embedding
antibodies and antigens using the esm2_t12_35M_UR50D ESM2 model and AntiBERTy (via IgFold)
language model, respectively. The best performing model is highlighted in bold.
We observed that WALLE’s performance with simple node encodings (‘one-hot’ and ‘BLOSUM62’)
is considerably lower than when using advanced embeddings from language models. This indicates
that the embeddings derived from language models capture more nuanced information about the
amino acids, enabling the model to better predict epitope-antigen interactions.
The degenerated performance of WALLE with simple encodings can be attributed to the lack of
contextual information and structural features in these representations. The high recall but low
precision values suggest that the model is unable to distinguish between true and false interactions,
leading to a high number of false positives. This highlights the importance of using meaningful
embeddings that capture the rich structural and sequential information present in protein sequences.
When comparing WALLE with WALLE-L (without the graph components), we observe that the
model’s performance drops considerably when the graph component is replaced with fully connected
linear layers. This indicates that the topological information captured by the graph component also
contributes to the model’s predictive performance.
We also observed that WALLE with ESM2 embeddings for both antibodies and antigens achieved
similar performance to WALLE with AntiBERTy and ESM2 embeddings for antibodies and antigens,
respectively. This suggests that the ESM2 embeddings somehow provide effective information for
both antibodies and antigens without training exclusively on antibody sequences.
D Impact Statement
This work extends to the optimization of antibody drug development, offering a more efficient and
accurate method for predicting where antibodies bind on antigens, a crucial challenge of developing
therapeutic antibodies. The potential impact of this advancement is underscored by the recent
approval of 136 antibody-based drugs in the United States or European Union, with 17 novel
antibody therapeutics approved since January 2023 and 18 more currently under review (Antibody
Society, Antibody therapeutics approved or in regulatory review in the EU or US, https://www.
antibodysociety.org/resources/approved-antibodies/ , 24 January 2024). These figures
show the transformative impact that antibody design innovation can have on transforming the
landscape of therapeutic development, offering new avenues for targeted, effective treatments that
can be developed in a more time- and cost-effective manner. Such advancements hold immense
potential in accelerating the creation of targeted therapies and implicitly support the broader goals of
personalized medicine. Fast-tracking antibody design through in silico epitope prediction can enable
quicker responses to emerging health threats like pandemics or rapidly mutating pathogens. However,
23
in silico predictions should not be blindly trusted and should merely guide and streamline research
and diligent testing, not replace it.
This paper presents work whose goal is to highlight antibody-specific epitope prediction as a major
challenge that has not been widely studied to date, which is presented as a bipartite graph connectivity
prediction task. This research stands out primarily for its development of a novel benchmarking
dataset for antibody-specific epitope prediction - a resource previously unavailable in the scientific
community with the potential to set a new standard in the field.
Existing methods are compared using uniform metrics and a vast room for improvement can be
demonstrated across the board. A novel model is presented, which surpasses its counterparts by
an order of magnitude, outperforming them by a factor of ten, validating its graph-based approach
utilizing antibody and antigen structural information as well as leveraging protein language models.
We provide a foundational framework that invites other researchers to further build upon and refine
this baseline model, which we have demonstrated to be a highly effective approach for this task.
Open availability of the dataset and model facilitates further research and exploration in this domain,
expediting the development of more advanced models. Highlighting types of antibody-antigen
interactions that are disregarded in existing datasets and methods encourages the examination of
shortcoming of current models. The focus on conventional antibodies in this work lays the groundwork
for future exploration into epitope prediction for novel antibodies, such as nanobodies, expanding
upon potential applications.
24 | Supplementary Materials
Dataset Documentation and Intended Uses
We provide a data card for this dataset, DataCard-AsEP.md , which can be downloaded using this
link: https://drive.google.com/file/d/1fc5kFcmUdKhyt3WmS30oLLPgnkyEeUjJ/view?
usp=drive_link
This dataset provides a unified benchmark for researchers to develop new machine-learning-based
methods for the epitope prediction task.
Access to the Dataset
There are two alternative sources where users can download the dataset:
•The dataset can be downloaded using the Python interface provided by our GitHub Reposi-
tory AsEP-dataset. Detailed instructions on how to download the dataset are provided in the
README file. Briefly, after installing the provided Python module, asep , the dataset can
be downloaded by running the following command in the terminal:
download - asep / path /to/ directory AsEP
# For example , to download the dataset to the current
,→directory , run
# download - asep . AsEP
•The dataset and benchmark are provided through Zenodo at https://doi.org/10.5281/
zenodo.11495514 .
• Code and Dataset interface is provided in our GitHub Repository AsEP-dataset athttps:
//github.com/biochunan/AsEP-dataset .
Author Statement
The authors affirm that they bear all responsibility in case of violation of rights, etc., and confirm the
data license. The dataset is licensed under the CC BY 4.0 License ( https://creativecommons.
org/licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License (https://opensource.org/licenses/MIT ).
Hosting, Licensing, and Maintenance Plan
The dataset is hosted on Zenodo, which provides a DOI (10.5281/zenodo.11495514) for the dataset.
It also comes with a Python interface provided in our GitHub Repository, AsEP-dataset at https:
//github.com/biochunan/AsEP-dataset , where users can submit issues and ask questions.
Future releases and updates will be made available through the same channels. As discussed in the
main text, the future plan includes expanding the dataset to include novel types of antibodies, such as
single-domain antibodies, and providing more sophisticated features for graph representations. The
dataset will be maintained by the authors and will be available for a long time.
Links to Access the Dataset and Its Metadata
The dataset, benchmark, and metadata are provided through Zenodo.
25
The Dataset
The dataset is constructed using pytorch-geometric Dataset module. The dataset can be loaded
using the following code:
from asep . data . asepv1_dataset import AsEPv1Evaluator
evaluator = AsEPv1Evaluator ()
# example
torch . manual_seed (0)
y_pred = torch . rand (1000)
y_true = torch . randint (0, 2, (1000 ,) )
input_dict = {’y_pred ’: y_pred , ’y_true ’: y_true }
result_dict = evaluator . eval ( input_dict )
print ( result_dict ) # got {’auc - prc ’: tensor (0.5565) }
We also provide detailed documentation of the dataset content on Zenodo and include a description
below:
•asepv1-AbDb-IDs.txt : A text file containing the AbDb identifiers of the 1723 antibody-
antigen pairs in the dataset.
•asepv1_interim_graphs.tar.gz : Contains 1723 .ptfiles, where each file is a dictio-
nary with structured data:
abdbid A string representing the antibody AbDb identifier.
seqres A dictionary containing:
abAn OrderedDict mapping string chain labels HandLto their corresponding se-
quence strings, representing heavy and light chains respectively.
agA dictionary mapping string chain labels to their corresponding sequence strings.
mapping Includes:
abContains:
seqres2cdr A binary numpy array indicating the CDR positions in the antibody
sequence.
agContains:
seqres2surf A binary numpy array indicating the surface residues in the antigen
sequence.
seqres2epitope A binary numpy array indicating the epitope residues in the
antigen sequence.
embedding Comprises:
abIncludes embeddings computed using the AntiBERTy model and ESM2 model for
the antibody sequences.
agIncludes embeddings for the antigen sequences computed using the ESM2 model.
edges Describes the interactions:
abA sparse coo tensor representing the binary edges between the CDR residues.
agA sparse coo tensor representing the binary edges between the surface residues.
stats Metadata about each antibody-antigen pair, including counts of CDR, surface, and
epitope residues, and the epitope-to-surface ratio.
•structures.tar.gz : Contains 1723 pdb structures, each named using the AbDb identi-
fier.
•split_dict.pt : Contains the train /val/test splits of the dataset, with splits based on
the epitope ratio and epitope group of the antigen.
Long-term Preservation
The current version of the dataset and benchmark are provided through Zenodo, which provides
long-term storage. Future versions will be made available through the same channel and users are
encouraged to submit queries and issues through the issues channel on the GitHub repository.
26
Explicit License
The dataset is licensed under the CC BY 4.0 license ( https://creativecommons.org/
licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License https://opensource.org/licenses/MIT .
Benchmarks
Detailed benchmark experiments and results are provided on Zenodo ( https://doi.org/10.5281/
zenodo.11495514 ), and the file benchmark.zip contains the instructions on how to reproduce
the results. To run ESMFold, EpiPred, and MaSIF-Site, we provided docker images on the Zenodo
repository or instructions on how to obtain them from DockerHub. The benchmark results are
reproducible by following the instructions provided in the zip file. For the method WALLE and its
variants used in the | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | model architecture of WALLE.
The use of separate GCN modules for the antibody and antigen allows for the capture of unique
structural and functional characteristics pertinent to each molecule before any interaction analysis.
This design choice aligns with the understanding that the antibody and antigen have distinct roles in
their interactions and their molecular features should be processed separately.
Decoder
We used a simple decoder to predict the binary labels of edges between the antibody and antigen
graphs, which takes a pair of node embeddings output by the graph modules as input and predicts the
probability of each edge. An edge is assigned a binary label of 1if the predicted probability is greater
than0.5or0otherwise. This is shown as the Decoder module in Figure 3. For the epitope prediction
task, we convert edge-level predictions to node-level by summing the predicted probabilities of all
edges connected to an antigen node; we assign the antigen node a label of 1if the number of connected
edges is greater than a threshold or 0otherwise. The threshold is treated as a hyperparameter and is
optimized in the experiments.
Implementation
We used PyTorch Geometric (Fey & Lenssen, 2019) framework to build our model. The graph
modules are implemented using the GCNConv module from PyTorch Geometric. We trained the
model to minimize a loss function consisting of two parts: a weighted binary cross-entropy loss
for the bipartite graph link reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph. We used the same set of hyperparameters and loss functions for both
dataset settings. The loss function and hyperparameters are described in detail in Appendix A.6.
Experiment results We evaluated each method for both dataset split settings on the test set using
the metrics described in Appendix A.2. Table 1a and Table 1b summarize the average performance
metrics across the test set samples. WALLE generally shows better performance among all metrics
7
Table 1: Performance on test set from dataset split by epitope to antigen surface ratio and epitope
groups.
(a) Performance on dataset split by epitope to antigen surface ratio.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.210 (0.020) 0.235 (0.018) 0.422 (0.028) 0.635 (0.013) 0.258 (0.018)
EpiPred 0.029 (0.018) 0.122 (0.014) 0.180 (0.019) — 0.142 (0.016)
ESMFold 0.028 (0.010) 0.137 (0.019) 0.043 (0.006) — 0.060 (0.008)
ESMBind 0.016 (0.008) 0.106 (0.012) 0.121 (0.014) 0.506 (0.004) 0.090 (0.009)
MaSIF-site 0.037 (0.012) 0.125 (0.015) 0.183 (0.017) — 0.114 (0.011)
(b) Performance on dataset split by epitope groups.
Algorithm MCC Precision Recall AUCROC F1
WALLE 0.077 (0.015) 0.143 (0.017) 0.266 (0.025) 0.544 (0.010) 0.145 (0.014)
EpiPred -0.006 (0.015) 0.089 (0.011) 0.158 (0.019) — 0.112 (0.014)
ESMFold 0.018 (0.010) 0.113 (0.019) 0.034 (0.007) — 0.046 (0.009)
ESMBind 0.002 (0.008) 0.082 (0.011) 0.076 (0.011) 0.500 (0.004) 0.064 (0.008)
MaSIF-site 0.046 (0.014) 0.164 (0.020) 0.174 (0.015) — 0.128 (0.012)
MCC : Matthews Correlation Coefficient; AUCROC : Area Under the Receiver Operating Characteristic Curve;
F1: F1 score. Standard errors are included in the parentheses. We omitted the results of EpiPred, ESMFold and
MaSIF-site for AUCROC. For EpiPred and ESMFold, the interface residues are determined from the predicted
structures by these methods such that the predicted values are binary and not comparable to other methods; As
for MaSIF-site, it outputs the probability of mesh vertices instead of node probabilities and epitopes are
determined as residues close to mesh vertices with probability greater than 0.7.
Table 2: Summary of Features Used in Benchmarking Methods.
Antibody Structure PLM Graph
WALLE ✓ ✓ ✓ ✓
EpiPred ✓ ✓ × ✓
ESMFold ✓ × ✓ ×
MaSIF-site × ✓ × ✓
ESMBind × × ✓ ×
Antibody: Antibody is taken into consideration when predicting epitope nodes;
Structure: Topological information from protein structures;
PLM: Representation from Protein Language Models;
Graph: Graph representation of protein structures.
except for recall for both dataset splits. We also provided the baseline performance for bipartite link
prediction in Table S6.
We also carried out | Section not found | Section not found | ablation studies (Appendix C) to investigate the impact of different components of
WALLE. When we replace the graph convolutional layers with fully connected layers, its performance
degenerates considerably, suggesting that the graph convolutional layers contribute to the model’s
performance. This is related to the fact that the interaction between a pair of protein structures is
dependent on the spatial arrangement of the residues as discussed by Reis et al. (2022). The interface
polar bonds, a major source of antibody specificity, tend to shield interface hydrophobic clusters. In
addition, the language model embeddings also contribute to the model’s performance, as performance
drops when they are replaced by one-hot or BLOSUM62 embeddings. Finally, we also investigated
whether the choice of language model affects the model’s performance. We found that the model
using AntiBERTy and ESM2 embeddings for antibodies and antigens performed slightly better than
the model using ESM2 embeddings for both antibodies and antigens. This suggests that the choice of
language model may impact the model’s performance, but a model like ESM2, which is trained on
general protein sequences, may contain sufficient information for the epitope prediction task.
8
While WALLE outperforms other methods in the second dataset split setting, its performance
degenerated considerably from the first dataset split setting. This suggests that WALLE is likely
biased toward the epitopes in the training set and does not generalize well to unseen epitopes. The
performance of the other four methods is not ideal for this task. We believe this would require a more
sophisticated model architecture and a more comprehensive dataset to improve the performance of
epitope prediction. We invite researchers to examine this issue and bring their insights to improve
generalization.
Edge features In terms of structure representation, we only used a simple invariant edge feature, the
distance matrix, to capture the neighborhood information of each residue. This topological descriptor
already performs better than other methods that use sequence-based features. For future work, more
edge features can be incorporated to enrich the graph representation, in addition to the invariant edge
features used in this work, such as inter-residue distances and edge types used in GearNet (Zhang
et al., 2023), and SE3 equivariant features, such as rotational and orientational relationships between
residues as used in abdockgen (Jin et al., 2022).
Antibody types We also plan to extend our work to include other types of antibodies. Current work
only looks at conventional antibodies, consisting of heavy- and light-chain variable domains. There
are also an increasing number of novel antibodies, for example nanobodies, which are single-variable-
domain antibodies derived from camelids. These will be included in future work.
6 Conclusion
In this work, we proposed a novel benchmarking dataset for the epitope prediction task and clustered
the samples by epitopes. We also provided a model, WALLE, which combines protein language
models and graph neural networks to leverage their abilities in capturing amino acid contextual
and geometric information. We benchmarked WALLE and four other methods, showing that while
WALLE outperforms existing methods on both tasks, there remains room for improvement. Never-
theless, we showed the combination of protein language models and graph neural networks improved
the performance on the epitope prediction task. We also discussed possible future directions. This
work can serve as a starting point for future research in this area.
7 Acknowledgments
CL was part-funded by a UCL Centre for Digital Innovation Amazon Web Services (AWS) Scholar-
ship; LD was funded by an ISMB MRC iCASE Studentship (MR/R015759/1).
References
Akbar, R., Bashour, H., Rawat, P., Robert, P. A., Smorodina, E., Cotet, T.-S., Flem-Karlsen, K., Frank,
R., Mehta, B. B., Vu, M. H., Zengin, T., Gutierrez-Marcos, J., Lund-Johansen, F., Andersen, J. T.,
and Greiff, V . Progress and challenges for the machine learning-based design of fit-for-purpose
monoclonal antibodies. mAbs , 14(1):2008790, 2022. doi: 10.1080/19420862.2021.2008790. URL
https://doi.org/10.1080/19420862.2021.2008790 . PMID: 35293269.
Bennett, N. R., Watson, J. L., Ragotte, R. J., Borst, A. J., See, D. L., Weidle, C., Biswas, R.,
Shrock, E. L., Leung, P. J. Y ., Huang, B., Goreshnik, I., Ault, R., Carr, K. D., Singer, B.,
Criswell, C., Vafeados, D., Garcia Sanchez, M., Kim, H. M., Vázquez Torres, S., Chan, S., and
Baker, D. Atomically accurate de novo design of single-domain antibodies. bioRxiv , 2024. doi:
10.1101/2024.03.14.585103. URL https://www.biorxiv.org/content/early/2024/03/
18/2024.03.14.585103 .
Berman, H., Henrick, K., and Nakamura, H. Announcing the worldwide protein data bank. Nature
Structural & Molecular Biology , 10(12):980–980, Dec 2003. ISSN 1545-9985. doi: 10.1038/
nsb1203-980. URL https://doi.org/10.1038/nsb1203-980 .
Chicco, D. and Jurman, G. The advantages of the matthews correlation coefficient (mcc) over
f1 score and accuracy in binary classification evaluation. BMC Genomics , 21(1):6, Jan 2020.
ISSN 1471-2164. doi: 10.1186/s12864-019-6413-7. URL https://doi.org/10.1186/
s12864-019-6413-7 .
9
Chicco, D. and Jurman, G. The matthews correlation coefficient (mcc) should replace the roc
auc as the standard metric for assessing binary classification. BioData Mining , 16(1):4, Feb
2023. ISSN 1756-0381. doi: 10.1186/s13040-023-00322-4. URL https://doi.org/10.1186/
s13040-023-00322-4 .
Chothia, C. and Lesk, A. M. Canonical structures for the hypervariable regions of immunoglobulins.
Journal of Molecular Biology , 196(4):901–917, 1987. ISSN 0022-2836. doi: https://doi.org/10.
1016/0022-2836(87)90412-8. URL https://www.sciencedirect.com/science/article/
pii/0022283687904128 .
Cia, G., Pucci, F., and Rooman, M. Critical review of conformational B-cell epitope prediction
methods. Briefings in Bioinformatics , 24(1):bbac567, 01 2023. ISSN 1477-4054. doi: 10.1093/
bib/bbac567. URL https://doi.org/10.1093/bib/bbac567 .
Clifford, R. et al. Bepipred-3.0: Improved prediction of b-cell epitopes using protein sequence and
structure data. Protein Science , 2022:4497, 2022. doi: 10.1002/pro.4497.
Evans, R., O’Neill, M., Pritzel, A., Antropova, N., Senior, A., Green, T., Žídek, A., Bates, R.,
Blackwell, S., Yim, J., Ronneberger, O., Bodenstein, S., Zielinski, M., Bridgland, A., Potapenko, A.,
Cowie, A., Tunyasuvunakool, K., Jain, R., Clancy, E., Kohli, P., Jumper, J., and Hassabis, D. Protein
complex prediction with alphafold-multimer. bioRxiv , 2022. doi: 10.1101/2021.10.04.463034.
URL https://www.biorxiv.org/content/early/2022/03/10/2021.10.04.463034 .
Falkner, S., Klein, A., and Hutter, F. Bohb: Robust and efficient hyperparameter optimization at scale,
2018.
Ferdous, S. and Martin, A. C. R. AbDb: antibody structure database—a database of PDB-derived
antibody structures. Database , 2018:bay040, 04 2018. ISSN 1758-0463. doi: 10.1093/database/
bay040. URL https://doi.org/10.1093/database/bay040 .
Fey, M. and Lenssen, J. E. Fast graph representation learning with pytorch geometric, 2019.
Gainza, P., Sverrisson, F., Monti, F., Rodolà, E., Boscaini, D., Bronstein, M. M., and Correia, B. E.
Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning.
Nature Methods , 17(2):184–192, Feb 2020. ISSN 1548-7105. doi: 10.1038/s41592-019-0666-6.
URL https://doi.org/10.1038/s41592-019-0666-6 .
Gao, M. et al. Deep learning-based method for predicting antibody-antigen binding residues with
sequence information. Computational and Biomedical Sciences , 2022:106064, 2022. doi: 10.
1016/j.compbiomed.2022.106064.
Henikoff, S. and Henikoff, J. G. Amino acid substitution matrices from protein blocks. Proceedings
of the National Academy of Sciences , 89(22):10915–10919, 1992. doi: 10.1073/pnas.89.22.10915.
URL https://www.pnas.org/doi/10.1073/pnas.89.22.10915 .
Hu, E. J., Shen, Y ., Wallis, P., Allen-Zhu, Z., Li, Y ., Wang, S., Wang, L., and Chen, W. Lora:
Low-rank adaptation of large language models, 2021.
Hummer, A. M., Abanades, B., and Deane, C. M. Advances in computational structure-based antibody
design. Current Opinion in Structural Biology , 74:102379, 2022. ISSN 0959-440X. doi: https://doi.
org/10.1016/j.sbi.2022.102379. URL https://www.sciencedirect.com/science/article/
pii/S0959440X22000586 .
Jamasb, A. R., Viñas, R., Ma, E. J., Harris, C., Huang, K., Hall, D., Lió, P., and Blundell, T. L.
Graphein - a python library for geometric deep learning and network analysis on protein structures
and interaction networks. bioRxiv , 2021. doi: 10.1101/2020.07.15.204701. URL https://www.
biorxiv.org/content/early/2021/10/12/2020.07.15.204701 .
Jin, W., Barzilay, R., and Jaakkola, T. Antibody-antigen docking and design via hierarchical
equivariant refinement, 2022.
10
Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K.,
Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie,
A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., Back, T., Petersen, S., Reiman, D., Clancy,
E., Zielinski, M., Steinegger, M., Pacholska, M., Berghammer, T., Bodenstein, S., Silver, D.,
Vinyals, O., Senior, A. W., Kavukcuoglu, K., Kohli, P., and Hassabis, D. Highly accurate protein
structure prediction with alphafold. Nature , 596(7873):583–589, Aug 2021. ISSN 1476-4687. doi:
10.1038/s41586-021-03819-2. URL https://doi.org/10.1038/s41586-021-03819-2 .
Kabsch, W. and Sander, C. Dictionary of protein secondary structure: Pattern recognition of
hydrogen-bonded and geometrical features. Biopolymers , 22(12):2577–2637, 1983. doi: https:
//doi.org/10.1002/bip.360221211. URL https://onlinelibrary.wiley.com/doi/abs/10.
1002/bip.360221211 .
Kozakov, D., Hall, D. R., Xia, B., Porter, K. A., Padhorny, D., Yueh, C., Beglov, D., and Vajda, S. The
cluspro web server for protein–protein docking. Nature Protocols , 12(2):255–278, Feb 2017. ISSN
1750-2799. doi: 10.1038/nprot.2016.169. URL https://doi.org/10.1038/nprot.2016.169 .
Krawczyk, K., Liu, X., Baker, T., Shi, J., and Deane, C. M. Improving B-cell epitope prediction
and its application to global antibody-antigen docking. Bioinformatics , 30(16):2288–2294, 04
2014. ISSN 1367-4803. doi: 10.1093/bioinformatics/btu190. URL https://doi.org/10.1093/
bioinformatics/btu190 .
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., dos Santos Costa, A., Fazel-Zarandi,
M., Sercu, T., Candido, S., et al. Language models of protein sequences at the scale of evolution
enable accurate structure prediction. bioRxiv , 2022.
Lin, Z., Akin, H., Rao, R., Hie, B., Zhu, Z., Lu, W., Smetanin, N., Verkuil, R., Kabeli, O., Shmueli, Y .,
dos Santos Costa, A., Fazel-Zarandi, M., Sercu, T., Candido, S., and Rives, A. Evolutionary-scale
prediction of atomic-level protein structure with a language model. Science , 379(6637):1123–1130,
2023. doi: 10.1126/science.ade2574. URL https://www.science.org/doi/abs/10.1126/
science.ade2574 .
Mahajan, S., Yan, Z., Jespersen, M. C., Jensen, K. K., Marcatili, P., Nielsen, M., Sette, A., and Peters,
B. Benchmark datasets of immune receptor-epitope structural complexes. BMC Bioinformatics ,
20(1):490, Oct 2019. ISSN 1471-2105. doi: 10.1186/s12859-019-3109-6. URL https://doi.
org/10.1186/s12859-019-3109-6 .
Martin, A. C., Cheetham, J. C., and Rees, A. R. Molecular modeling of antibody combining
sites. Methods Enzymology , 203:121–153, 1991. ISSN 0076-6879. doi: https://doi.org/10.1016/
0076-6879(91)03008-5. URL https://www.sciencedirect.com/science/article/pii/
0076687991030085 .
Matthews, B. Comparison of the predicted and observed secondary structure of t4 phage lysozyme.
Biochimica et Biophysica Acta (BBA) - Protein Structure , 405(2):442–451, 1975. ISSN 0005-2795.
doi: https://doi.org/10.1016/0005-2795(75)90109-9. URL https://www.sciencedirect.com/
science/article/pii/0005279575901099 .
Myung, J. et al. Csm-ab: A deep learning-based approach for predicting antibody-antigen binding
sites. Bioinformatics , 2021:btab762, 2021. doi: 10.1093/bioinformatics/btab762.
Pierce, B. G., Hourai, Y ., and Weng, Z. Accelerating protein docking in zdock using an advanced 3d
convolution library. PLOS ONE , 6(9):1–6, 09 2011. doi: 10.1371/journal.pone.0024657. URL
https://doi.org/10.1371/journal.pone.0024657 .
Pittala, S. and Bailey-Kellogg, C. Learning context-aware structural representations to predict antigen
and antibody binding interfaces. Bioinformatics , 36(13):3996–4003, 04 2020. ISSN 1367-4803.
doi: 10.1093/bioinformatics/btaa263. URL https://doi.org/10.1093/bioinformatics/
btaa263 .
Raghavan, A. K. and Martin, A. C. Analysis and improvements to Kabat and structurally correct
numbering of antibody variable domains. Molecular Immunology , 45:3832–3839, 2008. doi:
10.1016/j.molimm.2008.05.022.
11
Reis, P. B. P. S., Barletta, G. P., Gagliardi, L., Fortuna, S., Soler, M. A., and Rocchia, W. Antibody-
antigen binding interface analysis in the big data era. Frontiers in Molecular Biosciences , 9, 2022.
ISSN 2296-889X. doi: 10.3389/fmolb.2022.945808. URL https://www.frontiersin.org/
articles/10.3389/fmolb.2022.945808 .
Ruffolo, J. A., Gray, J. J., and Sulam, J. Deciphering antibody affinity maturation with language
models and weakly supervised learning, 2021.
Ruffolo, J. A., Chu, L.-S., Mahajan, S. P., and Gray, J. J. Fast, accurate antibody structure prediction
from deep learning on massive set of natural antibodies, Apr 2023.
Schreiber, A. Esmbind and qbind: Lora, qlora, and esm-2 for predicting binding sites and post
translational modification. bioRxiv , 2023. doi: 10.1101/2023.11.13.566930. URL https:
//www.biorxiv.org/content/early/2023/11/14/2023.11.13.566930 .
Sievers, F., Wilm, A., Dineen, D., Gibson, T. J., Karplus, K., Li, W., Lopez, R., McWilliam, H.,
Remmert, M., Söding, J., Thompson, J. D., and Higgins, D. G. Fast, scalable generation of high-
quality protein multiple sequence alignments using clustal omega. Molecular Systems Biology , 7
(1):539, 2011. doi: https://doi.org/10.1038/msb.2011.75. URL https://www.embopress.org/
doi/abs/10.1038/msb.2011.75 .
Steinegger, M. and Söding, J. Mmseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets. Nature Biotechnology , 35(11):1026–1028, Nov 2017. ISSN 1546-1696. doi:
10.1038/nbt.3988. URL https://doi.org/10.1038/nbt.3988 .
Sun, X. et al. Sagerank: A deep learning approach to predict antigenic epitopes using sequence and
structure data. Preprint at bioRxiv , 2023. doi: 10.1101/2023.10.11.561985.
Tubiana, J., Schneidman-Duhovny, D., and Wolfson, H. J. Scannet: an interpretable geometric
deep learning model for structure-based protein binding site prediction. Nature Methods , 19
(6):730–739, Jun 2022. ISSN 1548-7105. doi: 10.1038/s41592-022-01490-7. URL https:
//doi.org/10.1038/s41592-022-01490-7 .
Vecchio, A. D., Deac, A., Liò, P., and Veli ˇckovi ´c, P. Neural message passing for joint paratope-epitope
prediction, 2021.
Yan, Y ., Zhang, D., Zhou, P., Li, B., and Huang, S.-Y . HDOCK: a web server for protein–protein
and protein–DNA/RNA docking based on a hybrid strategy. Nucleic Acids Research , 45(W1):
W365–W373, 05 2017. ISSN 0305-1048. doi: 10.1093/nar/gkx407. URL https://doi.org/
10.1093/nar/gkx407 .
Yeturu, K. and Chandra, N. Pocketmatch: A new algorithm to compare binding sites in protein struc-
tures. BMC Bioinformatics , 9(1):543, Dec 2008. ISSN 1471-2105. doi: 10.1186/1471-2105-9-543.
URL https://doi.org/10.1186/1471-2105-9-543 .
Zhang, Z., Xu, M., Jamasb, A., Chenthamarakshan, V ., Lozano, A., Das, P., and Tang, J. Protein
representation learning by geometric structure pretraining, 2023.
Zhao, N., Han, B., Zhao, C., Xu, J., and Gong, X. ABAG-docking benchmark: a non-redundant
structure benchmark dataset for antibody–antigen computational docking. Briefings in Bioin-
formatics , 25(2):bbae048, 02 2024. ISSN 1477-4054. doi: 10.1093/bib/bbae048. URL
https://doi.org/10.1093/bib/bbae048 .
Zhou, X., Xue, D., Chen, R., Zheng, Z., Wang, L., and Gu, Q. Antigen-specific antibody design via
direct energy-based preference optimization, 2024.
12
A Appendix-A
A.1 Related work
Comparison of Previous Datasets We would like to highlight our dataset, AsEP, is the largest
curated AbAg benchmarking dataset to date. Existing ones either focus on general protein-protein
complexes designed to develop general docking methods or are way smaller than AsEP if designed
for AbAg interaction research. We summarized the sizes of existing datasets in the following table.
Table S1: Comparison of Dataset Sizes Across Different Methods
Method Dataset Size
WALLE (AsEP) 1723 AbAg complexes
Gao et al. 2022 Gao et al. (2022) 258 AbAg complexes
CSM-AB Myung et al. (2021) 472 AbAg complexes
SAGERank Sun et al. (2023) 287 AbAg complexes
Bepipred3.0 Clifford et al. (2022) 582 AbAg complexes
SCEptRe Mahajan et al. (2019) is a related dataset that keeps a weekly updated collection of 3D
complexes of epitope and receptor pairs, for example, antibody-antigen, TCR-pMHC, and MHC-
ligand complexes derived from the Immune Epitope Database (IEDB). Our approach for clustering
antibody-antigen complexes regarding their epitopes is similar to theirs, with the difference in the
clustering strategy. We cluster by antigen, then epitope group, and we allow mutated amino acids
in the same epitope region because we turn the epitope sites into columns in the multiple sequence
alignment. In contrast, SCEptRe clusters by antibody and then compares epitope similarity by
epitope conformation using atom-pair distances via PocketMatch Yeturu & Chandra (2008), which is
beneficial for comparing the function of various paratopes but is less suitable for our task of predicting
epitope residues.
Sequence-based epitope predictor We also tested purely sequence-based epitope prediction tool,
for example, Bepipred3.0 Clifford et al. (2022) on our dataset. Bepipred3.0 uses ESM2 model,
esm2_t33_650M_UR50D to generate sequence embeddings and was trained on a smaller dataset
of 582 antibody-antigen structures and evaluated on 15 antibody-antigen complexes. The authors
provided a relatively larger evaluation of linear B-cell epitopes derived from the Immune Epitope
Database and reported an AUC-ROC of 0.693on the top 10% of the predicted epitopes. We tested
Bepipred3.0 on our dataset and found its performance degenerates significantly, as shown in the table
below. This is not surprising because linear epitopes are consecutive positions in an antigen sequence,
and this task fits better with language model design. Additionally, as pointed out by the authors,
approximately 90% of epitopes (B-cell) fall into the conformational category Clifford et al. (2022),
which highlights the importance of the present benchmark dataset composed of conformational
epitopes derived from filtered antibody-antigen structures. We believe these results underline the
findings in our paper, showing that large language models alone, even if specialized for antibody-
antigen interactions, do not encompass all the relevant information needed for epitope prediction.
13
Confidence Threshold Top 10% Top 30% Top 50% Top 70% Top 90%
AUC 0.693392 0.693392 0.693392 0.693392 0.693392
Balanced Accuracy 0.573132 0.636365 0.638755 0.604556 0.542274
MCC 0.109817 0.140183 0.134689 0.113372 0.071876
Precision-Recall AUC 0.176429 0.176429 0.176429 0.176429 0.176429
Accuracy 0.850178 0.701202 0.536947 0.362489 0.179051
Precision 0.169202 0.141361 0.120547 0.104286 0.090441
Recall 0.236760 0.553204 0.756607 0.892628 0.977723
F1-Score 0.173370 0.208366 0.197153 0.179294 0.160151
Table S2: Bepipred3.0 results for the presented AsEP dataset. The distance cutoff was changed to
4.0Å, as this is the threshold used by Bepipred3.0. Results are shown for five confidence thresholds
as described in the BepiPred-3.0 paper. Across all stringency settings and metrics, Bepipred scored
lower than Walle. Furthermore, it is possible that some of the structures within the dataset are
contained within the Bepipred3.0 dataset, artificially increasing scores.
A.2 Evaluation
In this work, we focus on the epitope prediction task. We evaluate the performance of each method
using consistent metrics. Matthew’s Correlation Coefficient (MCC) is highly recommended for binary
classification assessments Matthews (1975) and is especially advocated for its ability to provide equal
weighting to all four values in the confusion matrix, making it a more informative metric about the
classifier’s performance at a given threshold than other metrics Chicco & Jurman (2020, 2023). We
encourage the community to adopt MCC for the epitope prediction task as it takes into account true
and false positives, as well as true and false negatives, offering a comprehensive measure of the
performance. It is considered superior to the AUC-ROC, which is evaluated over all thresholds. For
consistency, we also included Precision and Recall from prior studies EpiPred Krawczyk et al. (2014)
and PECAN Pittala & Bailey-Kellogg (2020), and we added Area Under the Receiver Operating
Characteristic Curve (AUC-ROC) and F1 score, both are typical binary classification metrics. For
methods that predict antibody-antigen complex structures, we determine the epitopes using the same
distance criterion as aforementioned.
A.3 Steps to build antibody-antigen complex dataset
We sourced our initial dataset from AbDb (version dated September 26, 2022), containing 11,767
antibody files originally collected from the Protein Data Bank (PDB). We collected complexes
numbered in Martin scheme Raghavan & Martin (2008) and used AbM CDR definition Martin et al.
(1991) to identify CDR residues from the heavy and light chains of antibodies.
We extracted antibody-antigen complexes that met the following criteria: (1) both VH and VL
domains are present in the antibody; (2) the antigen is a single-chain protein consisting of at least 50
amino acids; and (3) there are no unresolved CDR residues, yielding 4,081 files.
To deduplicate complexes, we used MMseqs2 Steinegger & Söding (2017) to cluster the complexes
by heavy and light chains in antibodies and antigen sequences. We used the easy-linclust mode with
the–cov-mode 0 option to cluster sequences; we used the default setting for coverage of aligned
cutoff at 80%; we used different –min-seq-id cutoffs for antibodies and antigens because the antibody
framework regions are more conserved than the CDR regions. We cluster heavy and light chains at
–min-seq-id cutoff of 100% and70%, respectively. We retained only one representative file for each
unique set of identifiers, leading to a refined dataset of 1,725 files.
Two additional files were manually removed. File 6jmr_1P was removed because its CDR residues
are masked with ‘UNK’ labels and the residue identities are unknown; file 7sgm_0P was removed
because of a non-canonical residue ‘DV7’ in its CDR-L3 loop.
The final dataset consists of 1,723 antibody-antigen complexes.
14
A.4 Pipeline to build graph dataset from AbDb
Prepare Graph Dataset
Raw Structure Files
AbDb Complex
antigenOriginal PDB filePDB id
AbDb PDB
Y es
[U, F]Coordinates, Sequences
Antigen Structure
Atom
Chain
ResidueSEQRES (U) ATMSEQ (V)
len(seq) > thr Processing Modules
Calculate
ASA
(DSSP)Calculate
distance
matrix Residue
CheckingSequence
AlignmentSequence
Embedding
(ESM)Intermediate Data
ATMSEQ2NODES
Mask (V -> N)SEQRES2A TMSEQ
Mask (U -> V)residue-residue
distance matrix
(V, V)Pre Node
Labels (V , 1)MasksApply Mask I
(V --> N)Apply Mask I
(V --> N)Apply Mask I & II
(U --> V --> N)[V, ] [V, V]Output Graph
Label
(N, 1)Edge
(2, E)Node
Embeddings
(N, C)
Figure S1: Pipeline to convert an antibody-antigen complex structure into a graph representation.
•Row 1 : given an AbAg complex PDB ID, retrieve ‘AbAg complex’ from AbDb and ‘raw
structure’ file from PDB as input, ‘AbDb complex antigen’ and ‘Original PDB file’ in the
top lane.
•Row 2 : They are then parsed as hierarchical coordinates (Antigen Structure), and extract
ATMSEQ and SEQRES sequences.
•Row 3 : these are then passed to a set of in-house modules for calculating solvent access
surface area (ASA), distance matrix, and filtering out problematic residues, which generates
an ATMSEQ2NODES mask. The sequence alignment module aligns ATMSEQ with
SEQRES sequences to generate a mask mapping from SEQRES to ATMSEQ. The
Sequence Embedding module passes SEQERS through the ESM module to generate
embeddings. ESM requires input sequence length and therefore filters out sequences longer
than 1021 amino acids.
•Row 4 : holds intermediate data that we apply masks to generate graph data in Row 5 .
•Row 6 : Apply the masks to map SEQRES node embeddings to nodes in the graphs and
calculate the edges between the graph nodes.
U,VandNdenote the number of residues in the SEQRES sequence, ATMSEQ sequence and the
graph, respectively. thr(at 50 residues) is the cutoff for antigen SEQRES length. We only include
antigen sequences with lengths of at least 50 residues. SEQRES andATMSEQ are two different
sequence representations of a protein structure. SEQRES is the sequence of residues in the protein
chain as defined in the header section of a PDB file, and it is the complete sequence of the protein
chain. ATMSEQ is the sequence of residues in the protein chain as defined in the ATOM section of a
PDB file. In other words, it is read from the structure, and any residues in a PDB file are not resolved
due to experimental issues that will be missing in the ATMSEQ sequence. Since we are building
graph representations using structures, we used ATMSEQ . However, the input to the language models
15
require a complete sequence, therefore we used SEQRES to generate node embeddings, and mapped
the node embeddings to the graph nodes. We performed two pairwise sequence alignments to map
such embeddings to graph vertices for a protein chain with Clustal Omega Sievers et al. (2011). We
first align the SEQRES sequence with the atom sequence (residues collected from the ATOM records
in a PDB file) and assign residue embeddings to matched residues. Because we excluded buried
residues from the graph, we aligned the sequence formed by the filtered graph vertices with the atom
sequence to assign residue embeddings to vertices. ASA is the solvent-accessible surface area of a
residue. If a residue has an ASA value of zero, it is considered buried and will be removed from the
graph.
A.5 Dataset split
Table S3: Distribution of epitope to antigen surface nodes in each set.
Epi/Surf Training Validation/Test
0, 5% 320 (23% ) 40 (24%)
5% , 10% 483 (35% ) 60 (35%)
10%, 15% 305 (22% ) 38 (22%)
15%, 20% 193 (14% ) 24 (14%)
20%, 25% 53 (4% ) 6 (4% )
25%, 30% 19 (1% ) 2 (1% )
30%, 35% 8 (0.6%) 0 (- )
35%, 40% 2 (0.1%) 0 (- )
sum 1383 170
A.6 | Section not found | Section not found | Section not found | Section not found | Implementation details
Exploratory Data Analysis We performed exploratory data analysis on the training dataset to
understand the distribution of the number of residue-residue contacts in the antibody-antigen interface.
We found that the number of contacts is approximately normally distributed with a mean of 43.42
and a standard deviation of 11.22 (Figure S2). We used this information to set the regularizer in the
loss function to penalize the model for predicting too many or too few positive edges.
0 20 40 60 80 100
Number of contacts0.0000.0050.0100.0150.0200.0250.0300.035Density
Mean: 43.42 Median: 44.00
HDI Left: 34.00 HDI Right: 49.00Number of contacts (bipartite graph edges) per AbAg complex
Mean
Median
50.0% HDI
Fitted Normal
Distribution
( = 43.42, = 11.22)
Figure S2: Blue line: distribution of the number of residue-residue contacts in antibody-antigen
interface across the dataset with a mean and median of 43.27 and 43.00, respectively. Red line: fitted
normal distribution with mean and standard deviation of 43.27 and 10.80, respectively.
16
Loss function Our loss function is a weighted sum of two parts: a binary cross-entropy loss for
the bipartite graph linkage reconstruction and a regularizer for the number of positive edges in the
reconstructed bipartite graph.
Loss =Lr+λNX
ˆe−c(3)
Lr=−1
NNX
i=1(wpos·ye·log( ˆye) +wneg·(1−ye)·log(1−ˆye)) (4)
The binary cross-entropy loss Lris weighted by wposandwnegfor positive and negative edges,
respectively. During hyperparameter tuning, we kept wnegfixed at 1.0and tuned wpos.Nis the
total number of edges in the bipartite graph, yedenotes the true label of edge e, and ˆyedenotes the
predicted probability of edge e. The regularizerPNˆe−cis the L1 norm of the difference between
the sum of the predicted probabilities of all edges of the reconstructed bipartite graph and the mean
positive edges in the training set, i.e., cset to 43. This aims to prevent an overly high false positive
rate, given the fact that the number of positive edges is far less than positive edges. The regularizer
weight λis tuned during hyperparameter tuning.
Hyperparameters We carried out hyperparameter search within a predefined space that included:
•Weights for positive edges in bipartite graph reconstruction loss, sampled uniformly between 50
and 150.
•Weights for the sum of bipartite graph positive links , where values were drawn from a log-
uniform distribution spanning 1e−7to1e−4.
•Edge cutoff (x) , defining an epitope node as any antigen node with more than x edges, with x
sampled following a normal distribution with a mean of 3 and a standard deviation of 1.
•Number of graph convolutional layers in the encoder, we tested using 2 and 3 layers.
•Decoder type was varied between two configurations:
–A fully connected layer, equipped with a bias term and a dropout rate of 0.1.
–An inner product decoder.
Computing resources All experiments were performed on a single Linux machine (Ubuntu 22.04)
with one NVIDIA RTX3090 GPU card, and it took on average 3 hours for a single hyper-parameter
sweeping experiment.
A.7 Antibody-antigen complex examples
To compare the epitopes of antibodies in AsEP, we first clustered these complexes by antigen
sequences to group together antibodies targeting the same antigen via MMseqs2 Steinegger & Söding
(2017). Specifically, we ran MMseqs2 on antigen SEQRES sequences and using the following setup:
•easy-linclust mode
•cov-mode set to 0with the default coverage of 80%: this means a sequence is considered a cluster
member if it aligns at least 80% of its length with the cluster representative;
•min-seq-id set to 0.7: this means a sequence is considered a cluster member if it shares at least
70% sequence identity with the cluster representative.
We encourage the reader to refer to the MMseqs2 documentation https://github.com/
soedinglab/mmseqs2/wiki for more details on the parameters used.
We then identify epitopes using a distance cut-off of 4.5 Å. An antigen residue is identified as epitope
if any of its heavy atoms are located within 4.5 Å of any heavy atoms from the antibody.
To compare epitopes of antibodies sharing the same antigen cluster, we aligned the antigen SEQRES
sequences using Clustal Omega Sievers et al. (2011) (download from: http://www.clustal.org/
omega/ ) to obtain a Multiple Sequence Alignment (MSA). Epitopes are mapped to and denoted as
the MSA column indices. The epitope similarity between a pair of epitopes is then calculated as
17
the fraction of identical columns. Two epitopes are identified as identical if they share over 0.7of
identical columns.
Table S4: Antibody-Antigen Complex Examples
(a) Antigen Group Information
abdbid repr size epitope_group
7eam_1P 7sn2_0P 183 0
5kvf_0P 5kvd_0P 9 1
5kvg_0P 5kvd_0P 9 2
(b) CDR Sequences (Heavy Chain)
abdbid H1 H2 H3
7eam_1P GFNIKDTYIH RIDPGDGDTE FYDYVDYGMDY
5kvf_0P GYTFTSSWMH MIHPNSGSTN YYYDYDGMDY
5kvg_0P GYTFTSYGIS VIYPRSGNTY ENYGSVY
(c) CDR Sequences (Light Chain)
abdbid L1 L2 L3
7zf4_1P RASGNIHNYLA NAKTLAD QHFWSTPPWT
7zbu_0P KSSQSLLYSSNQKNYLA WASTRES QQYYTYPYT
7xxl_0P KASQNVGTA V A SASNRYT QQFSSYPYT
(d) Structure Titles
abdbid resolution title repr_title
7zf4_1P 1.4 immune complex of SARS-CoV-2
RBD and cross-neutralizing antibody
7D6SARS-CoV-2 Omicron variant spike
protein in complex with Fab XGv265
7zbu_0P 1.4 Zika specific antibody, ZV-64, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
7xxl_0P 1.4 Zika specific antibody, ZV-67, bound
to ZIKA envelope DIIICryo-EM structure of zika virus com-
plexed with Fab C10 at pH 8.0
Here we provide three example antibody-antigen complexes from the same antigen group, meaning
the antigen sequences from each member complex share sequence identity of the aligned region at
least 70%. Due to space limitation, we have broken the rows into four parts: Antigen group
information, CDR sequences, and structure titles.
•abdbid : AbDb ID of the group member;
•repr: AbDb ID of the antigen representative;
•size: the number of complexes in the group;
•epitope_group : A categorical identifier of the epitope group the antibody-antigen complex
belongs to;
•H1,H2,H3,L1,L2,L3: CDR sequences of the heavy and light chains;
•resolution : Structure resolution;
•title: Structure title of the member;
•repr_title : Structure title of the antigen representative.
18
A.8 Multi-epitope Antigens
We include 641unique antigens and 973epitope groups in our dataset. Figure S3 shows two examples
of multi-epitope antigens in our dataset, hen egg white lysozyme (Figure S3a) and spike protein
(Figure S3b). Specifically, there are 52and64distinct antibodies in our dataset that bind to hen egg
white lysozyme and spike protein, respectively. For visual clarity, we only show five and sixteen
antibodies in Figure S3a and Figure S3b.
We can see that different antibodies bind to different locations on the same antigen. Details of all
epitope groups are provided in the Supplementary Table SI-AsEP-entries.csv with annotation
provided in Appendix A.7.
(a) Five different antibodies bound to hen egg white lysozyme. Complexes are superimposed on the antigen
structure (magenta). AbDb IDs of the complexes and their color: 1g7i_0P (green), 2yss_0P (cyan), 1dzb_1P
(yellow), 4tsb_0P (orange), 2iff_0P (wheat). Antigens are colored in magenta.
(b) Sixteen different antibodies bound to coronavirus spike protein. Complexes are superimposed on the antigen
structure (magenta) and antibodies are in different colors. AbDb IDs of the complexes: 7k8s_0P, 7m7w_1P,
7d0b_0P, 7dzy_0P, 7ey5_1P, 7jv4_0P, 7k8v_1P, 7kn4_1P, 7lqw_0P, 7n8i_0P, 7q9i_0P, 7rq6_0P, 7s0e_0P, 7upl_1P,
7wk8_0P, 7wpd_0P.
Figure S3: Examples of different antibodies binding to the same antigen.
19
A.9 Metrics definition
MCC =(TP×TN−FP×FN)p
(TP+FP)(TP+FN)(TN+FP)(TN+FN)
Precision =TP
TP+FP
Recall =TP
TP+FN
F1 =2×Precision ×Recall
Precision +Recall
TP: True Positive
FP: False Positive
TN: True Negative
FN: False Negative
A.10 Fine-tuning ESMBind on AsEP
The performance reported in the main text for ESMBind is derived by fine-tuning ESM2 on general
protein binding sites. We performed a further fine-tuning experiment, fine-tuning it on the presented
AsEP dataset and evaluating it on the AsEP test set to enable a more direct comparison of ESMBind
to WALLE. Fine-tuning of ESMBind on AsEP was done using the Low-Rank Adaptation method Hu
et al. (2021).
Table S5: Performance Metrics
Metric Value
MCC 0.103923
Accuracy 0.504478
AUC-ROC 0.584497
Precision 0.128934
Recall 0.707731
F1 0.213829
20
B Appendix: Link prediction baseline
While the majority of existing studies focus on node-level prediction, i.e., predicting which residues
are likely to be the epitope residues, we are interested in predicting the interactions between epitope
and antigen residues. We argue that, on the one hand, this would provide a more comprehensive
understanding of the interaction between epitopes and antigens, and on the other hand, it would be
good in terms of model interpretability. Existing methods for predicting epitope residues are mostly
based on sequence information, which is not directly interpretable in terms of the interaction between
epitopes and antigens.
Our hyperparameter search was conducted within a predefined space as defined in Appendix A.6.
We used the Bayesian optimization strategy implemented through Weights & Biases, targeting the
maximization of the average bipartite graph link Matthew’s Correlation Coefficient (MCC).
The optimization process was managed using the early termination functionality provided by the
Weights & Biases’ Hyperband method Falkner et al. (2018), with a range of minimum to maximum
iterations set from 3 to 27.
The best set of hyperparameters is 2GCNConv layers, a batch size of 32, a weight for positive edges
of54.7, a weight for the sum of positive links at approximately 5.75e−7, and an edge cutoff of 2.38.
The resulting MCC evaluated on the test set was 0.072(standard error: 0.009) for the bipartite graph
link prediction task.
Table S6: Evaluation of WALLE on the bipartite graph link prediction task
Metric Mean (Standard Error)
MCC 0.072 (0.009)
ROC-AUC 0.582 (0.011)
Precision 0.049 (0.008)
Recall 0.167 (0.023)
F1 0.053 (0.007)
21
C Appendix: Ablation Studies
To investigate the impact of different components on WALLE’s performance, we carried out ablation
studies and described them in this section. For each model variant, we performed hyperparameter
tuning and reported the evaluation performance using the model with the best performance on the
validation set.
C.1 Ablation study: replace graph component with linear layers
To investigate whether the graph component within the WALLE framework is essential for its
predictive performance, we conducted an ablation study in which the graph component was replaced
with two linear layers. We refer to the model as ‘WALLE-L’. The first linear layer was followed by a
ReLu activation function. Logits output by the second linear layer were used as input to the decoder.
The rest of the model architecture remained the same.
It differs from the original WALLE model in that the input to the first linear layer is simply the
concatenation of the embeddings of the antibody and antigen nodes, and the linear layers do not
consider the graph structure, i.e., the spatial arrangement of either antibody or antigen residues. The
model was trained using the same hyperparameters as the original WALLE model. The performance
of WALLE-L was evaluated on the test set using the same metrics as the original WALLE model.
C.2 Ablation study: WALLE with simple node encoding
The presented WALLE model utilizes embeddings from large language models, including ESM2 Lin
et al. (2022) or IgFoldRuffolo et al. (2023) for representing amino acid sequences, as these models
are able to capture the sequential and structural information inherent in protein sequences, providing
a rich, context-aware representation of amino acids. To test the effectiveness of such embeddings
in this downstream task, we conducted an ablation study where we replaced the embeddings from
language models with simple node encodings. Specifically, we evaluated the performance of WALLE
when using ‘one-hot’ encoding and ‘BLOSUM62’ encoding for amino acids in both antibody and
antigen sequences.
C.3 Ablation study: WALLE with ESM2 embeddings for both antibodies and antigens
We also investigated whether the choice of language models can impact the predictive performance
of WALLE; we conducted an ablation study to evaluate the performance of WALLE when both
antibodies and antigens are represented using embeddings from the ESM2 language model Lin et al.
(2022) while the original model uses AntiBERTy Ruffolo et al. (2023) for antibodies as it is trained
exclusively on antibody sequences. This also tests whether a language model trained on general
protein sequences can be used for a downstream task like antibody-antigen interaction prediction.
One-hot encoding
One-hot encoding is a method where each residue is represented as a binary vector. Each position in
the vector corresponds to a possible residue type, and the position corresponding to the residue present
is marked with a 1, while all other positions are set to 0. This encoding scheme is straightforward and
does not incorporate any information about the physical or chemical properties of the residues. This
method tests the model’s capability to leverage structural and relational information from the graph
component without any assumptions introduced by more complex encoding schemes.
BLOSUM62 encoding
BLOSUM62 Henikoff & Henikoff (1992) encoding involves using the BLOSUM62 matrix, which
is a substitution matrix used for sequence alignment of proteins. In this encoding, each residue
is represented by its corresponding row in the BLOSUM62 matrix. This method provides a more
nuanced representation of residues, reflecting evolutionary relationships and substitution frequencies.
22
C.4 Hyperparameter tuning
We used the same hyperparameter search space defined in Appendix A.6 and performed a hyperpa-
rameter search as defined in Appendix B for each model variant in the ablation studies. We report the
evaluation performance of the tuned model for each variant in Table S7.
Table S7: Performance of WALLE without graph component and simple node encodings on test set
from dataset split by epitope to antigen surface ratio.
Algorithm Encoding MCC AUCROC Precision Recall F1
WALLE Both 0.2097 (0.0195) 0.6351 (0.0126) 0.2346 (0.0183) 0.4217 (0.0279) 0.2580 (0.0178)
WALLE-L Both 0.1593 (0.0155) 0.6124 (0.0109) 0.1750 (0.0109) 0.4696 (0.0243) 0.2371 (0.0137)
WALLE ESM2 0.1955 (0.0212) 0.6219 (0.0137) 0.2280 (0.0188) 0.4103 (0.0291) 0.2553 (0.0188)
WALLE-L ESM2 0.1445 (0.0138) 0.6100 (0.0097) 0.1598 (0.0102) 0.5355 (0.0216) 0.2266 (0.0125)
WALLE One-hot 0.0968 (0.0094) 0.5830 (0.0076) 0.1185 (0.0052) 0.8923 (0.0118) 0.2026 (0.0081)
WALLE BLOSUM 0.0848 (0.010) 0.5739 (0.0081) 0.1182 (0.0055) 0.8401 (0.0151) 0.1993 (0.0083)
The values in parentheses represent the standard error of the mean; ‘WALLE-L’ refers to WALLE
with the graph component replaced by two linear layers. ‘ESM2’ refers to the embeddings from the
ESM2 language model esm2_t12_35M_UR50D . ‘One-Hot’ refers to one-hot encoding of amino
acids. ‘BLOSUM62’ refers to the BLOSUM62 encoding of amino acids. ‘Both’ refers to embedding
antibodies and antigens using the esm2_t12_35M_UR50D ESM2 model and AntiBERTy (via IgFold)
language model, respectively. The best performing model is highlighted in bold.
We observed that WALLE’s performance with simple node encodings (‘one-hot’ and ‘BLOSUM62’)
is considerably lower than when using advanced embeddings from language models. This indicates
that the embeddings derived from language models capture more nuanced information about the
amino acids, enabling the model to better predict epitope-antigen interactions.
The degenerated performance of WALLE with simple encodings can be attributed to the lack of
contextual information and structural features in these representations. The high recall but low
precision values suggest that the model is unable to distinguish between true and false interactions,
leading to a high number of false positives. This highlights the importance of using meaningful
embeddings that capture the rich structural and sequential information present in protein sequences.
When comparing WALLE with WALLE-L (without the graph components), we observe that the
model’s performance drops considerably when the graph component is replaced with fully connected
linear layers. This indicates that the topological information captured by the graph component also
contributes to the model’s predictive performance.
We also observed that WALLE with ESM2 embeddings for both antibodies and antigens achieved
similar performance to WALLE with AntiBERTy and ESM2 embeddings for antibodies and antigens,
respectively. This suggests that the ESM2 embeddings somehow provide effective information for
both antibodies and antigens without training exclusively on antibody sequences.
D Impact Statement
This work extends to the optimization of antibody drug development, offering a more efficient and
accurate method for predicting where antibodies bind on antigens, a crucial challenge of developing
therapeutic antibodies. The potential impact of this advancement is underscored by the recent
approval of 136 antibody-based drugs in the United States or European Union, with 17 novel
antibody therapeutics approved since January 2023 and 18 more currently under review (Antibody
Society, Antibody therapeutics approved or in regulatory review in the EU or US, https://www.
antibodysociety.org/resources/approved-antibodies/ , 24 January 2024). These figures
show the transformative impact that antibody design innovation can have on transforming the
landscape of therapeutic development, offering new avenues for targeted, effective treatments that
can be developed in a more time- and cost-effective manner. Such advancements hold immense
potential in accelerating the creation of targeted therapies and implicitly support the broader goals of
personalized medicine. Fast-tracking antibody design through in silico epitope prediction can enable
quicker responses to emerging health threats like pandemics or rapidly mutating pathogens. However,
23
in silico predictions should not be blindly trusted and should merely guide and streamline research
and diligent testing, not replace it.
This paper presents work whose goal is to highlight antibody-specific epitope prediction as a major
challenge that has not been widely studied to date, which is presented as a bipartite graph connectivity
prediction task. This research stands out primarily for its development of a novel benchmarking
dataset for antibody-specific epitope prediction - a resource previously unavailable in the scientific
community with the potential to set a new standard in the field.
Existing methods are compared using uniform metrics and a vast room for improvement can be
demonstrated across the board. A novel model is presented, which surpasses its counterparts by
an order of magnitude, outperforming them by a factor of ten, validating its graph-based approach
utilizing antibody and antigen structural information as well as leveraging protein language models.
We provide a foundational framework that invites other researchers to further build upon and refine
this baseline model, which we have demonstrated to be a highly effective approach for this task.
Open availability of the dataset and model facilitates further research and exploration in this domain,
expediting the development of more advanced models. Highlighting types of antibody-antigen
interactions that are disregarded in existing datasets and methods encourages the examination of
shortcoming of current models. The focus on conventional antibodies in this work lays the groundwork
for future exploration into epitope prediction for novel antibodies, such as nanobodies, expanding
upon potential applications.
24
Supplementary Materials
Dataset Documentation and Intended Uses
We provide a data card for this dataset, DataCard-AsEP.md , which can be downloaded using this
link: https://drive.google.com/file/d/1fc5kFcmUdKhyt3WmS30oLLPgnkyEeUjJ/view?
usp=drive_link
This dataset provides a unified benchmark for researchers to develop new machine-learning-based
methods for the epitope prediction task.
Access to the Dataset
There are two alternative sources where users can download the dataset:
•The dataset can be downloaded using the Python interface provided by our GitHub Reposi-
tory AsEP-dataset. Detailed instructions on how to download the dataset are provided in the
README file. Briefly, after installing the provided Python module, asep , the dataset can
be downloaded by running the following command in the terminal:
download - asep / path /to/ directory AsEP
# For example , to download the dataset to the current
,→directory , run
# download - asep . AsEP
•The dataset and benchmark are provided through Zenodo at https://doi.org/10.5281/
zenodo.11495514 .
• Code and Dataset interface is provided in our GitHub Repository AsEP-dataset athttps:
//github.com/biochunan/AsEP-dataset .
Author Statement
The authors affirm that they bear all responsibility in case of violation of rights, etc., and confirm the
data license. The dataset is licensed under the CC BY 4.0 License ( https://creativecommons.
org/licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License (https://opensource.org/licenses/MIT ).
Hosting, Licensing, and Maintenance Plan
The dataset is hosted on Zenodo, which provides a DOI (10.5281/zenodo.11495514) for the dataset.
It also comes with a Python interface provided in our GitHub Repository, AsEP-dataset at https:
//github.com/biochunan/AsEP-dataset , where users can submit issues and ask questions.
Future releases and updates will be made available through the same channels. As discussed in the
main text, the future plan includes expanding the dataset to include novel types of antibodies, such as
single-domain antibodies, and providing more sophisticated features for graph representations. The
dataset will be maintained by the authors and will be available for a long time.
Links to Access the Dataset and Its Metadata
The dataset, benchmark, and metadata are provided through Zenodo.
25
The Dataset
The dataset is constructed using pytorch-geometric Dataset module. The dataset can be loaded
using the following code:
from asep . data . asepv1_dataset import AsEPv1Evaluator
evaluator = AsEPv1Evaluator ()
# example
torch . manual_seed (0)
y_pred = torch . rand (1000)
y_true = torch . randint (0, 2, (1000 ,) )
input_dict = {’y_pred ’: y_pred , ’y_true ’: y_true }
result_dict = evaluator . eval ( input_dict )
print ( result_dict ) # got {’auc - prc ’: tensor (0.5565) }
We also provide detailed documentation of the dataset content on Zenodo and include a description
below:
•asepv1-AbDb-IDs.txt : A text file containing the AbDb identifiers of the 1723 antibody-
antigen pairs in the dataset.
•asepv1_interim_graphs.tar.gz : Contains 1723 .ptfiles, where each file is a dictio-
nary with structured data:
abdbid A string representing the antibody AbDb identifier.
seqres A dictionary containing:
abAn OrderedDict mapping string chain labels HandLto their corresponding se-
quence strings, representing heavy and light chains respectively.
agA dictionary mapping string chain labels to their corresponding sequence strings.
mapping Includes:
abContains:
seqres2cdr A binary numpy array indicating the CDR positions in the antibody
sequence.
agContains:
seqres2surf A binary numpy array indicating the surface residues in the antigen
sequence.
seqres2epitope A binary numpy array indicating the epitope residues in the
antigen sequence.
embedding Comprises:
abIncludes embeddings computed using the AntiBERTy model and ESM2 model for
the antibody sequences.
agIncludes embeddings for the antigen sequences computed using the ESM2 model.
edges Describes the interactions:
abA sparse coo tensor representing the binary edges between the CDR residues.
agA sparse coo tensor representing the binary edges between the surface residues.
stats Metadata about each antibody-antigen pair, including counts of CDR, surface, and
epitope residues, and the epitope-to-surface ratio.
•structures.tar.gz : Contains 1723 pdb structures, each named using the AbDb identi-
fier.
•split_dict.pt : Contains the train /val/test splits of the dataset, with splits based on
the epitope ratio and epitope group of the antigen.
Long-term Preservation
The current version of the dataset and benchmark are provided through Zenodo, which provides
long-term storage. Future versions will be made available through the same channel and users are
encouraged to submit queries and issues through the issues channel on the GitHub repository.
26
Explicit License
The dataset is licensed under the CC BY 4.0 license ( https://creativecommons.org/
licenses/by/4.0/ ), which is provided through the Zenodo repository. The code is licensed
under the MIT License https://opensource.org/licenses/MIT .
Benchmarks
Detailed benchmark experiments and results are provided on Zenodo ( https://doi.org/10.5281/
zenodo.11495514 ), and the file benchmark.zip contains the instructions on how to reproduce
the results. To run ESMFold, EpiPred, and MaSIF-Site, we provided docker images on the Zenodo
repository or instructions on how to obtain them from DockerHub. The benchmark results are
reproducible by following the instructions provided in the zip file. For the method WALLE and its
variants used in the ablation studies, their configuration YAML files and the trained models are also
provided on Zenodo.
27 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18158v1 | http://arxiv.org/pdf/2407.18158v1 | Unlocking Tokens as Data Points for Generalization Bounds on Larger Language Models | Sanae Lotfi, Yilun Kuang, Brandon Amos, Micah Goldblum, Marc Finzi, Andrew Gordon Wilson | 2024-07-25 | Abstract
Large language models (LLMs) with billions of parameters excel at predicting the next
token in a sequence. Recent work computes non-vacuous compression-based generalization
bounds for LLMs, but these bounds are vacuous for large models at the billion-parameter
scale. Moreover, these bounds are obtained through restrictive compression techniques,
bounding compressed models that generate low-quality text. Additionally, the tightness of
these existing bounds depends on the number of IID documents in a training set rather
than the much larger number of non-IID constituent tokens, leaving untapped potential
for tighter bounds. In this work, we instead use properties of martingales to derive
generalization bounds that benefit from the vast number of tokens in LLM training sets.
Since a dataset contains far more tokens than documents, our generalization bounds not
only tolerate but actually benefit from far less restrictive compression schemes. With
Monarch matrices, Kronecker factorizations, and post-training quantization, we achieve
non-vacuous generalization bounds for LLMs as large as LLaMA2-70B. Unlike previous
approaches, our work achieves the first non-vacuous bounds for models that are deployed
in practice and generate high-quality text.
1 | Introduction
Despite the impressive empirical performance of large language models (LLMs), our theoretical
understanding of their performance is lacking. PAC-Bayes and the related finite hypothesis
generalization bounds [ 5,13,17] offer a compelling framework for understanding this good
performance through the lens of compression. These bounds tell us that a model will provide
good generalization if it is capable of fitting its training data while simultaneously being
compressible relative to the size of its training set. The generalization bounds literature includes
many techniques for achieving tighter bounds on image classification problems, ranging from
improved bounds themselves to new compression methods [53, 14, 18, 38, 31].
Recent work presented the first non-vacuous generalization bounds for large language models,
considering training points to be independent and identically distributed (IID) documents [ 32].
The authors compute generalization bounds for the expected bits-per-dimension (BPD) loss,
defined for a document Xcomposed of ktokens and a language model has the average negative
log probability BPD(h, X) =−1
kPk
ilog2ph(xi|x<i). These bounds are only non-vacuous for
compressed GPT2 variants [ 39] that output un-grammatical text. The term vacuous refers to
∗Equal contribution, order decided by coin flip. Correspondence to: Sanae Lotfi <[email protected]>,
Andrew Gordon Wilson <[email protected]>.
†Meta-affiliated author was involved only in an advisory role. All experimentation and data processing were
conducted at NYU.
1arXiv:2407.18158v1 [stat.ML] 25 Jul 2024
103
104
Compressed Model Size (MB)45678BPD Bound
LLaMA1
LLaMA2
LLaMA2-Chat
103
104
Compressed Model Size (MB)2.62.83.0Train BPD Loss
106
107
Trainable Parameters4567Validation Loss
LoRA
Kronecker
MonarchFigure 1: Non-vacuous bounds for LLMs that scale up to 70B parameters. Left: Bits
per dimension (BPD) bounds on the Amber dataset [ 29] which contains 1.2trillion tokens for
different LLMs from the LLaMA family ranging in scale from 7 billion to 70 billion parameters
[47]. All of these models are quantized to 2-bits, 3-bits and 4-bits per-weight using QuIP#
and are publicly available [ 48]. The different quantization precisions are accounted for in
the compressed model size. The trade-off between the empirical performance and the model
complexity in our bounds favors models with a smaller compressed size in general, though we
observe that across different architectures we can find larger models yielding better bounds.
Middle: The BPD training loss for different models from the LLaMA family—the legend is
shared with the figure on the left. Overall, we observe that larger models yield a lower BPD while
having a higher compressed size. Right:Validation negative log-likelihood loss as a function of
the total number of trainable parameters for different nonlinear parametrization; namely low
rank adaptation (LoRA), the Kronecker decomposition of dense matrices and Monarch matrices.
The x-axis is in the log scale. As we vary the numer of trainable parameters, there are different
optimal compression techniques.
the random guess performance on next token prediction, which is log2Vfor BPD where Vis
the vocabulary size.
Compression-based generalization bounds at the document level suffer from three primary limita-
tions: (1) the number of documents in a training set is limited, and this small sample size leads
to loose bounds; (2) due to the small sample size, non-vacuous generalization bounds can only be
achieved using compression techniques which significantly modify the LLM pretraining routine.
This limitation also applies to state-of-the-art generalization bounds for image classification,
which heavily alter the training procedure to optimize the bounds [ 53,38,31]; (3) as a result,
the models which produce non-vacuous bounds generate low-quality text, so it is unclear what
these bounds can tell us about more performant language models.
In this work, we address the above limitations and use our bounds to derive insights about the
generalization properties and limitations of LLMs. Namely, we make the following contributions:
•In Section 4, we present and derive a generalization bound that considers each sample to
be an individual token. Even though tokens within a document are not independent, we
use properties of martingales to obtain a valid bound that benefits from the number of
tokens in a language model’s pretraining dataset.
•In Sections 5 and 6, we explore several expressive model compression techniques such as
Monarch matrices, Kronecker factorizations, and post-training quantization and show that
bounding the performance at the token-level favors less restrictive compression strategies.
•Our work is the first to compute non-vacuous generalization bounds for models compressed
only through post-training quantization and without altering the pretraining procedure
at all. Consequently, we obtain generalization bounds for massive pretrained LLMs like
LLaMA2-70B, as shown in Figure 1(Left) and Section 6, which generate high-quality text.
2
•Our experiments in Section 6 indicate that the chat versions of LLaMA have looser gener-
alization guarantees, demonstrating that fine-tuning these models for dialogue negatively
affects their performance on the next token prediction task.
•In Section 6.4, we demonstrate that GPT2 models that are restricted to only seeing k
tokens in their context for training and evaluation obtain significantly better bounds
than k-th order Markov chains for high values of k, reflecting the remarkable ability of
transformer-based models in capturing longer range correlations.
•We show in Section 6.5 that a model’s ability to recall memorized facts from its pretraining
data deteriorates faster than its ability to recognize structured patterns as we decrease the
size of the model through compression, distinguishing between compressible tasks where
generalization is possible and incompressible tasks that correspond to sheer memorization.
2 Related Work
Generalization bounds for neural networks. Deep neural networks are challenging to
understand using generalization theory due to their many parameters [ 51]. However, over the
past years, there has been success in constructing meaningful bounds covering image classification
models [13], vision-language models [ 1], and tabular data [ 17], often through the methodology
of compression [ 53,31]. Lotfi et al. [32]extend compression-based generalization bounds to
the LLM setting, and obtain non-vacuous bounds at the document level. Li et al. [27]explore
generalization in few-shot learning, establishing bounds based on in-context examples while
maintaining a fixed pretrained model. In contrast, we investigate pretraining generalization
bounds to understand why models do not overfit at training time, despite the increased dataset
complexity.
Non-IID Generalization bounds. While the vast majority of generalization bounds assume
that the different data points are drawn independently, there are a handful of works that aim to
relax this assumption in different ways. Ralaivola et al. [41]analyze the dependence graph of the
random variables, deriving a bound based on the graph coloring number, fitting into a broader
line of work making use of properties of the dependence graph [ 52]. Unfortunately for text data,
the dependencies are unknown or assumed to follow the triangular autoregressive dependency
structure for all pairs in the sequence, which limits the applicability of such an approach. A
related line of work has been to explicitly estimate coefficients which quantify the extent that
random variables relate to each other [e.g., 33,24]. However, it is unclear how best to apply
these methods to neural networks. Martingale tail bounds are sometimes used in online learning
and reinforcement learning, e.g., for establishing regret bounds [ 40]. Chugg et al. [7]present
a large collection of generalization bounds both in the IID and martingale settings, including
generalization bounds which could be used at the token level such as the one we derive. Their
results extend and generalize many existing bounds. We view our contribution as orthogonal
to these efforts since we focus on constructing the components necessary to generate practical
bounds for LLMs, rather than innovating on concentration inequalities themselves.
Large language models and compression. In recent years, language models went from
millions to billions of parameters, leading to consistent improvements across downstream
applications. A variety of compression techniques have been proposed to account for the
increased computational costs of LLMs while preserving their performance. Parameter-efficient
finetuning methods, such as LoRA [ 19], parametrize weight matrices as products of two trainable
low-rank matrices on top of frozen pretrained weights. QLoRA uses 4-bit NormalFloat (NF4)
and double quantization, enabling single-GPU finetuning for a 65B parameter LLM without
performance degradation [ 10,11]. Post-training quantization approaches, such as GPTQ [ 16],
rely on second-order information and quantize each row of weight matrices independently. QuIP
uses adaptive rounding and incoherence processing of second-order Hessian matrices, enabling
2-bit quantization of LLMs [ 6]. Other compression techniques for LLMs include replacing most of
3
the 16-bit operations with 8-bit matrix multiply [ 10], using data-free distillations [ 28], designing
custom kernels and sub-4-bit integer quantization [ 22,36], and compressing embeddings as
low-rank matrix-product state [50].
3 | Background
In this section, we review the different components of compression-based generalization bounds,
which we build upon with our method in Sections 4 and 5.
Finite | Related Work
Generalization bounds for neural networks. Deep neural networks are challenging to
understand using generalization theory due to their many parameters [ 51]. However, over the
past years, there has been success in constructing meaningful bounds covering image classification
models [13], vision-language models [ 1], and tabular data [ 17], often through the methodology
of compression [ 53,31]. Lotfi et al. [32]extend compression-based generalization bounds to
the LLM setting, and obtain non-vacuous bounds at the document level. Li et al. [27]explore
generalization in few-shot learning, establishing bounds based on in-context examples while
maintaining a fixed pretrained model. In contrast, we investigate pretraining generalization
bounds to understand why models do not overfit at training time, despite the increased dataset
complexity.
Non-IID Generalization bounds. While the vast majority of generalization bounds assume
that the different data points are drawn independently, there are a handful of works that aim to
relax this assumption in different ways. Ralaivola et al. [41]analyze the dependence graph of the
random variables, deriving a bound based on the graph coloring number, fitting into a broader
line of work making use of properties of the dependence graph [ 52]. Unfortunately for text data,
the dependencies are unknown or assumed to follow the triangular autoregressive dependency
structure for all pairs in the sequence, which limits the applicability of such an approach. A
related line of work has been to explicitly estimate coefficients which quantify the extent that
random variables relate to each other [e.g., 33,24]. However, it is unclear how best to apply
these methods to neural networks. Martingale tail bounds are sometimes used in online learning
and reinforcement learning, e.g., for establishing regret bounds [ 40]. Chugg et al. [7]present
a large collection of generalization bounds both in the IID and martingale settings, including
generalization bounds which could be used at the token level such as the one we derive. Their
results extend and generalize many existing bounds. We view our contribution as orthogonal
to these efforts since we focus on constructing the components necessary to generate practical
bounds for LLMs, rather than innovating on concentration inequalities themselves.
Large language models and compression. In recent years, language models went from
millions to billions of parameters, leading to consistent improvements across downstream
applications. A variety of compression techniques have been proposed to account for the
increased computational costs of LLMs while preserving their performance. Parameter-efficient
finetuning methods, such as LoRA [ 19], parametrize weight matrices as products of two trainable
low-rank matrices on top of frozen pretrained weights. QLoRA uses 4-bit NormalFloat (NF4)
and double quantization, enabling single-GPU finetuning for a 65B parameter LLM without
performance degradation [ 10,11]. Post-training quantization approaches, such as GPTQ [ 16],
rely on second-order information and quantize each row of weight matrices independently. QuIP
uses adaptive rounding and incoherence processing of second-order Hessian matrices, enabling
2-bit quantization of LLMs [ 6]. Other compression techniques for LLMs include replacing most of
3
the 16-bit operations with 8-bit matrix multiply [ 10], using data-free distillations [ 28], designing
custom kernels and sub-4-bit integer quantization [ 22,36], and compressing embeddings as
low-rank matrix-product state [50].
3 Background
In this section, we review the different components of compression-based generalization bounds,
which we build upon with our method in Sections 4 and 5.
Finite | Section not found | Section not found | Section not found | Section not found | hypothesis
generalization bounds [ 5,13,17] offer a compelling framework for understanding this good
performance through the lens of compression. These bounds tell us that a model will provide
good generalization if it is capable of fitting its training data while simultaneously being
compressible relative to the size of its training set. The generalization bounds literature includes
many techniques for achieving tighter bounds on image classification problems, ranging from
improved bounds themselves to new compression methods [53, 14, 18, 38, 31].
Recent work presented the first non-vacuous generalization bounds for large language models,
considering training points to be independent and identically distributed (IID) documents [ 32].
The authors compute generalization bounds for the expected bits-per-dimension (BPD) loss,
defined for a document Xcomposed of ktokens and a language model has the average negative
log probability BPD(h, X) =−1
kPk
ilog2ph(xi|x<i). These bounds are only non-vacuous for
compressed GPT2 variants [ 39] that output un-grammatical text. The term vacuous refers to
∗Equal contribution, order decided by coin flip. Correspondence to: Sanae Lotfi <[email protected]>,
Andrew Gordon Wilson <[email protected]>.
†Meta-affiliated author was involved only in an advisory role. All experimentation and data processing were
conducted at NYU.
1arXiv:2407.18158v1 [stat.ML] 25 Jul 2024
103
104
Compressed Model Size (MB)45678BPD Bound
LLaMA1
LLaMA2
LLaMA2-Chat
103
104
Compressed Model Size (MB)2.62.83.0Train BPD Loss
106
107
Trainable Parameters4567Validation Loss
LoRA
Kronecker
MonarchFigure 1: Non-vacuous bounds for LLMs that scale up to 70B parameters. Left: Bits
per dimension (BPD) bounds on the Amber dataset [ 29] which contains 1.2trillion tokens for
different LLMs from the LLaMA family ranging in scale from 7 billion to 70 billion parameters
[47]. All of these models are quantized to 2-bits, 3-bits and 4-bits per-weight using QuIP#
and are publicly available [ 48]. The different quantization precisions are accounted for in
the compressed model size. The trade-off between the empirical performance and the model
complexity in our bounds favors models with a smaller compressed size in general, though we
observe that across different architectures we can find larger models yielding better bounds.
Middle: The BPD training loss for different models from the LLaMA family—the legend is
shared with the figure on the left. Overall, we observe that larger models yield a lower BPD while
having a higher compressed size. Right:Validation negative log-likelihood loss as a function of
the total number of trainable parameters for different nonlinear parametrization; namely low
rank adaptation (LoRA), the Kronecker decomposition of dense matrices and Monarch matrices.
The x-axis is in the log scale. As we vary the numer of trainable parameters, there are different
optimal compression techniques.
the random guess performance on next token prediction, which is log2Vfor BPD where Vis
the vocabulary size.
Compression-based generalization bounds at the document level suffer from three primary limita-
tions: (1) the number of documents in a training set is limited, and this small sample size leads
to loose bounds; (2) due to the small sample size, non-vacuous generalization bounds can only be
achieved using compression techniques which significantly modify the LLM pretraining routine.
This limitation also applies to state-of-the-art generalization bounds for image classification,
which heavily alter the training procedure to optimize the bounds [ 53,38,31]; (3) as a result,
the models which produce non-vacuous bounds generate low-quality text, so it is unclear what
these bounds can tell us about more performant language models.
In this work, we address the above limitations and use our bounds to derive insights about the
generalization properties and limitations of LLMs. Namely, we make the following contributions:
•In Section 4, we present and derive a generalization bound that considers each sample to
be an individual token. Even though tokens within a document are not independent, we
use properties of martingales to obtain a valid bound that benefits from the number of
tokens in a language model’s pretraining dataset.
•In Sections 5 and 6, we explore several expressive model compression techniques such as
Monarch matrices, Kronecker factorizations, and post-training quantization and show that
bounding the performance at the token-level favors less restrictive compression strategies.
•Our work is the first to compute non-vacuous generalization bounds for models compressed
only through post-training quantization and without altering the pretraining procedure
at all. Consequently, we obtain generalization bounds for massive pretrained LLMs like
LLaMA2-70B, as shown in Figure 1(Left) and Section 6, which generate high-quality text.
2
•Our experiments in Section 6 indicate that the chat versions of LLaMA have looser gener-
alization guarantees, demonstrating that fine-tuning these models for dialogue negatively
affects their performance on the next token prediction task.
•In Section 6.4, we demonstrate that GPT2 models that are restricted to only seeing k
tokens in their context for training and evaluation obtain significantly better bounds
than k-th order Markov chains for high values of k, reflecting the remarkable ability of
transformer-based models in capturing longer range correlations.
•We show in Section 6.5 that a model’s ability to recall memorized facts from its pretraining
data deteriorates faster than its ability to recognize structured patterns as we decrease the
size of the model through compression, distinguishing between compressible tasks where
generalization is possible and incompressible tasks that correspond to sheer memorization.
2 Related Work
Generalization bounds for neural networks. Deep neural networks are challenging to
understand using generalization theory due to their many parameters [ 51]. However, over the
past years, there has been success in constructing meaningful bounds covering image classification
models [13], vision-language models [ 1], and tabular data [ 17], often through the | Section not found | methodology
of compression [ 53,31]. Lotfi et al. [32]extend compression-based generalization bounds to
the LLM setting, and obtain non-vacuous bounds at the document level. Li et al. [27]explore
generalization in few-shot learning, establishing bounds based on in-context examples while
maintaining a fixed pretrained model. In contrast, we investigate pretraining generalization
bounds to understand why models do not overfit at training time, despite the increased dataset
complexity.
Non-IID Generalization bounds. While the vast majority of generalization bounds assume
that the different data points are drawn independently, there are a handful of works that aim to
relax this assumption in different ways. Ralaivola et al. [41]analyze the dependence graph of the
random variables, deriving a bound based on the graph coloring number, fitting into a broader
line of work making use of properties of the dependence graph [ 52]. Unfortunately for text data,
the dependencies are unknown or assumed to follow the triangular autoregressive dependency
structure for all pairs in the sequence, which limits the applicability of such an approach. A
related line of work has been to explicitly estimate coefficients which quantify the extent that
random variables relate to each other [e.g., 33,24]. However, it is unclear how best to apply
these | methods [53, 14, 18, 38, 31].
Recent work presented the first non-vacuous generalization bounds for large language models,
considering training points to be independent and identically distributed (IID) documents [ 32].
The authors compute generalization bounds for the expected bits-per-dimension (BPD) loss,
defined for a document Xcomposed of ktokens and a language model has the average negative
log probability BPD(h, X) =−1
kPk
ilog2ph(xi|x<i). These bounds are only non-vacuous for
compressed GPT2 variants [ 39] that output un-grammatical text. The term vacuous refers to
∗Equal contribution, order decided by coin flip. Correspondence to: Sanae Lotfi <[email protected]>,
Andrew Gordon Wilson <[email protected]>.
†Meta-affiliated author was involved only in an advisory role. All experimentation and data processing were
conducted at NYU.
1arXiv:2407.18158v1 [stat.ML] 25 Jul 2024
103
104
Compressed Model Size (MB)45678BPD Bound
LLaMA1
LLaMA2
LLaMA2-Chat
103
104
Compressed Model Size (MB)2.62.83.0Train BPD Loss
106
107
Trainable Parameters4567Validation Loss
LoRA
Kronecker
MonarchFigure 1: Non-vacuous bounds for LLMs that scale up to 70B parameters. Left: Bits
per dimension (BPD) bounds on the Amber dataset [ 29] which contains 1.2trillion tokens for
different LLMs from the LLaMA family ranging in scale from 7 billion to 70 billion parameters
[47]. All of these models are quantized to 2-bits, 3-bits and 4-bits per-weight using QuIP#
and are publicly available [ 48]. The different quantization precisions are accounted for in
the compressed model size. The trade-off between the empirical performance and the model
complexity in our bounds favors models with a smaller compressed size in general, though we
observe that across different architectures we can find larger models yielding better bounds.
Middle: The BPD training loss for different models from the LLaMA family—the legend is
shared with the figure on the left. Overall, we observe that larger models yield a lower BPD while
having a higher compressed size. Right:Validation negative log-likelihood loss as a function of
the total number of trainable parameters for different nonlinear parametrization; namely low
rank adaptation (LoRA), the Kronecker decomposition of dense matrices and Monarch matrices.
The x-axis is in the log scale. As we vary the numer of trainable parameters, there are different
optimal compression techniques.
the random guess performance on next token prediction, which is log2Vfor BPD where Vis
the vocabulary size.
Compression-based generalization bounds at the document level suffer from three primary limita-
tions: (1) the number of documents in a training set is limited, and this small sample size leads
to loose bounds; (2) due to the small sample size, non-vacuous generalization bounds can only be
achieved using compression techniques which significantly modify the LLM pretraining routine.
This limitation also applies to state-of-the-art generalization bounds for image classification,
which heavily alter the training procedure to optimize the bounds [ 53,38,31]; (3) as a result,
the models which produce non-vacuous bounds generate low-quality text, so it is unclear what
these bounds can tell us about more performant language models.
In this work, we address the above limitations and use our bounds to derive insights about the
generalization properties and limitations of LLMs. Namely, we make the following contributions:
•In Section 4, we present and derive a generalization bound that considers each sample to
be an individual token. Even though tokens within a document are not independent, we
use properties of martingales to obtain a valid bound that benefits from the number of
tokens in a language model’s pretraining dataset.
•In Sections 5 and 6, we explore several expressive model compression techniques such as
Monarch matrices, Kronecker factorizations, and post-training quantization and show that
bounding the performance at the token-level favors less restrictive compression strategies.
•Our work is the first to compute non-vacuous generalization bounds for models compressed
only through post-training quantization and without altering the pretraining procedure
at all. Consequently, we obtain generalization bounds for massive pretrained LLMs like
LLaMA2-70B, as shown in Figure 1(Left) and Section 6, which generate high-quality text.
2
•Our experiments in Section 6 indicate that the chat versions of LLaMA have looser gener-
alization guarantees, demonstrating that fine-tuning these models for dialogue negatively
affects their performance on the next token prediction task.
•In Section 6.4, we demonstrate that GPT2 models that are restricted to only seeing k
tokens in their context for training and evaluation obtain significantly better bounds
than k-th order Markov chains for high values of k, reflecting the remarkable ability of
transformer-based models in capturing longer range correlations.
•We show in Section 6.5 that a model’s ability to recall memorized facts from its pretraining
data deteriorates faster than its ability to recognize structured patterns as we decrease the
size of the model through compression, distinguishing between compressible tasks where
generalization is possible and incompressible tasks that correspond to sheer memorization.
2 Related Work
Generalization bounds for neural networks. Deep neural networks are challenging to
understand using generalization theory due to their many parameters [ 51]. However, over the
past years, there has been success in constructing meaningful bounds covering image classification
models [13], vision-language models [ 1], and tabular data [ 17], often through the methodology
of compression [ 53,31]. Lotfi et al. [32]extend compression-based generalization bounds to
the LLM setting, and obtain non-vacuous bounds at the document level. Li et al. [27]explore
generalization in few-shot learning, establishing bounds based on in-context examples while
maintaining a fixed pretrained model. In contrast, we investigate pretraining generalization
bounds to understand why models do not overfit at training time, despite the increased dataset
complexity.
Non-IID Generalization bounds. While the vast majority of generalization bounds assume
that the different data points are drawn independently, there are a handful of works that aim to
relax this assumption in different ways. Ralaivola et al. [41]analyze the dependence graph of the
random variables, deriving a bound based on the graph coloring number, fitting into a broader
line of work making use of properties of the dependence graph [ 52]. Unfortunately for text data,
the dependencies are unknown or assumed to follow the triangular autoregressive dependency
structure for all pairs in the sequence, which limits the applicability of such an approach. A
related line of work has been to explicitly estimate coefficients which quantify the extent that
random variables relate to each other [e.g., 33,24]. However, it is unclear how best to apply
these methods to neural networks. Martingale tail bounds are sometimes used in online learning
and reinforcement learning, e.g., for establishing regret bounds [ 40]. Chugg et al. [7]present
a large collection of generalization bounds both in the IID and martingale settings, including
generalization bounds which could be used at the token level such as the one we derive. Their | Section not found | Section not found | Section not found | results extend and generalize many existing bounds. We view our contribution as orthogonal
to these efforts since we focus on constructing the components necessary to generate practical
bounds for LLMs, rather than innovating on concentration inequalities themselves.
Large language models and compression. In recent years, language models went from
millions to billions of parameters, leading to consistent improvements across downstream
applications. A variety of compression techniques have been proposed to account for the
increased computational costs of LLMs while preserving their performance. Parameter-efficient
finetuning methods, such as LoRA [ 19], parametrize weight matrices as products of two trainable
low-rank matrices on top of frozen pretrained weights. QLoRA uses 4-bit NormalFloat (NF4)
and double quantization, enabling single-GPU finetuning for a 65B parameter LLM without
performance degradation [ 10,11]. Post-training quantization approaches, such as GPTQ [ 16],
rely on second-order information and quantize each row of weight matrices independently. QuIP
uses adaptive rounding and incoherence processing of second-order Hessian matrices, enabling
2-bit quantization of LLMs [ 6]. Other compression techniques for LLMs include replacing most of
3
the 16-bit operations with 8-bit matrix multiply [ 10], using data-free distillations [ 28], designing
custom kernels and sub-4-bit integer quantization [ 22,36], and compressing embeddings as
low-rank matrix-product state [50].
3 Background
In this section, we review the different components of compression-based generalization bounds,
which we build upon with our method in Sections 4 and 5.
Finite hypothesis compression bounds. LetR(h, x)∈[a, a+ ∆]be a bounded risk and
h∈ Hbe a hypothesis drawn from a finite hypothesis space with prior P(h). A classic finite
hypothesis generalization bound [43] states that for any δ >0with probability 1−δ,
R(h)≤ˆR(h) + ∆r
log 1/P(h) + log 1 /δ
2m(1)
where the empirical risk is defined as ˆR(h) :=1
mPm
i=1R(h, xi)with{xi}m
i=1being IID and
R(h) =E[ˆR(h)]. The complexity term depends on the prior log probability log1/P(h). We
use the Solomonoff prior P(h)≤2−K(h)[45], where K(h)is the prefix Kolmogorov complexity
ofhdefined as the length of the shortest program that produces hfor a fixed programming
language [ 23]. Consequently, our prior favors models hthat have a small minimum compressed
length. While the Kolmogorov complexity is incomputable, it can be bounded as log1/P(h)≤
K(h)log2≤C(h)log2+2logC(h), where C(h)is the compressed size of the model according to
a pre-specified compressor. Therefore, we can find the right trade-off between the empirical risk
and the compressed size of the model by tuning the extent of compression, hence the different
compression techniques we explore in this work.
Compression bounds for LLMs. When constructing document-level bounds for language,
the empirical risk is defined over an entire document XasR(h, X) =−log2ph(X)/L, where
ph(X)is defined auto-regressively on the sequence of tokens X= [x1, x2, . . . x L]aspθ(X) =QL
i=1ph(xi|x<i), where x<idenotes x1, x2, . . . , x i−1.
Prediction smoothing. Since the bound in Equation (1) only applies to a bounded risk, it is
not valid for the bits-per-dimension loss that is unbounded. In this case, one can introduce a
prediction smoothing probability αto the predictive model such that the generative probability
distribution becomes a mixture between the next token probability according to the auto-
regressive model f(θ)with parameters θand a uniform distribution over the vocabulary of size
Vas follows: ph(xi|x<i) = (1 −α)pθ(xi|x<i) +α/V. With this construction, R(h, X)can be
bounded in an interval of size ∆ = log2(1 + (1 −α)V/α). The optimal hyperparameter αis
determined via a grid search in Lotfi et al. [32].
Compressing LLMs with SubLoRA. To achieve the extreme compression level necessary
to obtain non-vacuous document-level bounds, Lotfi et al. [32]propose SubLoRA, a non-linear
subspace parametrization of an LLM’s weights θ. Using SubLoRA, these weights can be written
asθ=θ0+LoRA (Pw). Here θ0∈RDare the model weights at random initialization and
LoRA (Pw)combines low-rank adaptation (LoRA) [ 19] with subspace training [ 31] via the
projector P∈RD×d. The LoRA decomposition parameterizes a dense matrix W∈Ra×b
as the product of two low-rank matrices A∈Ra×r, B∈Rr×bwith a small rank r. As for
the linear subspace parametrization Pw, the projection matrix Pis defined as a Kronecker
product P=Q1⊗Q2produced by orthogonalizing Q1, Q2∼ N (0,1/√
D)√
D×√
dvia a QR
decomposition.
In practice, a selected subset of the dense matrices in an LLM are parameterized using LoRA’s
low rank matrices, then the concatenation of LoRA’s matrices is projected into the subspace
parameters wusing P. The model is therefore effectively trained via the weights w∈Rd. As a
result, the model can be coded via a random seed that reproduces the pre-fixed initialization θ0
4
and projection matrix P, and a coding of wwhich is performed using arithmetic coding [ 25].
The dimension dofwcan be varied to achieve the best trade-off between empirical risk and
complexity, and these degrees of freedom are accounted for in the coding of the hypothesis h.
4 Token-Level Generalization Bounds
In order to unlock a deeper understanding of LLM generalization, it is not sufficient to consider
the training data at the level of entire documents. In fact, token-level performance is arguably
what we care about most when evaluating a model’s generalization on its next token prediction
pretraining task. Moreover, simplifying the bounds to meet the IID assumption over sampled
documents restricts our ability to capture the dependencies between individual tokens. In this
section, we derive novel bounds at the token level through a simple yet powerful application of
Azuma’s inequality that allows us to use the properties of martingales to go beyond the IID
setting. Then, we discuss the interpretation of our bounds and demonstrate their ability to
predict generalization on downstream tasks. Finally, we introduce a new optimization strategy
for tuning a prediction smoothing hyperparameter that further improves our bounds.
4.1 A Novel Non-IID Token-Level Generalization Bound
In deriving token-level bounds, one might consider applying Equation (1) to the finite dataset
D={(x<i, xi)}M
i=1composed of input and output pairs. In this scenario, model training can be
performed on a random subset S⊂ Dofmpairs, which differs from how training is usually
performed via contiguous sequences. Then, we could use the performance on Sto bound the
average performance on Dsince Sis constructed as an IID sample from D. While these bounds
are valid, they require fundamentally altering the training procedure, and they only pertain
to the held out pairs which must be collected in advance and separated from their naturally
occurring context.
To avoid these limitations, we construct a novel bound that naturally accommodates the non-IID
structure of the tokens as they occur in documents as follows:
Theorem 1. With probability at least 1−δover the randomness in a sampled sequence
{x1, x2, . . . , x m}, if the negative log likelihood of a model h∈ Hcan be bounded −log2ph(·|x<i)∈
[a, a+ ∆ i], then the negative log likelihood of the data for model hsatisfies
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m,(2)
where ˆ∆=q
1
mPm
i=1∆2
i, the expectation is taken over Xi∼p(Xi|x<i)from the data generating
process, and P(h)is any normalized prior over a discrete hypothesis space Hthat does not
depend on {xi}m
i=1.
We provide a proof sketch as well as the full proof in Appendix A.1.
On the right-hand side of the bound is the conventional empirical risk: −1
mlog2ph(x≤m) =
−1
mP
ilog2ph(xi|x<i)onthemeasuredsequenceandacomplexityterm log1/P(h). Wedescribe
in detail how we sample sequence x≤mand compute the empirical risk in Section 4.2. The
quantity which we are bounding on the left-hand side is the expected next token negative
log-likelihood under resampling from the data generating process, averaged over the different
contexts that have been encountered in the training set. The bound ensures generalization on
contexts seen at training when the next tokens are resampled, but not on data with contexts
that are different. However, given how diffuse the distribution over next tokens is, e.g., at the
beginning of a new sentence, our bounds remain predictive of generalization and achieving a
non-vacuous bound requires generalization. We further discuss the interpretation of our bounds
in Section 4.3.
5
2 4 6
Entropy0100002000030000Frequency
0248161282565127681023
Token Index02468Entropy
108
109
Trainable Parameters20406080100120PPL / Acc (%)PPL
BPDACC
4.04.24.44.64.85.0
Bound Objective (BPD)Figure 2: Our bounds analyze a quantity that is meaningful and predictive of
generalization. Left: Using LLaMA2-7B, we compute the entropy of p(xi|x<i), where the
context x<iis fixed and sampled from the Amber training dataset. The distribution over next
tokens given a fixed context from the training data is indeed diffuse and characterized by high
entropy values. Middle: Entropy of p(xi|x<i)as a function of the token index ishown on the
x-axis for a context length L= 1024. The average entropy has a decreasing trend but remains
high overall; note that the average entropy for i= 768is as high as the average entropy for
i= 128.Right:On the left y-axis, we plot the average zero-shot accuracy (ACC) and perplexity
(PPL) achieved by GPT2 models ranging in scale from 117M to 1.5B averaged over downstream
datasets, as reported in Radford et al. [39]. On the right y-axis, we plot an approximation of
the conditional BPD expectation that we bound in Equation (2) where we resample xifrom a
LLaMA2-7B given fixed training contexts x<ifrom the Amber dataset. The approximation of
the BPD objective that we bound achieves 97.9%and99.1%correlation with the accuracy and
perplexity, respectively.
4.2 Sampling and Empirical Risk Evaluation
In this section, we more precisely define the sequence x≤mfor which we compute the empirical
risk in Equation (2). We construct a sample x≤mfrom the stochastic process pdataby first
sampling independent and identically distributed documents, e.g., the documents that form
the OpenWebText dataset. Then, we concatenate these documents deterministically using end
of text (EOT) tokens. Consequently, the ground truth stochastic process has the following
property:
pdata(xi|x<i) =pdata(xi|xk, ...., x i−1), (3)
where xkis the previous EOT token. This equality holds exactly due to how the stochastic
process is implemented.
On the other hand, it would not be guaranteed that a generative model ph(x)satisfies the
property in Equation (3) apriori if the model were allowed to attend to tokens x<k, even when
the data generating process has this property. However, we explicitly prohibit our generative
model hfrom attending to tokens x<kthrough the attention mask, as we have the flexibility to
do so in defining our hypothesis class and model family. Therefore, our model phthat we bound
also satisfies this property ph(xi|x<i) =ph(xi|xk, ...., x i−1)exactly, and not approximately.
In conclusion, the empirical risk for our generative model hand a sequence x≤msampled from
the stochastic process defined above can be written as follows:
−1
mlog2ph(x≤m) =−1
mX
ilog2ph(xi|x<i) =−1
mX
ilog2ph(xi|xk, . . . x i−1),
where xkis the nearest EOT token occurring before xi. Given the large size of the OpenWebText
and Amber datasets, containing 9 billions and 1.2 trillion tokens respectively, we use subsampling
for the evaluation of the empirical risk. More details can be found in Appendix A.2.
6
4.3 Token-level Bounds Are Predictive of Generalization
Token-level vs. document-level bounds. In contrast to document-level bounds, token-level
bounds increase the number of samples, driving down the size of the complexity term, and
do not require the IID assumption. Whereas the number of samples previously would be the
number of documents, it is now simply the number of tokens in the dataset, a far higher
number. As a consequence of decreasing the complexity term, the empirical risk will be a more
significant contributor to our bounds compared to document-level bounds. Therefore, we achieve
non-vacuous bounds for much larger and more performant models that generate high-quality
text. This development brings our theoretical bounds much closer to aligning with empirical
generalization.
Interpretation of token-level bounds. It is important to note the difference between the
quantity that we bound1
mPm
i=1E[−log2ph(Xi|x<i)|x<i], which is conditioned on contexts
seen at training, and the expected risk E[−log2ph(Xi|x<i)]under resampling from the data
generating process where new contexts can be sampled from this process. However, the
resampled next tokens xi|x<iare not necessarily from the training set, and to the extent that
the distribution over next tokens is entropic, we are measuring a different quantity than the
empirical training performance of the hypothesis h. Moreover, we know that the distribution
over next tokens is often indeed diffuse; for instance, many words have common synonyms. The
distribution over next tokens is especially diffuse when we start a new sentence, for example. We
demonstrate how diffuse the distribution p(xi|x<i)is for fixed contexts x<ifrom the publicly
available Amber training dataset [ 29] (see Appendix B.7) by sampling xi|x<iusing LLaMA2-7B
to approximate the generative process. Figure 2(Left) shows that, indeed, the distribution
p(xi|x<i)is characterized by a high entropy for a large number of tokens. In Figure 2(Middle),
we plot the entropy of p(xi|x<i)for each index iin a context of length 1024. This figure
confirms our intuition that the next token distribution is particularly diffuse at the beginning of
a sentence, while it decreases for later tokens but remains relatively high. Given how diffuse
the distribution is and the large number of possible sentences, it is broadly infeasible to make
predictions on new resampled tokens from the empirical distribution alone.
Our bounds are predictive of downstream performance. We compute an approximation
of the quantity that we bound in Equation (2) by sampling next tokens xiusing LLaMA2-7B
given fixed contexts x<ifrom the Amber dataset. We plot this quantity on the right y-axis of
Figure 2(Right), and show on the left y-axis the performance of GPT2 models of varying sizes
on downstream datasets as reported in Radford et al. [39]; see Appendix B.4 for more details.
Not only does the approximation of the BPD objective show the same trend as the downstream
performance for different GPT2 variants, but it also achieves 97.9%and99.1%correlation [ 4]
with downstream task accuracy and perplexity metrics, respectively.
In short, our bounds go significantly beyond the observation that the empirical distribution
converges to the true distribution, and are predictive of generalization on downstream tasks.
Achieving a non-vacuous token-level bound requires generalization. We provide further interpre-
tation of the bounds, including a protein application, in Section 6.
4.4 Token-Level Prediction Smoothing
Rather than using a single label smoothing αfor all data points, we propose to use the
network itself to determine which tokens warrant more confidence and which ones require more
smoothing to limit their worst-case behavior. We perform token-level prediction smoothing
by adding a linear head to the LLM that outputs the probability αfor each token, such that
ph(xi|x<i) =
1−αθ(x<i)
pθ(xi|x<i) +αθ(x<i)/V. The training objective corresponds to the
upper bound in Equation (2) rather than the empirical risk alone, where the αparameter factors
into the bound via the interval size ∆i= log2
1 + (1 −αθ(x<i))V/α θ(x<i)
. Therefore, the
values of αθ(x<i)are adjusted to achieve the best trade-off between the empirical risk and
7
106
107
Trainable Parameters8.59.510.5Bound Loss
Before Optimization
After Optimization
104
103
102
101
Prediction smoothing ()
8.08.48.8BPD Bound
Grid Search
Token-Dependent
0.05 0.10 0.15
Prediction smoothing ()
0500100015002000Empirical DistributionFigure 3: Token-level prediction smoothing improves our bounds. Left: After training,
we optimize a conservative upper bound on the generalization bound that we would get from
Equation (2) with respect to the αhead parameters. Doing so yields a noticeable reduction
in the value of the bound. Middle: BPD generalization bound as a function of a single
global parameter chosen from a discrete number of values vs. the generalization bound for the
token-dependent αafter optimization. Right:Histogram of the values taken by α(x<i)over
different inputs.
the compressed model size. We perform this optimization post-training using a subset of the
training dataset.
We demonstrate in Figure 3(Left) that using this token-dependent αsignificantly improves the
value of the bounds. In Figure 3 (Middle), we compare to the setting where the optimal α
is obtained through a grid search, and in Figure 3(Right) we examine the distribution of α
produced by the model.
5 Compressing LLMs to Minimize Complexity
In shifting from document-level to token-level bounds, the number of data points mincreases
considerably, and thus we can afford to pay significantly more bits in the complexity of the
compressed model. In this new regime, the SubLoRA compression technique, which consists of
training only a linear subspace of LoRA-parameterized weights in the attention layers, becomes
very restrictive. Therefore, we explore other less restrictive forms of compression.
5.1 Efficient Nonlinear Parametrizations
In addition to LoRA, we explore two expressive nonlinear parametrizations f(θ)that make
efficient use of the parameter space: Kronecker structures [ 15] and Monarch matrices [ 9]. We
can use these nonlinear parametrizations directly, or in conjunction with subspace compression,
parametrizing the full parameters as θ=θ0+f(Pw)for a projection matrix P∈RD×d. After
training, the parameters are quantized and coded using arithmetic coding. We describe these
structures below.
LoRA.With LoRA [ 19], the weight matrices of linear layers are parametrized via low rank
updates. Each weight matrix W∈Ra×bis parametrized W=W0+ABforA∈Ra×r, B∈Rr×b
with a small rank r, where W0is given by the initialization and A,Bform the trainable
parameters in each layer. Rather than considering only self-attention layer weights [ 19,32], we
extend SubLoRA to all linear layers in the model and compress the biases and layernorm weights
in the subspace projection. We define f(θ) =LoRA (θ)as the transformation that unpacks θ
intoAandB, multiplies the low rank matrices and adding the initialization to form Wand
reshaping them into the parameters in the usual way.
Kronecker Product. We can represent Was a Kronecker product W=A⊗B, where ⊗
is the Kronecker product, A∈Ra1×b1, B∈Ra2×b2anda1a2=a,b1b2=b, which reduces the
8
parameters over the dense layer. This approach has been used in recent work for parameter-
efficient finetuning [ 15] and as an alternative structure for pretraining. Similarly to LoRA, we
define f(θ) = Kron( θ)as this parametrization for all linear layers.
Monarch Matrices. We also consider Monarch matrices [ 9], which employ two block diagonal
matrices A, and Btypically with AandBformed by√ablocks of size√a×√
band a reshape or
permutation operation R:W=ARB. The matrix multiplication is implemented by reshaping
the input axis ainto(√a,√a), applying matrix Aas a batched matrix multiply on one axis,
and then applying Bto the other axis by permuting the axes. Monarch matrices have shown
considerable promise as an expressive and hardware-efficient replacement for linear layers. We
define f(θ) = Monarch( θ)for their application to each of the linear layers in the network.
In our experiments, we apply all three compression techniques, with and without subspace
compression, to all linear layers in the models.
5.2 QuIP 2-Bit Quantization of LLM
In addition to pretraining LLMs in efficient nonlinear subspaces, we explore recent post-training
quantization methods to reduce the model complexity. Quantization with Incoherence Process
(QuIP) compresses LLM weights to a smaller number of bits while preserving model performance
[6].
Adaptive Rounding. For a weight matrix W∈Ra×b, QuIP minimizes the proxy quadratic
objective ℓ(ˆW) =E[∥(ˆW−W)x∥2] =tr((ˆW−W)H(ˆW−W)⊤), where ˆW∈Ra×bare the
quantized weights, x∈Rbis a vector drawn randomly from a calibration set, and His the
second moment matrix of these vectors used as a proxy Hessian [6].
Incoherence Processing. Based on the observation that incoherences between the weights W
and the proxy Hessian Hbenefit quantization, QuIP further applies incoherence post-processing
using Kronecker products of random orthogonal matrices U∈Ra×a, V∈Rb×bsuch that
˜H←V HV⊤,˜W←UWV⊤. Here U=U1⊗ ··· ⊗ UkandV=V1⊗ ··· ⊗ Vk.
Subsequent work like QuIP# improves upon QuIP by using randomized Hadamard transform
and vector quantizations [ 48]. To compute the compressed size C(h)of QuIP-quantized models,
we use gzip[12] to compress the quantized model checkpoint and obtain the term C(h)as the
bits required for the storage afterwards.
6Non-Vacuous Bounds for LLMs with Billions of Parame-
ters
As described in the previous section, we compute generalization bounds for: (i) models that are
trained through non-linear subspace compression in the form of LoRA, Kronecker product or
Monarch matrices on the OpenWebText dataset, then quantized using the same setup as Lotfi
et al.[32], or (ii) models that are pretrained on a dataset other than the OpenWebText dataset
– or on datasets that might have the OpenWebText as a subset– and made publicly available.
For the pretrained models, we either apply aggressive quantization, which is the case for GPT2,
or use QuIP 2-bit, 3-bit and 4-bit publicly-available quantized models, which is the case for
LLaMA. In the pretrained LLMs setting, we evaluate our bounds for both the OpenWebText
(9B tokens) and Amber (1.2T tokens) datasets. In both settings, we obtain highly compressed
models that lead to non-vacuous generalization bounds.
In addition to reporting generalization bounds on BPD, we also report the bounds that we
obtain on the Top-1, Top-10 and Top-100 error. The Top- kerror refers to the 0-1error in
predicting the next token among the top- kpredictions of the model. For instance, the Top-1
error for token xiis defined as 1[argmax xjp(xj|x<i=x<i) =xi], where argmaxoperates over
tokens xjacross the vocabulary. We extend this definition to the Top-k error and define it
9
Compression Approach BPD Bound Top-1 Error Top-10 Error Top-100 Error
SubLoRA [32] 10.49 90.44 71.33 49.77
Enhanced SubLoRA (Ours) 10.44 89.38 69.54 49.84
Enhanced LoRA (Ours) 7.85 78.15 52.48 31.64
Monarch Only (Ours) 7.65 75.87 47.47 28.34
Kronecker Only (Ours) 8.03 80.80 52.77 30.14
Kronecker + Subspace (Ours) 10.02 88.75 67.91 47.14
Random Guess 15.62 99.99 99.98 99.80
Table 1:Non-vacuous generalization bounds using different compression techniques
for GPT2 pretraining. We find that with the larger complexity budget afforded by the
token-level bounds, subspace compression is no longer necessary or even beneficial for the bounds.
Of the structures we consider, the Monarch parametrization performs best.
as1[xi∈argmax xj,kp(xj|x<i=x<i)], where the argmaxoperator here selects the top- ktokens
predicted by the model according to its next token probability distribution p(xj|x<i=x<i).
Our bound in Equation (2) applies not only to the log likelihood but to any bounded risk, and
therefore can be computed for the Top- kerror since it is bounded between 0and1. We call a
Top-kerror bound vacuous when the bound is larger than the random guess top- kerror equal
to1−k/V, where Vis the vocabulary size.
We present our bounds in this section and contrast the quality of the text generated by our
best performing model in terms of the BPD bound to the text generated by Lotfi et al. [32]’s
best performing model. We also compute token-level generalization bounds for antibody design,
a task where conditioning on contexts from the training dataset arises naturally. Finally, we
investigate the effect of aggressive compression on memorization vs. reasoning in LLMs. We
provide all the experimental details in Appendix B.
6.1 Token-level Bounds via Nonlinear Parametrizations
As discussed in Section 5.1, we experiment with LoRA in addition to the Kronecker and
Monarch subspace parametrizations in order to train compressed versions of GPT2 small (124M
parameters). Compared to previous work, we enhance both LoRA and SubLoRA by not only
applying the low-rank decomposition to the attention layers and the linear head, but to all the
fully-connected layers in the LLM. Additionally, we train all the bias and layer normalization
parameters instead of keeping them fixed at their values at initialization. We also use rotary
position embeddings [ 46] to directly encode the positional information into the LLM. Combined
with our proposed token-level optimization of the label smoothing probability α, we significantly
improve upon the LoRA subspace compression, as shown in Table 1. It is worth noting the
LoRA alone led to vacuous BPD document-level bounds in Lotfi et al. [32]while our version is
non-vacuous.
Among all subspace compression strategies that we explore in Table 1, Monarch without subspace
leads to the tightest token-level bound. In fact, the substantial scale of our dataset, comprising 9
billion tokens, significantly changes the trade-off between the empirical risk and the compressed
model size compared to previous work, since the compressed size factor in the bound is divided
by the size of the dataset. Consequently, we have greater flexibility in selecting larger models
that achieve an improved empirical risk. In this setting, the Monarch parametrization achieves
the best trade-off between the empirical risk and the compressed size of the model as shown in
Table 1, followed by LoRA and Kronecker. Monarch and Kronecker also perform best in terms
of the validation loss, as shown in Figure 1(Right). The new trade-off between the empirical
risk and the compressed size of the model also explains why subspace compression is no longer
beneficial in obtaining tighter bounds compared to previous work, as further reducing the
10
Model BPDTop-1 Error (%) Top-100 Error (%)
GPT2 (124M) 7.61 74 .82 26 .98
GPT2 (355M) 8.50 79.19 32.72
GPT2 (774M) 10.47 89.50 44.23
Random Guess 15.62 99.99 99.80
Table 2:Non-vacuous token-level generalization bounds for open-source pretrained
GPT2 models. Pretrained GPT2 models achieve non-vacuous bounds for next token prediction
on OpenWebText through post-training quantization only and without altering the pretraining.
Model BPDTop-1 Error (%) Top-100 Error (%)
LLaMA2-7B 4.28 47 .50 12 .56
LLaMA2-13B 4.51 47.85 14.44
LLaMA2-70B 6.39 58.26 25.04
Random Guess 14.97 99.99 99.68
Table 3:Non-vacuous token-level generalization bounds for open-source pretrained
LLaMA2 models. Pretrained LLaMA2 models achieve non-vacuous token-level bounds for
next token prediction on the Amber dataset via 2-bit post-training QuIP quantization only.
number of trainable parameters through linear subspace projection leads to a worse trade-off
between the empirical performance of the compressed model and its compressed size.
6.2Non-vacuous Bounds for Pretrained LLMs: GPT2, LLaMA1 and
LLaMA2
Intensive quantization is another way we can achieve model compression, and therefore tighter
generalization bounds. We explore the setting where we only apply post-training quantization
to pretrained LLMs and compute the corresponding token-level generalization bounds.
Pretrained GPT2 models. We apply the post-training quantization [ 31] to the publicly
available GPT2 models [ 39] of sizes 124M (GPT2 small), 354M (GPT2 medium), and 773M
(GPT2 large) parameters that were pretrained on the WebText dataset and report the numbers
in Table 2. We find that GPT2 small not only yields non-vacuous bounds, but these bounds are
quite comparable to those obtained using aggressive compression techniques in Table 1. GPT2
medium and large also achieve non-vacuous bounds despite having almost a billion parameters.
Pretrained LLaMA models. In this set of experiments, we use pretrained and pre-quantized
publicly available LLaMA1, LLaMA2 and LLaMA2-Chat models and plug in their empirical
risk and compressed size directly into our token-level bounds. We report the bounds obtained
for 2-bit LLaMA2 in Table 3. The full set of results is reported in Table 8. The bounds
are computed for the next token prediction task on the Amber dataset, which contains 1.2T
tokens. We obtain non-vacuous bounds for these models despite their large scale, ranging from 7
billion to 70 billions parameters. Our experiments show that the LLaMA2-Chat models achieve
worse generalization bounds as reported in Table 8 and Figure 1(Left), demonstrating that
fine-tuning Chat models for dialogue use cases hurts their generalization performance on next
token prediction. Although we do not know what data was used to pretrain the LLaMA models,
our bounds remain valid since they do not require for the models to be trained on the same
data that the empirical risk is evaluated on.
High-quality text generation. One of the major benefits to achieving non-vacuous generaliza-
tion bounds for the original model without aggressive subspace training is to be able to generate
high-quality text with the model that achieves the best bounds. In fact, a significant limitation
of document-level bounds is that the SubLoRA model achieving the best document-level bound
generates un-grammatical, low-quality text as demonstrated by Lotfi et al. [32]and shown in
11
Compression Approach Bits Per Dimension Top-1 Error Top-10 Error Validation Loss
Mistral 377M 2.41 31.60 26.46 0.28
Mistral 212M 2.06 26.25 21.07 0.30
Mistral 94M 1.62 19.40 14.59 0.30
Random Guess 4.86 96.56 65.51 1.46
Table 4:Models pretrained on antibody sequences achieve non-vacuous token-level
generalization bounds. Language models based on the Mistral 7B architecture with scaled-
down sizes pretrained on antibody sequences achieves non-vacuous bounds for next token
prediction on a processed subset of Observed Antibody Sequences (OAS) through post-training
quantization only. The vocabulary size of an antibody LLM is 29.
Training Context Length 01241024
GPT2-S-Quantized 13.911.19.07.9 7.6
Markov Chain 11.310.515.322.4-
Table 5:GPT2 models achieve tighter bounds than Markov chains for large context
lengths. We evaluate the generalization bound BPD achieved when k= 0,1,2,4,1024previous
tokens are made visible to a GPT2 LLM during training when predicting the next token, and
we compare to a our bounds evaluated on a sparse k-th order Markov chain trained on the same
data; with 0th order being just the empirical token probabilities. Our LLM bounds provide a
much stronger statement than what would be explained by low order Markov models.
Table 9. Moreover, document-level bounds for the original model or for models with a sufficiently
high number of trainable parameters to generate high-quality text are vacuous, as shown in
Table 1 and Figure 1 of Lotfi et al. [32]. In contrast, our top-performing model in terms of
token-level BPD bounds on the OpenWebText dataset, which is the quantized GPT2 small
model, generates high-quality text, ensuring a unique combination of practical usefulness and
tight guarantees on the population risk.
6.3 Token-Level Generalization Bounds on Antibody Sequences
Inadditiontonaturallanguages, ourtoken-levelgeneralizationboundsareparticularlydescriptive
of antibody design in biology. An antibody sequence is usually composed of 20 different amino
acid tokens to bind to a target of interest. In therapeutic antibody design, biologists propose
mutations to existing antibody sequences by changing the amino acid tokens at specific positions
in the sequence. Recent works have shown that LLMs pretrained on large antibody datasets
can be used to propose mutations conditioned on starting antibody sequences [ 44,2]. Our
token-level generalization bounds match the settings by bounding the expected next amino acid
token negative log likelihood averaged over training contexts that serve as starting sequences
for iterative mutations. In Table 4, we show that language models based on the Mistral 7B
architecture pretrained on a processed subset of the Observed Antibody Sequences (OAS) from
scratch achieves non-vacuous token-level generalization bounds [ 20,35,2]. Details of these
experiments can be found in Appendix B.9
6.4 Contextualizing GPT2 Bounds Against Markov Chains
The best token-level bound that we achieve for BPD on the OpenWebText dataset is 7.6. But
what does this value exactly mean? One might consider the possibility that our bounds are
describing only the simplest components of fitting the data that exist in the model, such as the
predictions of a 0th or 1st order Markov chain [34].
12
In Table 5 we show that this is not the case, by explicitly training a sparse k-th order Markov
chain on OpenWebText and computing our token-level bounds for the result. Sweeping over
different numbers of n-grams to use for the Markov chains, our bounds for these models cap
out at 10.5BPD and rapidly degrade with higher order as more statistics need to be stored.
We also train and compress versions of GPT2 that are restricted to only seeing ktokens as
context, mirroring the restrictions of the Markov chains. We find that for the simple 0and1st
order Markov chains, our compression via the transformer is slightly worse. However, the LLM
performs much better for higher orders.
6.5 Memorization vs. Reasoning
Large language models are capable of memorizing facts from their pretraining data, but they
also can learn highly structured patterns. As we compress a model more and more, it must
lose its ability to recall memorized facts, but it may still remember patterns, since they are
compressible. In this section, we examine the difference between memorization and reasoning
by measuring the ability of LLMs to compress structured and unstructured sequence data.
25 50 75 100
Quantization Levels0.00.20.40.60.8Accuracy (%)
Structured Sequences
Random Sequences
Figure 4: As language models are com-
pressed, they retain their understanding
of patterns, but they forget highly ran-
dom and unstructured data rapidly. Exper-
imentsperformedonGPT2modelswithdatasets
created as detailed in Section 6.5. Compression
performed via post-training quantization where
lower quantization levels reflect more aggressive
compression.To generate structured sequences, we first use
short binary expression trees to generate nu-
merical sequences of integers [ 17]. These se-
quences are highly compressible as they are
generated using short and deterministic pro-
grams. To generate unstructured sequences,
we collect the set of all unique integers from
the structured sequences and form random
sequences composed of IID samples from the
set of unique integers (see Appendix B.6 for
details). We train standard GPT2 models
from scratch on structured and random se-
quences separately. In Figure 4, we show the
integer prediction training accuracy with vary-
ing degrees of post-training quantization. We
observe that as models are quantized more
aggressively, i.e. the number of quantization
levels decreases, they forget unstructured se-
quences far faster than structured sequences.
These results parallel the | findings of Jin et al.
[21]who show that smaller models can retain
in-context learning capabilities but lose their
ability to recall facts.
7 Conclusion
In this work, we introduced novel token-level generalization bounds for LLMs which are able
to accommodate the non-IID nature of the tokens within the training corpus. Combined with
different compression techniques, we achieve non-vacuous generalization bounds for LLMs with
up to 70 billion parameters. The compressed models for which we construct our bounds are
capable of producing high quality text, unlike those in prior work. While there is still have a
gap to close between the typical validation BPD and the constraint of our bounds, our bounds
are predictive of generalization and provide insights into model behaviour.
In future work, one could envision constructing new bounds that make use of the independence
structure between documents and then the non-independent structure within documents to
achieve the best of both. It would also be exciting to further explore the development of these
13
bounds for new downstream predictive tasks, in the vein of the antibody design task we briefly
consider here.
Acknowledgements
We thank Alan Amin for helpful | discussions and anonymous reviewers for helpful feedback.
This work is supported by NSF CAREER IIS-2145492, NSF CDS&E-MSS 2134216, NSF
HDR-2118310, BigHat Biosciences, Capital One, and an Amazon Research Award. | interpretation of our bounds and demonstrate their ability to
predict generalization on downstream tasks. Finally, we introduce a new optimization strategy
for tuning a prediction smoothing hyperparameter that further improves our bounds.
4.1 A Novel Non-IID Token-Level Generalization Bound
In deriving token-level bounds, one might consider applying Equation (1) to the finite dataset
D={(x<i, xi)}M
i=1composed of input and output pairs. In this scenario, model training can be
performed on a random subset S⊂ Dofmpairs, which differs from how training is usually
performed via contiguous sequences. Then, we could use the performance on Sto bound the
average performance on Dsince Sis constructed as an IID sample from D. While these bounds
are valid, they require fundamentally altering the training procedure, and they only pertain
to the held out pairs which must be collected in advance and separated from their naturally
occurring context.
To avoid these | Section not found | limitations and use our bounds to derive insights about the
generalization properties and limitations of LLMs. Namely, we make the following contributions:
•In Section 4, we present and derive a generalization bound that considers each sample to
be an individual token. Even though tokens within a document are not independent, we
use properties of martingales to obtain a valid bound that benefits from the number of
tokens in a language model’s pretraining dataset.
•In Sections 5 and 6, we explore several expressive model compression techniques such as
Monarch matrices, Kronecker factorizations, and post-training quantization and show that
bounding the performance at the token-level favors less restrictive compression strategies.
•Our work is the first to compute non-vacuous generalization bounds for models compressed
only through post-training quantization and without altering the pretraining procedure
at all. Consequently, we obtain generalization bounds for massive pretrained LLMs like
LLaMA2-70B, as shown in Figure 1(Left) and Section 6, which generate high-quality text.
2
•Our experiments in Section 6 indicate that the chat versions of LLaMA have looser gener-
alization guarantees, demonstrating that fine-tuning these models for dialogue negatively
affects their performance on the next token prediction task.
•In Section 6.4, we demonstrate that GPT2 models that are restricted to only seeing k
tokens in their context for training and evaluation obtain significantly better bounds
than k-th order Markov chains for high values of k, reflecting the remarkable ability of
transformer-based models in capturing longer range correlations.
•We show in Section 6.5 that a model’s ability to recall memorized facts from its pretraining
data deteriorates faster than its ability to recognize structured patterns as we decrease the
size of the model through compression, distinguishing between compressible tasks where
generalization is possible and incompressible tasks that correspond to sheer memorization.
2 Related Work
Generalization bounds for neural networks. Deep neural networks are challenging to
understand using generalization theory due to their many parameters [ 51]. However, over the
past years, there has been success in constructing meaningful bounds covering image classification
models [13], vision-language models [ 1], and tabular data [ 17], often through the methodology
of compression [ 53,31]. Lotfi et al. [32]extend compression-based generalization bounds to
the LLM setting, and obtain non-vacuous bounds at the document level. Li et al. [27]explore
generalization in few-shot learning, establishing bounds based on in-context examples while
maintaining a fixed pretrained model. In contrast, we investigate pretraining generalization
bounds to understand why models do not overfit at training time, despite the increased dataset
complexity.
Non-IID Generalization bounds. While the vast majority of generalization bounds assume
that the different data points are drawn independently, there are a handful of works that aim to
relax this assumption in different ways. Ralaivola et al. [41]analyze the dependence graph of the
random variables, deriving a bound based on the graph coloring number, fitting into a broader
line of work making use of properties of the dependence graph [ 52]. Unfortunately for text data,
the dependencies are unknown or assumed to follow the triangular autoregressive dependency
structure for all pairs in the sequence, which limits the applicability of such an approach. A
related line of work has been to explicitly estimate coefficients which quantify the extent that
random variables relate to each other [e.g., 33,24]. However, it is unclear how best to apply
these methods to neural networks. Martingale tail bounds are sometimes used in online learning
and reinforcement learning, e.g., for establishing regret bounds [ 40]. Chugg et al. [7]present
a large collection of generalization bounds both in the IID and martingale settings, including
generalization bounds which could be used at the token level such as the one we derive. Their
results extend and generalize many existing bounds. We view our contribution as orthogonal
to these efforts since we focus on constructing the components necessary to generate practical
bounds for LLMs, rather than innovating on concentration inequalities themselves.
Large language models and compression. In recent years, language models went from
millions to billions of parameters, leading to consistent improvements across downstream
applications. A variety of compression techniques have been proposed to account for the
increased computational costs of LLMs while preserving their performance. Parameter-efficient
finetuning methods, such as LoRA [ 19], parametrize weight matrices as products of two trainable
low-rank matrices on top of frozen pretrained weights. QLoRA uses 4-bit NormalFloat (NF4)
and double quantization, enabling single-GPU finetuning for a 65B parameter LLM without
performance degradation [ 10,11]. Post-training quantization approaches, such as GPTQ [ 16],
rely on second-order information and quantize each row of weight matrices independently. QuIP
uses adaptive rounding and incoherence processing of second-order Hessian matrices, enabling
2-bit quantization of LLMs [ 6]. Other compression techniques for LLMs include replacing most of
3
the 16-bit operations with 8-bit matrix multiply [ 10], using data-free distillations [ 28], designing
custom kernels and sub-4-bit integer quantization [ 22,36], and compressing embeddings as
low-rank matrix-product state [50].
3 Background
In this section, we review the different components of compression-based generalization bounds,
which we build upon with our method in Sections 4 and 5.
Finite hypothesis compression bounds. LetR(h, x)∈[a, a+ ∆]be a bounded risk and
h∈ Hbe a hypothesis drawn from a finite hypothesis space with prior P(h). A classic finite
hypothesis generalization bound [43] states that for any δ >0with probability 1−δ,
R(h)≤ˆR(h) + ∆r
log 1/P(h) + log 1 /δ
2m(1)
where the empirical risk is defined as ˆR(h) :=1
mPm
i=1R(h, xi)with{xi}m
i=1being IID and
R(h) =E[ˆR(h)]. The complexity term depends on the prior log probability log1/P(h). We
use the Solomonoff prior P(h)≤2−K(h)[45], where K(h)is the prefix Kolmogorov complexity
ofhdefined as the length of the shortest program that produces hfor a fixed programming
language [ 23]. Consequently, our prior favors models hthat have a small minimum compressed
length. While the Kolmogorov complexity is incomputable, it can be bounded as log1/P(h)≤
K(h)log2≤C(h)log2+2logC(h), where C(h)is the compressed size of the model according to
a pre-specified compressor. Therefore, we can find the right trade-off between the empirical risk
and the compressed size of the model by tuning the extent of compression, hence the different
compression techniques we explore in this work.
Compression bounds for LLMs. When constructing document-level bounds for language,
the empirical risk is defined over an entire document XasR(h, X) =−log2ph(X)/L, where
ph(X)is defined auto-regressively on the sequence of tokens X= [x1, x2, . . . x L]aspθ(X) =QL
i=1ph(xi|x<i), where x<idenotes x1, x2, . . . , x i−1.
Prediction smoothing. Since the bound in Equation (1) only applies to a bounded risk, it is
not valid for the bits-per-dimension loss that is unbounded. In this case, one can introduce a
prediction smoothing probability αto the predictive model such that the generative probability
distribution becomes a mixture between the next token probability according to the auto-
regressive model f(θ)with parameters θand a uniform distribution over the vocabulary of size
Vas follows: ph(xi|x<i) = (1 −α)pθ(xi|x<i) +α/V. With this construction, R(h, X)can be
bounded in an interval of size ∆ = log2(1 + (1 −α)V/α). The optimal hyperparameter αis
determined via a grid search in Lotfi et al. [32].
Compressing LLMs with SubLoRA. To achieve the extreme compression level necessary
to obtain non-vacuous document-level bounds, Lotfi et al. [32]propose SubLoRA, a non-linear
subspace parametrization of an LLM’s weights θ. Using SubLoRA, these weights can be written
asθ=θ0+LoRA (Pw). Here θ0∈RDare the model weights at random initialization and
LoRA (Pw)combines low-rank adaptation (LoRA) [ 19] with subspace training [ 31] via the
projector P∈RD×d. The LoRA decomposition parameterizes a dense matrix W∈Ra×b
as the product of two low-rank matrices A∈Ra×r, B∈Rr×bwith a small rank r. As for
the linear subspace parametrization Pw, the projection matrix Pis defined as a Kronecker
product P=Q1⊗Q2produced by orthogonalizing Q1, Q2∼ N (0,1/√
D)√
D×√
dvia a QR
decomposition.
In practice, a selected subset of the dense matrices in an LLM are parameterized using LoRA’s
low rank matrices, then the concatenation of LoRA’s matrices is projected into the subspace
parameters wusing P. The model is therefore effectively trained via the weights w∈Rd. As a
result, the model can be coded via a random seed that reproduces the pre-fixed initialization θ0
4
and projection matrix P, and a coding of wwhich is performed using arithmetic coding [ 25].
The dimension dofwcan be varied to achieve the best trade-off between empirical risk and
complexity, and these degrees of freedom are accounted for in the coding of the hypothesis h.
4 Token-Level Generalization Bounds
In order to unlock a deeper understanding of LLM generalization, it is not sufficient to consider
the training data at the level of entire documents. In fact, token-level performance is arguably
what we care about most when evaluating a model’s generalization on its next token prediction
pretraining task. Moreover, simplifying the bounds to meet the IID assumption over sampled
documents restricts our ability to capture the dependencies between individual tokens. In this
section, we derive novel bounds at the token level through a simple yet powerful application of
Azuma’s inequality that allows us to use the properties of martingales to go beyond the IID
setting. Then, we discuss the interpretation of our bounds and demonstrate their ability to
predict generalization on downstream tasks. Finally, we introduce a new optimization strategy
for tuning a prediction smoothing hyperparameter that further improves our bounds.
4.1 A Novel Non-IID Token-Level Generalization Bound
In deriving token-level bounds, one might consider applying Equation (1) to the finite dataset
D={(x<i, xi)}M
i=1composed of input and output pairs. In this scenario, model training can be
performed on a random subset S⊂ Dofmpairs, which differs from how training is usually
performed via contiguous sequences. Then, we could use the performance on Sto bound the
average performance on Dsince Sis constructed as an IID sample from D. While these bounds
are valid, they require fundamentally altering the training procedure, and they only pertain
to the held out pairs which must be collected in advance and separated from their naturally
occurring context.
To avoid these limitations, we construct a novel bound that naturally accommodates the non-IID
structure of the tokens as they occur in documents as follows:
Theorem 1. With probability at least 1−δover the randomness in a sampled sequence
{x1, x2, . . . , x m}, if the negative log likelihood of a model h∈ Hcan be bounded −log2ph(·|x<i)∈
[a, a+ ∆ i], then the negative log likelihood of the data for model hsatisfies
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m,(2)
where ˆ∆=q
1
mPm
i=1∆2
i, the expectation is taken over Xi∼p(Xi|x<i)from the data generating
process, and P(h)is any normalized prior over a discrete hypothesis space Hthat does not
depend on {xi}m
i=1.
We provide a proof sketch as well as the full proof in Appendix A.1.
On the right-hand side of the bound is the conventional empirical risk: −1
mlog2ph(x≤m) =
−1
mP
ilog2ph(xi|x<i)onthemeasuredsequenceandacomplexityterm log1/P(h). Wedescribe
in detail how we sample sequence x≤mand compute the empirical risk in Section 4.2. The
quantity which we are bounding on the left-hand side is the expected next token negative
log-likelihood under resampling from the data generating process, averaged over the different
contexts that have been encountered in the training set. The bound ensures generalization on
contexts seen at training when the next tokens are resampled, but not on data with contexts
that are different. However, given how diffuse the distribution over next tokens is, e.g., at the
beginning of a new sentence, our bounds remain predictive of generalization and achieving a
non-vacuous bound requires generalization. We further discuss the interpretation of our bounds
in Section 4.3.
5
2 4 6
Entropy0100002000030000Frequency
0248161282565127681023
Token Index02468Entropy
108
109
Trainable Parameters20406080100120PPL / Acc (%)PPL
BPDACC
4.04.24.44.64.85.0
Bound Objective (BPD)Figure 2: Our bounds analyze a quantity that is meaningful and predictive of
generalization. Left: Using LLaMA2-7B, we compute the entropy of p(xi|x<i), where the
context x<iis fixed and sampled from the Amber training dataset. The distribution over next
tokens given a fixed context from the training data is indeed diffuse and characterized by high
entropy values. Middle: Entropy of p(xi|x<i)as a function of the token index ishown on the
x-axis for a context length L= 1024. The average entropy has a decreasing trend but remains
high overall; note that the average entropy for i= 768is as high as the average entropy for
i= 128.Right:On the left y-axis, we plot the average zero-shot accuracy (ACC) and perplexity
(PPL) achieved by GPT2 models ranging in scale from 117M to 1.5B averaged over downstream
datasets, as reported in Radford et al. [39]. On the right y-axis, we plot an approximation of
the conditional BPD expectation that we bound in Equation (2) where we resample xifrom a
LLaMA2-7B given fixed training contexts x<ifrom the Amber dataset. The approximation of
the BPD objective that we bound achieves 97.9%and99.1%correlation with the accuracy and
perplexity, respectively.
4.2 Sampling and Empirical Risk Evaluation
In this section, we more precisely define the sequence x≤mfor which we compute the empirical
risk in Equation (2). We construct a sample x≤mfrom the stochastic process pdataby first
sampling independent and identically distributed documents, e.g., the documents that form
the OpenWebText dataset. Then, we concatenate these documents deterministically using end
of text (EOT) tokens. Consequently, the ground truth stochastic process has the following
property:
pdata(xi|x<i) =pdata(xi|xk, ...., x i−1), (3)
where xkis the previous EOT token. This equality holds exactly due to how the stochastic
process is implemented.
On the other hand, it would not be guaranteed that a generative model ph(x)satisfies the
property in Equation (3) apriori if the model were allowed to attend to tokens x<k, even when
the data generating process has this property. However, we explicitly prohibit our generative
model hfrom attending to tokens x<kthrough the attention mask, as we have the flexibility to
do so in defining our hypothesis class and model family. Therefore, our model phthat we bound
also satisfies this property ph(xi|x<i) =ph(xi|xk, ...., x i−1)exactly, and not approximately.
In conclusion, the empirical risk for our generative model hand a sequence x≤msampled from
the stochastic process defined above can be written as follows:
−1
mlog2ph(x≤m) =−1
mX
ilog2ph(xi|x<i) =−1
mX
ilog2ph(xi|xk, . . . x i−1),
where xkis the nearest EOT token occurring before xi. Given the large size of the OpenWebText
and Amber datasets, containing 9 billions and 1.2 trillion tokens respectively, we use subsampling
for the evaluation of the empirical risk. More details can be found in Appendix A.2.
6
4.3 Token-level Bounds Are Predictive of Generalization
Token-level vs. document-level bounds. In contrast to document-level bounds, token-level
bounds increase the number of samples, driving down the size of the complexity term, and
do not require the IID assumption. Whereas the number of samples previously would be the
number of documents, it is now simply the number of tokens in the dataset, a far higher
number. As a consequence of decreasing the complexity term, the empirical risk will be a more
significant contributor to our bounds compared to document-level bounds. Therefore, we achieve
non-vacuous bounds for much larger and more performant models that generate high-quality
text. This development brings our theoretical bounds much closer to aligning with empirical
generalization.
Interpretation of token-level bounds. It is important to note the difference between the
quantity that we bound1
mPm
i=1E[−log2ph(Xi|x<i)|x<i], which is conditioned on contexts
seen at training, and the expected risk E[−log2ph(Xi|x<i)]under resampling from the data
generating process where new contexts can be sampled from this process. However, the
resampled next tokens xi|x<iare not necessarily from the training set, and to the extent that
the distribution over next tokens is entropic, we are measuring a different quantity than the
empirical training performance of the hypothesis h. Moreover, we know that the distribution
over next tokens is often indeed diffuse; for instance, many words have common synonyms. The
distribution over next tokens is especially diffuse when we start a new sentence, for example. We
demonstrate how diffuse the distribution p(xi|x<i)is for fixed contexts x<ifrom the publicly
available Amber training dataset [ 29] (see Appendix B.7) by sampling xi|x<iusing LLaMA2-7B
to approximate the generative process. Figure 2(Left) shows that, indeed, the distribution
p(xi|x<i)is characterized by a high entropy for a large number of tokens. In Figure 2(Middle),
we plot the entropy of p(xi|x<i)for each index iin a context of length 1024. This figure
confirms our intuition that the next token distribution is particularly diffuse at the beginning of
a sentence, while it decreases for later tokens but remains relatively high. Given how diffuse
the distribution is and the large number of possible sentences, it is broadly infeasible to make
predictions on new resampled tokens from the empirical distribution alone.
Our bounds are predictive of downstream performance. We compute an approximation
of the quantity that we bound in Equation (2) by sampling next tokens xiusing LLaMA2-7B
given fixed contexts x<ifrom the Amber dataset. We plot this quantity on the right y-axis of
Figure 2(Right), and show on the left y-axis the performance of GPT2 models of varying sizes
on downstream datasets as reported in Radford et al. [39]; see Appendix B.4 for more details.
Not only does the approximation of the BPD objective show the same trend as the downstream
performance for different GPT2 variants, but it also achieves 97.9%and99.1%correlation [ 4]
with downstream task accuracy and perplexity metrics, respectively.
In short, our bounds go significantly beyond the observation that the empirical distribution
converges to the true distribution, and are predictive of generalization on downstream tasks.
Achieving a non-vacuous token-level bound requires generalization. We provide further interpre-
tation of the bounds, including a protein application, in Section 6.
4.4 Token-Level Prediction Smoothing
Rather than using a single label smoothing αfor all data points, we propose to use the
network itself to determine which tokens warrant more confidence and which ones require more
smoothing to limit their worst-case behavior. We perform token-level prediction smoothing
by adding a linear head to the LLM that outputs the probability αfor each token, such that
ph(xi|x<i) =
1−αθ(x<i)
pθ(xi|x<i) +αθ(x<i)/V. The training objective corresponds to the
upper bound in Equation (2) rather than the empirical risk alone, where the αparameter factors
into the bound via the interval size ∆i= log2
1 + (1 −αθ(x<i))V/α θ(x<i)
. Therefore, the
values of αθ(x<i)are adjusted to achieve the best trade-off between the empirical risk and
7
106
107
Trainable Parameters8.59.510.5Bound Loss
Before Optimization
After Optimization
104
103
102
101
Prediction smoothing ()
8.08.48.8BPD Bound
Grid Search
Token-Dependent
0.05 0.10 0.15
Prediction smoothing ()
0500100015002000Empirical DistributionFigure 3: Token-level prediction smoothing improves our bounds. Left: After training,
we optimize a conservative upper bound on the generalization bound that we would get from
Equation (2) with respect to the αhead parameters. Doing so yields a noticeable reduction
in the value of the bound. Middle: BPD generalization bound as a function of a single
global parameter chosen from a discrete number of values vs. the generalization bound for the
token-dependent αafter optimization. Right:Histogram of the values taken by α(x<i)over
different inputs.
the compressed model size. We perform this optimization post-training using a subset of the
training dataset.
We demonstrate in Figure 3(Left) that using this token-dependent αsignificantly improves the
value of the bounds. In Figure 3 (Middle), we compare to the setting where the optimal α
is obtained through a grid search, and in Figure 3(Right) we examine the distribution of α
produced by the model.
5 Compressing LLMs to Minimize Complexity
In shifting from document-level to token-level bounds, the number of data points mincreases
considerably, and thus we can afford to pay significantly more bits in the complexity of the
compressed model. In this new regime, the SubLoRA compression technique, which consists of
training only a linear subspace of LoRA-parameterized weights in the attention layers, becomes
very restrictive. Therefore, we explore other less restrictive forms of compression.
5.1 Efficient Nonlinear Parametrizations
In addition to LoRA, we explore two expressive nonlinear parametrizations f(θ)that make
efficient use of the parameter space: Kronecker structures [ 15] and Monarch matrices [ 9]. We
can use these nonlinear parametrizations directly, or in conjunction with subspace compression,
parametrizing the full parameters as θ=θ0+f(Pw)for a projection matrix P∈RD×d. After
training, the parameters are quantized and coded using arithmetic coding. We describe these
structures below.
LoRA.With LoRA [ 19], the weight matrices of linear layers are parametrized via low rank
updates. Each weight matrix W∈Ra×bis parametrized W=W0+ABforA∈Ra×r, B∈Rr×b
with a small rank r, where W0is given by the initialization and A,Bform the trainable
parameters in each layer. Rather than considering only self-attention layer weights [ 19,32], we
extend SubLoRA to all linear layers in the model and compress the biases and layernorm weights
in the subspace projection. We define f(θ) =LoRA (θ)as the transformation that unpacks θ
intoAandB, multiplies the low rank matrices and adding the initialization to form Wand
reshaping them into the parameters in the usual way.
Kronecker Product. We can represent Was a Kronecker product W=A⊗B, where ⊗
is the Kronecker product, A∈Ra1×b1, B∈Ra2×b2anda1a2=a,b1b2=b, which reduces the
8
parameters over the dense layer. This approach has been used in recent work for parameter-
efficient finetuning [ 15] and as an alternative structure for pretraining. Similarly to LoRA, we
define f(θ) = Kron( θ)as this parametrization for all linear layers.
Monarch Matrices. We also consider Monarch matrices [ 9], which employ two block diagonal
matrices A, and Btypically with AandBformed by√ablocks of size√a×√
band a reshape or
permutation operation R:W=ARB. The matrix multiplication is implemented by reshaping
the input axis ainto(√a,√a), applying matrix Aas a batched matrix multiply on one axis,
and then applying Bto the other axis by permuting the axes. Monarch matrices have shown
considerable promise as an expressive and hardware-efficient replacement for linear layers. We
define f(θ) = Monarch( θ)for their application to each of the linear layers in the network.
In our experiments, we apply all three compression techniques, with and without subspace
compression, to all linear layers in the models.
5.2 QuIP 2-Bit Quantization of LLM
In addition to pretraining LLMs in efficient nonlinear subspaces, we explore recent post-training
quantization methods to reduce the model complexity. Quantization with Incoherence Process
(QuIP) compresses LLM weights to a smaller number of bits while preserving model performance
[6].
Adaptive Rounding. For a weight matrix W∈Ra×b, QuIP minimizes the proxy quadratic
objective ℓ(ˆW) =E[∥(ˆW−W)x∥2] =tr((ˆW−W)H(ˆW−W)⊤), where ˆW∈Ra×bare the
quantized weights, x∈Rbis a vector drawn randomly from a calibration set, and His the
second moment matrix of these vectors used as a proxy Hessian [6].
Incoherence Processing. Based on the observation that incoherences between the weights W
and the proxy Hessian Hbenefit quantization, QuIP further applies incoherence post-processing
using Kronecker products of random orthogonal matrices U∈Ra×a, V∈Rb×bsuch that
˜H←V HV⊤,˜W←UWV⊤. Here U=U1⊗ ··· ⊗ UkandV=V1⊗ ··· ⊗ Vk.
Subsequent work like QuIP# improves upon QuIP by using randomized Hadamard transform
and vector quantizations [ 48]. To compute the compressed size C(h)of QuIP-quantized models,
we use gzip[12] to compress the quantized model checkpoint and obtain the term C(h)as the
bits required for the storage afterwards.
6Non-Vacuous Bounds for LLMs with Billions of Parame-
ters
As described in the previous section, we compute generalization bounds for: (i) models that are
trained through non-linear subspace compression in the form of LoRA, Kronecker product or
Monarch matrices on the OpenWebText dataset, then quantized using the same setup as Lotfi
et al.[32], or (ii) models that are pretrained on a dataset other than the OpenWebText dataset
– or on datasets that might have the OpenWebText as a subset– and made publicly available.
For the pretrained models, we either apply aggressive quantization, which is the case for GPT2,
or use QuIP 2-bit, 3-bit and 4-bit publicly-available quantized models, which is the case for
LLaMA. In the pretrained LLMs setting, we evaluate our bounds for both the OpenWebText
(9B tokens) and Amber (1.2T tokens) datasets. In both settings, we obtain highly compressed
models that lead to non-vacuous generalization bounds.
In addition to reporting generalization bounds on BPD, we also report the bounds that we
obtain on the Top-1, Top-10 and Top-100 error. The Top- kerror refers to the 0-1error in
predicting the next token among the top- kpredictions of the model. For instance, the Top-1
error for token xiis defined as 1[argmax xjp(xj|x<i=x<i) =xi], where argmaxoperates over
tokens xjacross the vocabulary. We extend this definition to the Top-k error and define it
9
Compression Approach BPD Bound Top-1 Error Top-10 Error Top-100 Error
SubLoRA [32] 10.49 90.44 71.33 49.77
Enhanced SubLoRA (Ours) 10.44 89.38 69.54 49.84
Enhanced LoRA (Ours) 7.85 78.15 52.48 31.64
Monarch Only (Ours) 7.65 75.87 47.47 28.34
Kronecker Only (Ours) 8.03 80.80 52.77 30.14
Kronecker + Subspace (Ours) 10.02 88.75 67.91 47.14
Random Guess 15.62 99.99 99.98 99.80
Table 1:Non-vacuous generalization bounds using different compression techniques
for GPT2 pretraining. We find that with the larger complexity budget afforded by the
token-level bounds, subspace compression is no longer necessary or even beneficial for the bounds.
Of the structures we consider, the Monarch parametrization performs best.
as1[xi∈argmax xj,kp(xj|x<i=x<i)], where the argmaxoperator here selects the top- ktokens
predicted by the model according to its next token probability distribution p(xj|x<i=x<i).
Our bound in Equation (2) applies not only to the log likelihood but to any bounded risk, and
therefore can be computed for the Top- kerror since it is bounded between 0and1. We call a
Top-kerror bound vacuous when the bound is larger than the random guess top- kerror equal
to1−k/V, where Vis the vocabulary size.
We present our bounds in this section and contrast the quality of the text generated by our
best performing model in terms of the BPD bound to the text generated by Lotfi et al. [32]’s
best performing model. We also compute token-level generalization bounds for antibody design,
a task where conditioning on contexts from the training dataset arises naturally. Finally, we
investigate the effect of aggressive compression on memorization vs. reasoning in LLMs. We
provide all the experimental details in Appendix B.
6.1 Token-level Bounds via Nonlinear Parametrizations
As discussed in Section 5.1, we experiment with LoRA in addition to the Kronecker and
Monarch subspace parametrizations in order to train compressed versions of GPT2 small (124M
parameters). Compared to previous work, we enhance both LoRA and SubLoRA by not only
applying the low-rank decomposition to the attention layers and the linear head, but to all the
fully-connected layers in the LLM. Additionally, we train all the bias and layer normalization
parameters instead of keeping them fixed at their values at initialization. We also use rotary
position embeddings [ 46] to directly encode the positional information into the LLM. Combined
with our proposed token-level optimization of the label smoothing probability α, we significantly
improve upon the LoRA subspace compression, as shown in Table 1. It is worth noting the
LoRA alone led to vacuous BPD document-level bounds in Lotfi et al. [32]while our version is
non-vacuous.
Among all subspace compression strategies that we explore in Table 1, Monarch without subspace
leads to the tightest token-level bound. In fact, the substantial scale of our dataset, comprising 9
billion tokens, significantly changes the trade-off between the empirical risk and the compressed
model size compared to previous work, since the compressed size factor in the bound is divided
by the size of the dataset. Consequently, we have greater flexibility in selecting larger models
that achieve an improved empirical risk. In this setting, the Monarch parametrization achieves
the best trade-off between the empirical risk and the compressed size of the model as shown in
Table 1, followed by LoRA and Kronecker. Monarch and Kronecker also perform best in terms
of the validation loss, as shown in Figure 1(Right). The new trade-off between the empirical
risk and the compressed size of the model also explains why subspace compression is no longer
beneficial in obtaining tighter bounds compared to previous work, as further reducing the
10
Model BPDTop-1 Error (%) Top-100 Error (%)
GPT2 (124M) 7.61 74 .82 26 .98
GPT2 (355M) 8.50 79.19 32.72
GPT2 (774M) 10.47 89.50 44.23
Random Guess 15.62 99.99 99.80
Table 2:Non-vacuous token-level generalization bounds for open-source pretrained
GPT2 models. Pretrained GPT2 models achieve non-vacuous bounds for next token prediction
on OpenWebText through post-training quantization only and without altering the pretraining.
Model BPDTop-1 Error (%) Top-100 Error (%)
LLaMA2-7B 4.28 47 .50 12 .56
LLaMA2-13B 4.51 47.85 14.44
LLaMA2-70B 6.39 58.26 25.04
Random Guess 14.97 99.99 99.68
Table 3:Non-vacuous token-level generalization bounds for open-source pretrained
LLaMA2 models. Pretrained LLaMA2 models achieve non-vacuous token-level bounds for
next token prediction on the Amber dataset via 2-bit post-training QuIP quantization only.
number of trainable parameters through linear subspace projection leads to a worse trade-off
between the empirical performance of the compressed model and its compressed size.
6.2Non-vacuous Bounds for Pretrained LLMs: GPT2, LLaMA1 and
LLaMA2
Intensive quantization is another way we can achieve model compression, and therefore tighter
generalization bounds. We explore the setting where we only apply post-training quantization
to pretrained LLMs and compute the corresponding token-level generalization bounds.
Pretrained GPT2 models. We apply the post-training quantization [ 31] to the publicly
available GPT2 models [ 39] of sizes 124M (GPT2 small), 354M (GPT2 medium), and 773M
(GPT2 large) parameters that were pretrained on the WebText dataset and report the numbers
in Table 2. We find that GPT2 small not only yields non-vacuous bounds, but these bounds are
quite comparable to those obtained using aggressive compression techniques in Table 1. GPT2
medium and large also achieve non-vacuous bounds despite having almost a billion parameters.
Pretrained LLaMA models. In this set of experiments, we use pretrained and pre-quantized
publicly available LLaMA1, LLaMA2 and LLaMA2-Chat models and plug in their empirical
risk and compressed size directly into our token-level bounds. We report the bounds obtained
for 2-bit LLaMA2 in Table 3. The full set of results is reported in Table 8. The bounds
are computed for the next token prediction task on the Amber dataset, which contains 1.2T
tokens. We obtain non-vacuous bounds for these models despite their large scale, ranging from 7
billion to 70 billions parameters. Our experiments show that the LLaMA2-Chat models achieve
worse generalization bounds as reported in Table 8 and Figure 1(Left), demonstrating that
fine-tuning Chat models for dialogue use cases hurts their generalization performance on next
token prediction. Although we do not know what data was used to pretrain the LLaMA models,
our bounds remain valid since they do not require for the models to be trained on the same
data that the empirical risk is evaluated on.
High-quality text generation. One of the major benefits to achieving non-vacuous generaliza-
tion bounds for the original model without aggressive subspace training is to be able to generate
high-quality text with the model that achieves the best bounds. In fact, a significant limitation
of document-level bounds is that the SubLoRA model achieving the best document-level bound
generates un-grammatical, low-quality text as demonstrated by Lotfi et al. [32]and shown in
11
Compression Approach Bits Per Dimension Top-1 Error Top-10 Error Validation Loss
Mistral 377M 2.41 31.60 26.46 0.28
Mistral 212M 2.06 26.25 21.07 0.30
Mistral 94M 1.62 19.40 14.59 0.30
Random Guess 4.86 96.56 65.51 1.46
Table 4:Models pretrained on antibody sequences achieve non-vacuous token-level
generalization bounds. Language models based on the Mistral 7B architecture with scaled-
down sizes pretrained on antibody sequences achieves non-vacuous bounds for next token
prediction on a processed subset of Observed Antibody Sequences (OAS) through post-training
quantization only. The vocabulary size of an antibody LLM is 29.
Training Context Length 01241024
GPT2-S-Quantized 13.911.19.07.9 7.6
Markov Chain 11.310.515.322.4-
Table 5:GPT2 models achieve tighter bounds than Markov chains for large context
lengths. We evaluate the generalization bound BPD achieved when k= 0,1,2,4,1024previous
tokens are made visible to a GPT2 LLM during training when predicting the next token, and
we compare to a our bounds evaluated on a sparse k-th order Markov chain trained on the same
data; with 0th order being just the empirical token probabilities. Our LLM bounds provide a
much stronger statement than what would be explained by low order Markov models.
Table 9. Moreover, document-level bounds for the original model or for models with a sufficiently
high number of trainable parameters to generate high-quality text are vacuous, as shown in
Table 1 and Figure 1 of Lotfi et al. [32]. In contrast, our top-performing model in terms of
token-level BPD bounds on the OpenWebText dataset, which is the quantized GPT2 small
model, generates high-quality text, ensuring a unique combination of practical usefulness and
tight guarantees on the population risk.
6.3 Token-Level Generalization Bounds on Antibody Sequences
Inadditiontonaturallanguages, ourtoken-levelgeneralizationboundsareparticularlydescriptive
of antibody design in biology. An antibody sequence is usually composed of 20 different amino
acid tokens to bind to a target of interest. In therapeutic antibody design, biologists propose
mutations to existing antibody sequences by changing the amino acid tokens at specific positions
in the sequence. Recent works have shown that LLMs pretrained on large antibody datasets
can be used to propose mutations conditioned on starting antibody sequences [ 44,2]. Our
token-level generalization bounds match the settings by bounding the expected next amino acid
token negative log likelihood averaged over training contexts that serve as starting sequences
for iterative mutations. In Table 4, we show that language models based on the Mistral 7B
architecture pretrained on a processed subset of the Observed Antibody Sequences (OAS) from
scratch achieves non-vacuous token-level generalization bounds [ 20,35,2]. Details of these
experiments can be found in Appendix B.9
6.4 Contextualizing GPT2 Bounds Against Markov Chains
The best token-level bound that we achieve for BPD on the OpenWebText dataset is 7.6. But
what does this value exactly mean? One might consider the possibility that our bounds are
describing only the simplest components of fitting the data that exist in the model, such as the
predictions of a 0th or 1st order Markov chain [34].
12
In Table 5 we show that this is not the case, by explicitly training a sparse k-th order Markov
chain on OpenWebText and computing our token-level bounds for the result. Sweeping over
different numbers of n-grams to use for the Markov chains, our bounds for these models cap
out at 10.5BPD and rapidly degrade with higher order as more statistics need to be stored.
We also train and compress versions of GPT2 that are restricted to only seeing ktokens as
context, mirroring the restrictions of the Markov chains. We find that for the simple 0and1st
order Markov chains, our compression via the transformer is slightly worse. However, the LLM
performs much better for higher orders.
6.5 Memorization vs. Reasoning
Large language models are capable of memorizing facts from their pretraining data, but they
also can learn highly structured patterns. As we compress a model more and more, it must
lose its ability to recall memorized facts, but it may still remember patterns, since they are
compressible. In this section, we examine the difference between memorization and reasoning
by measuring the ability of LLMs to compress structured and unstructured sequence data.
25 50 75 100
Quantization Levels0.00.20.40.60.8Accuracy (%)
Structured Sequences
Random Sequences
Figure 4: As language models are com-
pressed, they retain their understanding
of patterns, but they forget highly ran-
dom and unstructured data rapidly. Exper-
imentsperformedonGPT2modelswithdatasets
created as detailed in Section 6.5. Compression
performed via post-training quantization where
lower quantization levels reflect more aggressive
compression.To generate structured sequences, we first use
short binary expression trees to generate nu-
merical sequences of integers [ 17]. These se-
quences are highly compressible as they are
generated using short and deterministic pro-
grams. To generate unstructured sequences,
we collect the set of all unique integers from
the structured sequences and form random
sequences composed of IID samples from the
set of unique integers (see Appendix B.6 for
details). We train standard GPT2 models
from scratch on structured and random se-
quences separately. In Figure 4, we show the
integer prediction training accuracy with vary-
ing degrees of post-training quantization. We
observe that as models are quantized more
aggressively, i.e. the number of quantization
levels decreases, they forget unstructured se-
quences far faster than structured sequences.
These results parallel the findings of Jin et al.
[21]who show that smaller models can retain
in-context learning capabilities but lose their
ability to recall facts.
7 Conclusion
In this work, we introduced novel token-level generalization bounds for LLMs which are able
to accommodate the non-IID nature of the tokens within the training corpus. Combined with
different compression techniques, we achieve non-vacuous generalization bounds for LLMs with
up to 70 billion parameters. The compressed models for which we construct our bounds are
capable of producing high quality text, unlike those in prior work. While there is still have a
gap to close between the typical validation BPD and the constraint of our bounds, our bounds
are predictive of generalization and provide insights into model behaviour.
In | future work, one could envision constructing new bounds that make use of the independence
structure between documents and then the non-independent structure within documents to
achieve the best of both. It would also be exciting to further explore the development of these
13
bounds for new downstream predictive tasks, in the vein of the antibody design task we briefly
consider here.
Acknowledgements
We thank Alan Amin for helpful discussions and anonymous reviewers for helpful feedback.
This work is supported by NSF CAREER IIS-2145492, NSF CDS&E-MSS 2134216, NSF
HDR-2118310, BigHat Biosciences, Capital One, and an Amazon Research Award. | conclusion, the empirical risk for our generative model hand a sequence x≤msampled from
the stochastic process defined above can be written as follows:
−1
mlog2ph(x≤m) =−1
mX
ilog2ph(xi|x<i) =−1
mX
ilog2ph(xi|xk, . . . x i−1),
where xkis the nearest EOT token occurring before xi. Given the large size of the OpenWebText
and Amber datasets, containing 9 billions and 1.2 trillion tokens respectively, we use subsampling
for the evaluation of the empirical risk. More details can be found in Appendix A.2.
6
4.3 Token-level Bounds Are Predictive of Generalization
Token-level vs. document-level bounds. In contrast to document-level bounds, token-level
bounds increase the number of samples, driving down the size of the complexity term, and
do not require the IID assumption. Whereas the number of samples previously would be the
number of documents, it is now simply the number of tokens in the dataset, a far higher
number. As a consequence of decreasing the complexity term, the empirical risk will be a more
significant contributor to our bounds compared to document-level bounds. Therefore, we achieve
non-vacuous bounds for much larger and more performant models that generate high-quality
text. This development brings our theoretical bounds much closer to aligning with empirical
generalization.
Interpretation of token-level bounds. It is important to note the difference between the
quantity that we bound1
mPm
i=1E[−log2ph(Xi|x<i)|x<i], which is conditioned on contexts
seen at training, and the expected risk E[−log2ph(Xi|x<i)]under resampling from the data
generating process where new contexts can be sampled from this process. However, the
resampled next tokens xi|x<iare not necessarily from the training set, and to the extent that
the distribution over next tokens is entropic, we are measuring a different quantity than the
empirical training performance of the hypothesis h. Moreover, we know that the distribution
over next tokens is often indeed diffuse; for instance, many words have common synonyms. The
distribution over next tokens is especially diffuse when we start a new sentence, for example. We
demonstrate how diffuse the distribution p(xi|x<i)is for fixed contexts x<ifrom the publicly
available Amber training dataset [ 29] (see Appendix B.7) by sampling xi|x<iusing LLaMA2-7B
to approximate the generative process. Figure 2(Left) shows that, indeed, the distribution
p(xi|x<i)is characterized by a high entropy for a large number of tokens. In Figure 2(Middle),
we plot the entropy of p(xi|x<i)for each index iin a context of length 1024. This figure
confirms our intuition that the next token distribution is particularly diffuse at the beginning of
a sentence, while it decreases for later tokens but remains relatively high. Given how diffuse
the distribution is and the large number of possible sentences, it is broadly infeasible to make
predictions on new resampled tokens from the empirical distribution alone.
Our bounds are predictive of downstream performance. We compute an approximation
of the quantity that we bound in Equation (2) by sampling next tokens xiusing LLaMA2-7B
given fixed contexts x<ifrom the Amber dataset. We plot this quantity on the right y-axis of
Figure 2(Right), and show on the left y-axis the performance of GPT2 models of varying sizes
on downstream datasets as reported in Radford et al. [39]; see Appendix B.4 for more details.
Not only does the approximation of the BPD objective show the same trend as the downstream
performance for different GPT2 variants, but it also achieves 97.9%and99.1%correlation [ 4]
with downstream task accuracy and perplexity metrics, respectively.
In short, our bounds go significantly beyond the observation that the empirical distribution
converges to the true distribution, and are predictive of generalization on downstream tasks.
Achieving a non-vacuous token-level bound requires generalization. We provide further interpre-
tation of the bounds, including a protein application, in Section 6.
4.4 Token-Level Prediction Smoothing
Rather than using a single label smoothing αfor all data points, we propose to use the
network itself to determine which tokens warrant more confidence and which ones require more
smoothing to limit their worst-case behavior. We perform token-level prediction smoothing
by adding a linear head to the LLM that outputs the probability αfor each token, such that
ph(xi|x<i) =
1−αθ(x<i)
pθ(xi|x<i) +αθ(x<i)/V. The training objective corresponds to the
upper bound in Equation (2) rather than the empirical risk alone, where the αparameter factors
into the bound via the interval size ∆i= log2
1 + (1 −αθ(x<i))V/α θ(x<i)
. Therefore, the
values of αθ(x<i)are adjusted to achieve the best trade-off between the empirical risk and
7
106
107
Trainable Parameters8.59.510.5Bound Loss
Before Optimization
After Optimization
104
103
102
101
Prediction smoothing ()
8.08.48.8BPD Bound
Grid Search
Token-Dependent
0.05 0.10 0.15
Prediction smoothing ()
0500100015002000Empirical DistributionFigure 3: Token-level prediction smoothing improves our bounds. Left: After training,
we optimize a conservative upper bound on the generalization bound that we would get from
Equation (2) with respect to the αhead parameters. Doing so yields a noticeable reduction
in the value of the bound. Middle: BPD generalization bound as a function of a single
global parameter chosen from a discrete number of values vs. the generalization bound for the
token-dependent αafter optimization. Right:Histogram of the values taken by α(x<i)over
different inputs.
the compressed model size. We perform this optimization post-training using a subset of the
training dataset.
We demonstrate in Figure 3(Left) that using this token-dependent αsignificantly improves the
value of the bounds. In Figure 3 (Middle), we compare to the setting where the optimal α
is obtained through a grid search, and in Figure 3(Right) we examine the distribution of α
produced by the model.
5 Compressing LLMs to Minimize Complexity
In shifting from document-level to token-level bounds, the number of data points mincreases
considerably, and thus we can afford to pay significantly more bits in the complexity of the
compressed model. In this new regime, the SubLoRA compression technique, which consists of
training only a linear subspace of LoRA-parameterized weights in the attention layers, becomes
very restrictive. Therefore, we explore other less restrictive forms of compression.
5.1 Efficient Nonlinear Parametrizations
In addition to LoRA, we explore two expressive nonlinear parametrizations f(θ)that make
efficient use of the parameter space: Kronecker structures [ 15] and Monarch matrices [ 9]. We
can use these nonlinear parametrizations directly, or in conjunction with subspace compression,
parametrizing the full parameters as θ=θ0+f(Pw)for a projection matrix P∈RD×d. After
training, the parameters are quantized and coded using arithmetic coding. We describe these
structures below.
LoRA.With LoRA [ 19], the weight matrices of linear layers are parametrized via low rank
updates. Each weight matrix W∈Ra×bis parametrized W=W0+ABforA∈Ra×r, B∈Rr×b
with a small rank r, where W0is given by the initialization and A,Bform the trainable
parameters in each layer. Rather than considering only self-attention layer weights [ 19,32], we
extend SubLoRA to all linear layers in the model and compress the biases and layernorm weights
in the subspace projection. We define f(θ) =LoRA (θ)as the transformation that unpacks θ
intoAandB, multiplies the low rank matrices and adding the initialization to form Wand
reshaping them into the parameters in the usual way.
Kronecker Product. We can represent Was a Kronecker product W=A⊗B, where ⊗
is the Kronecker product, A∈Ra1×b1, B∈Ra2×b2anda1a2=a,b1b2=b, which reduces the
8
parameters over the dense layer. This approach has been used in recent work for parameter-
efficient finetuning [ 15] and as an alternative structure for pretraining. Similarly to LoRA, we
define f(θ) = Kron( θ)as this parametrization for all linear layers.
Monarch Matrices. We also consider Monarch matrices [ 9], which employ two block diagonal
matrices A, and Btypically with AandBformed by√ablocks of size√a×√
band a reshape or
permutation operation R:W=ARB. The matrix multiplication is implemented by reshaping
the input axis ainto(√a,√a), applying matrix Aas a batched matrix multiply on one axis,
and then applying Bto the other axis by permuting the axes. Monarch matrices have shown
considerable promise as an expressive and hardware-efficient replacement for linear layers. We
define f(θ) = Monarch( θ)for their application to each of the linear layers in the network.
In our experiments, we apply all three compression techniques, with and without subspace
compression, to all linear layers in the models.
5.2 QuIP 2-Bit Quantization of LLM
In addition to pretraining LLMs in efficient nonlinear subspaces, we explore recent post-training
quantization methods to reduce the model complexity. Quantization with Incoherence Process
(QuIP) compresses LLM weights to a smaller number of bits while preserving model performance
[6].
Adaptive Rounding. For a weight matrix W∈Ra×b, QuIP minimizes the proxy quadratic
objective ℓ(ˆW) =E[∥(ˆW−W)x∥2] =tr((ˆW−W)H(ˆW−W)⊤), where ˆW∈Ra×bare the
quantized weights, x∈Rbis a vector drawn randomly from a calibration set, and His the
second moment matrix of these vectors used as a proxy Hessian [6].
Incoherence Processing. Based on the observation that incoherences between the weights W
and the proxy Hessian Hbenefit quantization, QuIP further applies incoherence post-processing
using Kronecker products of random orthogonal matrices U∈Ra×a, V∈Rb×bsuch that
˜H←V HV⊤,˜W←UWV⊤. Here U=U1⊗ ··· ⊗ UkandV=V1⊗ ··· ⊗ Vk.
Subsequent work like QuIP# improves upon QuIP by using randomized Hadamard transform
and vector quantizations [ 48]. To compute the compressed size C(h)of QuIP-quantized models,
we use gzip[12] to compress the quantized model checkpoint and obtain the term C(h)as the
bits required for the storage afterwards.
6Non-Vacuous Bounds for LLMs with Billions of Parame-
ters
As described in the previous section, we compute generalization bounds for: (i) models that are
trained through non-linear subspace compression in the form of LoRA, Kronecker product or
Monarch matrices on the OpenWebText dataset, then quantized using the same setup as Lotfi
et al.[32], or (ii) models that are pretrained on a dataset other than the OpenWebText dataset
– or on datasets that might have the OpenWebText as a subset– and made publicly available.
For the pretrained models, we either apply aggressive quantization, which is the case for GPT2,
or use QuIP 2-bit, 3-bit and 4-bit publicly-available quantized models, which is the case for
LLaMA. In the pretrained LLMs setting, we evaluate our bounds for both the OpenWebText
(9B tokens) and Amber (1.2T tokens) datasets. In both settings, we obtain highly compressed
models that lead to non-vacuous generalization bounds.
In addition to reporting generalization bounds on BPD, we also report the bounds that we
obtain on the Top-1, Top-10 and Top-100 error. The Top- kerror refers to the 0-1error in
predicting the next token among the top- kpredictions of the model. For instance, the Top-1
error for token xiis defined as 1[argmax xjp(xj|x<i=x<i) =xi], where argmaxoperates over
tokens xjacross the vocabulary. We extend this definition to the Top-k error and define it
9
Compression Approach BPD Bound Top-1 Error Top-10 Error Top-100 Error
SubLoRA [32] 10.49 90.44 71.33 49.77
Enhanced SubLoRA (Ours) 10.44 89.38 69.54 49.84
Enhanced LoRA (Ours) 7.85 78.15 52.48 31.64
Monarch Only (Ours) 7.65 75.87 47.47 28.34
Kronecker Only (Ours) 8.03 80.80 52.77 30.14
Kronecker + Subspace (Ours) 10.02 88.75 67.91 47.14
Random Guess 15.62 99.99 99.98 99.80
Table 1:Non-vacuous generalization bounds using different compression techniques
for GPT2 pretraining. We find that with the larger complexity budget afforded by the
token-level bounds, subspace compression is no longer necessary or even beneficial for the bounds.
Of the structures we consider, the Monarch parametrization performs best.
as1[xi∈argmax xj,kp(xj|x<i=x<i)], where the argmaxoperator here selects the top- ktokens
predicted by the model according to its next token probability distribution p(xj|x<i=x<i).
Our bound in Equation (2) applies not only to the log likelihood but to any bounded risk, and
therefore can be computed for the Top- kerror since it is bounded between 0and1. We call a
Top-kerror bound vacuous when the bound is larger than the random guess top- kerror equal
to1−k/V, where Vis the vocabulary size.
We present our bounds in this section and contrast the quality of the text generated by our
best performing model in terms of the BPD bound to the text generated by Lotfi et al. [32]’s
best performing model. We also compute token-level generalization bounds for antibody design,
a task where conditioning on contexts from the training dataset arises naturally. Finally, we
investigate the effect of aggressive compression on memorization vs. reasoning in LLMs. We
provide all the experimental details in Appendix B.
6.1 Token-level Bounds via Nonlinear Parametrizations
As discussed in Section 5.1, we experiment with LoRA in addition to the Kronecker and
Monarch subspace parametrizations in order to train compressed versions of GPT2 small (124M
parameters). Compared to previous work, we enhance both LoRA and SubLoRA by not only
applying the low-rank decomposition to the attention layers and the linear head, but to all the
fully-connected layers in the LLM. Additionally, we train all the bias and layer normalization
parameters instead of keeping them fixed at their values at initialization. We also use rotary
position embeddings [ 46] to directly encode the positional information into the LLM. Combined
with our proposed token-level optimization of the label smoothing probability α, we significantly
improve upon the LoRA subspace compression, as shown in Table 1. It is worth noting the
LoRA alone led to vacuous BPD document-level bounds in Lotfi et al. [32]while our version is
non-vacuous.
Among all subspace compression strategies that we explore in Table 1, Monarch without subspace
leads to the tightest token-level bound. In fact, the substantial scale of our dataset, comprising 9
billion tokens, significantly changes the trade-off between the empirical risk and the compressed
model size compared to previous work, since the compressed size factor in the bound is divided
by the size of the dataset. Consequently, we have greater flexibility in selecting larger models
that achieve an improved empirical risk. In this setting, the Monarch parametrization achieves
the best trade-off between the empirical risk and the compressed size of the model as shown in
Table 1, followed by LoRA and Kronecker. Monarch and Kronecker also perform best in terms
of the validation loss, as shown in Figure 1(Right). The new trade-off between the empirical
risk and the compressed size of the model also explains why subspace compression is no longer
beneficial in obtaining tighter bounds compared to previous work, as further reducing the
10
Model BPDTop-1 Error (%) Top-100 Error (%)
GPT2 (124M) 7.61 74 .82 26 .98
GPT2 (355M) 8.50 79.19 32.72
GPT2 (774M) 10.47 89.50 44.23
Random Guess 15.62 99.99 99.80
Table 2:Non-vacuous token-level generalization bounds for open-source pretrained
GPT2 models. Pretrained GPT2 models achieve non-vacuous bounds for next token prediction
on OpenWebText through post-training quantization only and without altering the pretraining.
Model BPDTop-1 Error (%) Top-100 Error (%)
LLaMA2-7B 4.28 47 .50 12 .56
LLaMA2-13B 4.51 47.85 14.44
LLaMA2-70B 6.39 58.26 25.04
Random Guess 14.97 99.99 99.68
Table 3:Non-vacuous token-level generalization bounds for open-source pretrained
LLaMA2 models. Pretrained LLaMA2 models achieve non-vacuous token-level bounds for
next token prediction on the Amber dataset via 2-bit post-training QuIP quantization only.
number of trainable parameters through linear subspace projection leads to a worse trade-off
between the empirical performance of the compressed model and its compressed size.
6.2Non-vacuous Bounds for Pretrained LLMs: GPT2, LLaMA1 and
LLaMA2
Intensive quantization is another way we can achieve model compression, and therefore tighter
generalization bounds. We explore the setting where we only apply post-training quantization
to pretrained LLMs and compute the corresponding token-level generalization bounds.
Pretrained GPT2 models. We apply the post-training quantization [ 31] to the publicly
available GPT2 models [ 39] of sizes 124M (GPT2 small), 354M (GPT2 medium), and 773M
(GPT2 large) parameters that were pretrained on the WebText dataset and report the numbers
in Table 2. We find that GPT2 small not only yields non-vacuous bounds, but these bounds are
quite comparable to those obtained using aggressive compression techniques in Table 1. GPT2
medium and large also achieve non-vacuous bounds despite having almost a billion parameters.
Pretrained LLaMA models. In this set of experiments, we use pretrained and pre-quantized
publicly available LLaMA1, LLaMA2 and LLaMA2-Chat models and plug in their empirical
risk and compressed size directly into our token-level bounds. We report the bounds obtained
for 2-bit LLaMA2 in Table 3. The full set of results is reported in Table 8. The bounds
are computed for the next token prediction task on the Amber dataset, which contains 1.2T
tokens. We obtain non-vacuous bounds for these models despite their large scale, ranging from 7
billion to 70 billions parameters. Our experiments show that the LLaMA2-Chat models achieve
worse generalization bounds as reported in Table 8 and Figure 1(Left), demonstrating that
fine-tuning Chat models for dialogue use cases hurts their generalization performance on next
token prediction. Although we do not know what data was used to pretrain the LLaMA models,
our bounds remain valid since they do not require for the models to be trained on the same
data that the empirical risk is evaluated on.
High-quality text generation. One of the major benefits to achieving non-vacuous generaliza-
tion bounds for the original model without aggressive subspace training is to be able to generate
high-quality text with the model that achieves the best bounds. In fact, a significant limitation
of document-level bounds is that the SubLoRA model achieving the best document-level bound
generates un-grammatical, low-quality text as demonstrated by Lotfi et al. [32]and shown in
11
Compression Approach Bits Per Dimension Top-1 Error Top-10 Error Validation Loss
Mistral 377M 2.41 31.60 26.46 0.28
Mistral 212M 2.06 26.25 21.07 0.30
Mistral 94M 1.62 19.40 14.59 0.30
Random Guess 4.86 96.56 65.51 1.46
Table 4:Models pretrained on antibody sequences achieve non-vacuous token-level
generalization bounds. Language models based on the Mistral 7B architecture with scaled-
down sizes pretrained on antibody sequences achieves non-vacuous bounds for next token
prediction on a processed subset of Observed Antibody Sequences (OAS) through post-training
quantization only. The vocabulary size of an antibody LLM is 29.
Training Context Length 01241024
GPT2-S-Quantized 13.911.19.07.9 7.6
Markov Chain 11.310.515.322.4-
Table 5:GPT2 models achieve tighter bounds than Markov chains for large context
lengths. We evaluate the generalization bound BPD achieved when k= 0,1,2,4,1024previous
tokens are made visible to a GPT2 LLM during training when predicting the next token, and
we compare to a our bounds evaluated on a sparse k-th order Markov chain trained on the same
data; with 0th order being just the empirical token probabilities. Our LLM bounds provide a
much stronger statement than what would be explained by low order Markov models.
Table 9. Moreover, document-level bounds for the original model or for models with a sufficiently
high number of trainable parameters to generate high-quality text are vacuous, as shown in
Table 1 and Figure 1 of Lotfi et al. [32]. In contrast, our top-performing model in terms of
token-level BPD bounds on the OpenWebText dataset, which is the quantized GPT2 small
model, generates high-quality text, ensuring a unique combination of practical usefulness and
tight guarantees on the population risk.
6.3 Token-Level Generalization Bounds on Antibody Sequences
Inadditiontonaturallanguages, ourtoken-levelgeneralizationboundsareparticularlydescriptive
of antibody design in biology. An antibody sequence is usually composed of 20 different amino
acid tokens to bind to a target of interest. In therapeutic antibody design, biologists propose
mutations to existing antibody sequences by changing the amino acid tokens at specific positions
in the sequence. Recent works have shown that LLMs pretrained on large antibody datasets
can be used to propose mutations conditioned on starting antibody sequences [ 44,2]. Our
token-level generalization bounds match the settings by bounding the expected next amino acid
token negative log likelihood averaged over training contexts that serve as starting sequences
for iterative mutations. In Table 4, we show that language models based on the Mistral 7B
architecture pretrained on a processed subset of the Observed Antibody Sequences (OAS) from
scratch achieves non-vacuous token-level generalization bounds [ 20,35,2]. Details of these
experiments can be found in Appendix B.9
6.4 Contextualizing GPT2 Bounds Against Markov Chains
The best token-level bound that we achieve for BPD on the OpenWebText dataset is 7.6. But
what does this value exactly mean? One might consider the possibility that our bounds are
describing only the simplest components of fitting the data that exist in the model, such as the
predictions of a 0th or 1st order Markov chain [34].
12
In Table 5 we show that this is not the case, by explicitly training a sparse k-th order Markov
chain on OpenWebText and computing our token-level bounds for the result. Sweeping over
different numbers of n-grams to use for the Markov chains, our bounds for these models cap
out at 10.5BPD and rapidly degrade with higher order as more statistics need to be stored.
We also train and compress versions of GPT2 that are restricted to only seeing ktokens as
context, mirroring the restrictions of the Markov chains. We find that for the simple 0and1st
order Markov chains, our compression via the transformer is slightly worse. However, the LLM
performs much better for higher orders.
6.5 Memorization vs. Reasoning
Large language models are capable of memorizing facts from their pretraining data, but they
also can learn highly structured patterns. As we compress a model more and more, it must
lose its ability to recall memorized facts, but it may still remember patterns, since they are
compressible. In this section, we examine the difference between memorization and reasoning
by measuring the ability of LLMs to compress structured and unstructured sequence data.
25 50 75 100
Quantization Levels0.00.20.40.60.8Accuracy (%)
Structured Sequences
Random Sequences
Figure 4: As language models are com-
pressed, they retain their understanding
of patterns, but they forget highly ran-
dom and unstructured data rapidly. Exper-
imentsperformedonGPT2modelswithdatasets
created as detailed in Section 6.5. Compression
performed via post-training quantization where
lower quantization levels reflect more aggressive
compression.To generate structured sequences, we first use
short binary expression trees to generate nu-
merical sequences of integers [ 17]. These se-
quences are highly compressible as they are
generated using short and deterministic pro-
grams. To generate unstructured sequences,
we collect the set of all unique integers from
the structured sequences and form random
sequences composed of IID samples from the
set of unique integers (see Appendix B.6 for
details). We train standard GPT2 models
from scratch on structured and random se-
quences separately. In Figure 4, we show the
integer prediction training accuracy with vary-
ing degrees of post-training quantization. We
observe that as models are quantized more
aggressively, i.e. the number of quantization
levels decreases, they forget unstructured se-
quences far faster than structured sequences.
These results parallel the findings of Jin et al.
[21]who show that smaller models can retain
in-context learning capabilities but lose their
ability to recall facts.
7 Conclusion
In this work, we introduced novel token-level generalization bounds for LLMs which are able
to accommodate the non-IID nature of the tokens within the training corpus. Combined with
different compression techniques, we achieve non-vacuous generalization bounds for LLMs with
up to 70 billion parameters. The compressed models for which we construct our bounds are
capable of producing high quality text, unlike those in prior work. While there is still have a
gap to close between the typical validation BPD and the constraint of our bounds, our bounds
are predictive of generalization and provide insights into model behaviour.
In future work, one could envision constructing new bounds that make use of the independence
structure between documents and then the non-independent structure within documents to
achieve the best of both. It would also be exciting to further explore the development of these
13
bounds for new downstream predictive tasks, in the vein of the antibody design task we briefly
consider here.
Acknowledgements
We thank Alan Amin for helpful discussions and anonymous reviewers for helpful feedback.
This work is supported by NSF CAREER IIS-2145492, NSF CDS&E-MSS 2134216, NSF
HDR-2118310, BigHat Biosciences, Capital One, and an Amazon Research Award. | Section not found | Section not found | References
[1]V. Akinwande, Y. Jiang, D. Sam, and J. Z. Kolter. Understanding prompt engineering may
not require rethinking generalization. arXiv preprint arXiv:2310.03957 , 2023.
[2]Anonymous. Bayesian optimization of antibodies informed by a generative model of evolving
sequences. Manuscript , 2024.
[3]K. Azuma. Weighted sums of certain dependent random variables. Tohoku Mathematical
Journal, Second Series , 19(3):357–367, 1967.
[4]J. Benesty, J. Chen, Y. Huang, and I. Cohen. Pearson correlation coefficient. In Noise
reduction in speech processing , pages 37–40. Springer, 2009.
[5]O.Catoni. Pac-bayesiansupervisedclassification: thethermodynamicsofstatisticallearning.
arXiv preprint arXiv:0712.0248 , 2007.
[6]J. Chee, Y. Cai, V. Kuleshov, and C. D. Sa. Quip: 2-bit quantization of large language
models with guarantees, 2024.
[7]B. Chugg, H. Wang, and A. Ramdas. A unified recipe for deriving (time-uniform) pac-bayes
bounds. Journal of Machine Learning Research , 24(372):1–61, 2023.
[8]T. Computer. Redpajama: an open dataset for training large language models, 2023. URL
https://github .com/togethercomputer/RedPajama-Data .
[9]T. Dao, B. Chen, N. S. Sohoni, A. Desai, M. Poli, J. Grogan, A. Liu, A. Rao, A. Rudra,
and C. Ré. Monarch: Expressive structured matrices for efficient and accurate training. In
International Conference on Machine Learning , pages 4690–4721. PMLR, 2022.
[10]T. Dettmers, M. Lewis, S. Shleifer, and L. Zettlemoyer. 8-bit optimizers via block-wise
quantization, 2022.
[11]T. Dettmers, S. Shmitchell, A. Roberts, K. Lee, T. B. Brown, D. Song, and C. Raffel.
Qlora: Efficient finetuning of quantized llms. arXiv preprint arXiv:2305.14314 , 2023.
[12] P. Deutsch. Rfc1952: Gzip file format specification version 4.3, 1996.
[13]G. K. Dziugaite and D. M. Roy. Computing nonvacuous generalization bounds for deep
(stochastic) neural networks with many more parameters than training data. arXiv preprint
arXiv:1703.11008 , 2017.
[14]G. K. Dziugaite, K. Hsu, W. Gharbieh, G. Arpino, and D. Roy. On the role of data in
pac-bayes bounds. In International Conference on Artificial Intelligence and Statistics ,
pages 604–612. PMLR, 2021.
[15]A. Edalati, M. Tahaei, I. Kobyzev, V. P. Nia, J. J. Clark, and M. Rezagholizadeh. Krona:
Parameter efficient tuning with kronecker adapter. arXiv preprint arXiv:2212.10650 , 2022.
[16]Z. Frantal, A. Gruslys, and D. Kiela. Gptq: Accurate post-training quantization for
generative pre-trained transformers. arXiv preprint arXiv:2210.17323 , 2022.
14
[17]M. Goldblum, M. Finzi, K. Rowan, and A. G. Wilson. The no free lunch theorem,
kolmogorov complexity, and the role of inductive biases in machine learning. arXiv preprint
arXiv:2304.05366 , 2023.
[18]S. Hayou, B. He, and G. K. Dziugaite. Probabilistic fine-tuning of pruning masks and
pac-bayes self-bounded learning. arXiv preprint arXiv:2110.11804 , 2021.
[19]E. J. Hu, Y. Shen, P. Wallis, Z. Allen-Zhu, Y. Li, S. Wang, L. Wang, and W. Chen. Lora:
Low-rank adaptation of large language models. arXiv preprint arXiv:2106.09685 , 2021.
[20]A. Q. Jiang, A. Sablayrolles, A. Mensch, C. Bamford, D. S. Chaplot, D. d. l. Casas,
F. Bressand, G. Lengyel, G. Lample, L. Saulnier, et al. Mistral 7b. arXiv preprint
arXiv:2310.06825 , 2023.
[21]T. Jin, N. Clement, X. Dong, V. Nagarajan, M. Carbin, J. Ragan-Kelley, and G. K.
Dziugaite. The cost of down-scaling language models: Fact recall deteriorates before
in-context learning. arXiv preprint arXiv:2310.04680 , 2023.
[22]J. Kim, J. H. Lee, S. Kim, J. Park, K. M. Yoo, S. J. Kwon, and D. Lee. Memory-efficient
fine-tuning of compressed large language models via sub-4-bit integer quantization. arXiv
preprint arXiv:2305.14152 , 2023.
[23]A. N. Kolmogorov. On tables of random numbers. Sankhy¯ a: The Indian Journal of
Statistics, Series A , pages 369–376, 1963.
[24]V. Kuznetsov and M. Mohri. Generalization bounds for non-stationary mixing processes.
Machine Learning , 106(1):93–117, 2017.
[25]G. G. Langdon. An introduction to arithmetic coding. IBM Journal of Research and
Development , 28(2):135–149, 1984.
[26]R. Li, L. B. Allal, Y. Zi, N. Muennighoff, D. Kocetkov, C. Mou, M. Marone, C. Akiki,
J. Li, J. Chim, Q. Liu, E. Zheltonozhskii, T. Y. Zhuo, T. Wang, O. Dehaene, M. Davaadorj,
J. Lamy-Poirier, J. Monteiro, O. Shliazhko, N. Gontier, N. Meade, A. Zebaze, M.-H. Yee,
L. K. Umapathi, J. Zhu, B. Lipkin, M. Oblokulov, Z. Wang, R. Murthy, J. Stillerman, S. S.
Patel, D. Abulkhanov, M. Zocca, M. Dey, Z. Zhang, N. Fahmy, U. Bhattacharyya, W. Yu,
S. Singh, S. Luccioni, P. Villegas, M. Kunakov, F. Zhdanov, M. Romero, T. Lee, N. Timor,
J.Ding, C.Schlesinger, H.Schoelkopf, J.Ebert, T.Dao, M.Mishra, A.Gu, J.Robinson, C.J.
Anderson, B. Dolan-Gavitt, D. Contractor, S. Reddy, D. Fried, D. Bahdanau, Y. Jernite,
C. M. Ferrandis, S. Hughes, T. Wolf, A. Guha, L. von Werra, and H. de Vries. Starcoder:
may the source be with you!, 2023.
[27]Y. Li, M. E. Ildiz, D. Papailiopoulos, and S. Oymak. Transformers as algorithms: Gen-
eralization and stability in in-context learning. In International Conference on Machine
Learning , pages 19565–19594. PMLR, 2023.
[28]Y. Liu, Q. Xu, W. Xu, and J. Zhu. Llm-qat: Data-free quantization aware training for
large language models. arXiv preprint arXiv:2305.17888 , 2023.
[29]Z. Liu, A. Qiao, W. Neiswanger, H. Wang, B. Tan, T. Tao, J. Li, Y. Wang, S. Sun,
O. Pangarkar, R. Fan, Y. Gu, V. Miller, Y. Zhuang, G. He, H. Li, F. Koto, L. Tang,
N. Ranjan, Z. Shen, X. Ren, R. Iriondo, C. Mu, Z. Hu, M. Schulze, P. Nakov, T. Baldwin,
and E. P. Xing. Llm360: Towards fully transparent open-source llms, 2023.
[30]I. Loshchilov and F. Hutter. Decoupled weight decay regularization. arXiv preprint
arXiv:1711.05101 , 2017.
[31]S. Lotfi, M. Finzi, S. Kapoor, A. Potapczynski, M. Goldblum, and A. G. Wilson. Pac-bayes
compression bounds so tight that they can explain generalization. Advances in Neural
Information Processing Systems , 35:31459–31473, 2022.
15
[32]S. Lotfi, M. Finzi, Y. Kuang, T. G. Rudner, M. Goldblum, and A. G. Wilson. Non-vacuous
generalization bounds for large language models. arXiv preprint arXiv:2312.17173 , 2023.
[33]M. Mohri and A. Rostamizadeh. Stability bounds for non-iid processes. Advances in Neural
Information Processing Systems , 20, 2007.
[34] J. R. Norris. Markov chains . Number 2. Cambridge university press, 1998.
[35]T. H. Olsen, F. Boyles, and C. M. Deane. Observed antibody space: A diverse database of
cleaned, annotated, and translated unpaired and paired antibody sequences. Protein Sci. ,
31(1):141–146, Jan. 2022.
[36]G. Park, J. Kim, J. Kim, E. Choi, S. Kim, S. Kim, M. Lee, H. Shin, and J. Lee. Lut-gemm:
Quantized matrix multiplication based on luts for efficient inference in large-scale generative
language model. arXiv preprint arXiv:2206.09557 , 2022.
[37]G. Penedo, Q. Malartic, D. Hesslow, R. Cojocaru, A. Cappelli, H. Alobeidli, B. Pannier,
E. Almazrouei, and J. Launay. The refinedweb dataset for falcon llm: Outperforming
curated corpora with web data, and web data only, 2023.
[38]M. Pérez-Ortiz, O. Rivasplata, J. Shawe-Taylor, and C. Szepesvári. Tighter risk certificates
for neural networks. Journal of Machine Learning Research , 22(227):1–40, 2021.
[39]A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, I. Sutskever, et al. Language models
are unsupervised multitask learners. OpenAI blog , 1(8):9, 2019.
[40]A. Rakhlin and K. Sridharan. On equivalence of martingale tail bounds and deterministic
regret inequalities. In Conference on Learning Theory , pages 1704–1722. PMLR, 2017.
[41]L. Ralaivola, M. Szafranski, and G. Stempfel. Chromatic pac-bayes bounds for non-iid
data: Applications to ranking and stationary β-mixing processes. The Journal of Machine
Learning Research , 11:1927–1956, 2010.
[42]C. RelaxML. Quip#: Quip with lattice codebooks. https://github .com/Cornell-
RelaxML/quip-sharp , 2024.
[43]S. Shalev-Shwartz and S. Ben-David. Understanding machine learning: From theory to
algorithms . Cambridge university press, 2014.
[44]R. W. Shuai, J. A. Ruffolo, and J. J. Gray. Generative language modeling for antibody
design.bioRxiv, pages 2021–12, 2021.
[45]R. J. Solomonoff. A formal theory of inductive inference. part i. Information and control , 7
(1):1–22, 1964.
[46]J. Su, M. Ahmed, Y. Lu, S. Pan, W. Bo, and Y. Liu. Roformer: Enhanced transformer
with rotary position embedding. Neurocomputing , 568:127063, 2024.
[47]H.Touvron, L.Martin, K.Stone, P.Albert, A.Almahairi, Y.Babaei, N.Bashlykov, S.Batra,
P. Bhargava, S. Bhosale, D. Bikel, L. Blecher, C. C. Ferrer, M. Chen, G. Cucurull, D. Esiobu,
J. Fernandes, J. Fu, W. Fu, B. Fuller, C. Gao, V. Goswami, N. Goyal, A. Hartshorn,
S. Hosseini, R. Hou, H. Inan, M. Kardas, V. Kerkez, M. Khabsa, I. Kloumann, A. Korenev,
P. S. Koura, M.-A. Lachaux, T. Lavril, J. Lee, D. Liskovich, Y. Lu, Y. Mao, X. Martinet,
T. Mihaylov, P. Mishra, I. Molybog, Y. Nie, A. Poulton, J. Reizenstein, R. Rungta,
K. Saladi, A. Schelten, R. Silva, E. M. Smith, R. Subramanian, X. E. Tan, B. Tang,
R.Taylor, A.Williams, J.X.Kuan, P.Xu, Z.Yan, I.Zarov, Y.Zhang, A.Fan, M.Kambadur,
S. Narang, A. Rodriguez, R. Stojnic, S. Edunov, and T. Scialom. Llama 2: Open foundation
and fine-tuned chat models, 2023.
[48]A. Tseng, J. Chee, Q. Sun, V. Kuleshov, and C. De Sa. Quip#: Even better llm quantization
with hadamard incoherence and lattice codebooks. arXiv preprint arXiv:2402.04396 , 2024.
16
[49]K. Wang, X. Hu, and J. Zhang. Fast clonal family inference from large-scale B cell repertoire
sequencing data. Cell Rep Methods , 3(10):100601, Oct. 2023.
[50]Q. Xu, W. Xu, and J. Zhu. Tensorgpt: Efficient compression of the embedding layer in
llms based on the tensor-train decomposition. arXiv preprint arXiv:2307.00526 , 2023.
[51]C. Zhang, S. Bengio, M. Hardt, B. Recht, and O. Vinyals. Understanding deep learning
(still) requires rethinking generalization. Communications of the ACM , 64(3):107–115, 2021.
[52]R.-R. Zhang and M.-R. Amini. Generalization bounds for learning under graph-dependence:
A survey. arXiv preprint arXiv:2203.13534 , 2022.
[53]W. Zhou, V. Veitch, M. Austern, R. P. Adams, and P. Orbanz. Non-vacuous generalization
bounds at the imagenet scale: a pac-bayesian compression approach. In International
Conference on Learning Representations , 2019.
17
A Token-Level Martingale Bound
A.1 Proof of the Main Theorem
Theorem 2. With probability at least 1−δover the randomness in a sampled sequence
x1, x2, . . . , x m, if the negative log likelihood of a model h∈ Hcan be bounded −log2ph(·|x<i)∈
[a, a+ ∆ i]for some ∆i(possibly a function of h), then the negative log likelihood of the data of
a given hypothesis hsatisfies
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m,(4)
where ˆ∆=q
1
mPm
i=1∆2
i, the expectation is taken over Xi∼p(Xi|x<i)from the data generating
process, and P(h)is any normalized prior over a discrete hypothesis space Hthat does not
depend on {xi}m
i=1.
Proof sketch. The proof of Theorem 1 is an application of Azuma’s inequality [ 3] and can be
broken down into the following steps:
•Construct a martingale difference sequence from the difference between the NLL on token
xi, and its expectation given the tokens x<i. From the boundedness of NLL one can show
that the differences are bounded.
•Apply Azuma’s inequality for each hypothesis, choosing failure probability proportional to
the chosen prior P(h).
•Perform a union bound of the failure probabilities over all hypotheses. If all of the
hypotheses satisfy the bound simultaneously, then so does the data dependent hypothesis
h∗.
Proof.Given the autoregressive predictions R(h, xi, x<i) :=−log2ph(xi|x<i)where x<i:=
{x1, x2, . . . , x i−1}. Let{xi}denote the actual values of the sequence that were found empirically,
and{Xi}be the random variables for these quantities.
The collection of random variables (indexed by i)Zi=E[R(h, X i, x<i)|x<i]−R(h, X i, x<i)
form a Martingale difference sequence with respect to x<i. Note here that the expectation is
over the distribution Xi∼p(Xi|x<i). From the construction, E[Zi|x<i] = 0and the sequence
is bounded: Ai=E[R(h, X i, x<i)|x<i]−a≤Zi≤∆i+E[R(h, X i, x<i)|x<i]−a=Bi, with
Bi−Ai= ∆ i.
∆imay depend on x≥ibut only through it’s dependence on the hypothesis h({x}m
i=1). For a
fixed hwe may conclude thatPm
i=1Ziis bounded difference Martingale sequence (with respect
to{x<i}m
i=1), and we can apply Azuma’s inequality [3] to derive that for any t >0:
P mX
i=1Zi> mt
≤exp
−2m2t2/mX
i=1∆2
i
P 1
mmX
i=1Zi> t
≤exp
−2mt2/ˆ∆2
.
Judiciously choosing
t(h) =ˆ∆r
log 1/P(h) + log 1 /δ
2m,
18
we have that P 1
mPm
i=1Zi> t(h)
=P(h)δ.
Applying a union over the eventsS
h∈H1
mPm
i=1Zi(h)> t(h)
, we have
P 1
mmX
i=1Zi> t(h)
≤X
hP(h)δ=δ,
therefore P 1
mPm
i=1Zi≤t(h)
>1−δ. Unpacking the definition of Zi, we have that with
probability at least 1−δ
1
mmX
i=1E[R(h, X i, x<i)|x<i]≤1
mmX
i=1R(h, xi, x<i) +ˆ∆r
log 1/P(h) + log 1 /δ
2m.
Expressed in terms of the log likelihood, we can write this as:
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m
A.2 Empirical Risk Subsampling
We evaluate our bounds for the OpenWebtext and Amber datasets which contain 9 billion and
1.2 trillion tokens, respectively. Computing the exact empirical risk for these datasets would be
prohibitively expensive. Therefore, we use subsampling for the evaluation of the empirical risk
to accelerate bound computation. In Equation (2), we use the following inequality which holds
with probability at least 1−δ2:
−1
mlog2ph(x≤m)≤ −1
nnX
j=1log2ph(xσ(j)|x<σ(j)) +ˆ∆r
log 1/δ2
2n(5)
for a subsample of size nwhere σis a random permutation. We choose δ1in Equation (2) with
respect to a new overall failure probability δto be δ1=δn/(n+m)and choose δ2=δm/(n+m)
so that the overall failure probability is still δ. The proof is simple and similar to that provided
in Lotfi et al. [32].
B Experimental Details
B.1 Pretraining with Nonlinear Parametrizations
To achieve the necessary model compression level for computing non-vacuous bounds, we pretrain
GPT2 Small with 124 million parameters on the OpenWebText1dataset based on the nanoGPT
implementation2[39]. We parametrize the linear layers of CausalSelfAttention ,MLP, and the
LinearHead of the GPT2 models with our nonlinear compression techniques (LoRA, Kronecker,
Monarch), where we use a bias vector except for the LinearHead layer. For LoRA and Kronecker,
we use weight tying between the token embedding and the final LinearHead layer parameterized
by nonlinear compression techniques. We also train the layer norm parameters in addition to
all of the nonlinear projection parameters applied to the linear layers. For Monarch, we only
train the linear layers parameterized by Monarch matrices. We also combine the three nonlinear
parametrizations with linear subspace projection, where all the trainable parameters θare
projected into a subspace of parameters wusing a projection matrix P, such that θ=θ0+Pw.
We vary the dimension of was a hyperparameter in the bound evaluation.
1http://Skylion007 .github .io/OpenWebTextCorpus
2https://github .com/karpathy/nanoGPT
19
For all the pretraining experiments, we use a batch size of 8, a sequence length of 1024, and
a standard AdamW optimizer [ 30] with a learning rate of 0.0002. We perform a learning
rate warm-up for 500iterations, and we apply rotary embedding [ 46] to all three nonlinear
parametrizations.
B.1.1 Hyperparameter Sweeps for LoRA
LoRA.We sweep over LoRA rank values r∈ {1,4,16,32,64,128,256}. We choose a learning
rate of 0.0002with a LoRA dropout value of 0.1and LoRA alpha value of 32.
SubLoRA. We report the rank rand the corresponding subspace dimension values that we
sweep over for SubLoRA in Table 6.
Rank rSubspace Dimension d
1 25000
4 50000
8 50000
16 50000
32 10000, 750000
64 25000, 2000000
128 7000000, 15000000
Table 6: Hyperparameter sweep for SubLoRA. For all the SubLoRA pretraining experiments,
we use a learning rate of 0.0002, a LoRA dropout value of 0.1, and a LoRA alpha value of 32.
B.1.2 Hyperparameter Sweeps for Kronecker
For the Kronecker factorization W=A⊗B, we choose the matrices AandBsuch that
A∈Ra1×b1, B∈Ra2×b2where a1a2=aandb1b2=b. We sweep over all possible combinations
of{a1, a2}and{b1, b2}by performing prime factorizations with multiplicity on the numbers
a, band enumerating all possible combinations. All of our Kronecker pretraining experiments
use a learning rate of 0.0002.
B.1.3 Hyperparameter Sweeps for Monarch
For the Monarch parametrization, we relax the restriction for the number of blocks to be strictly√aand instead by a number divisible by ato sweep over different numbers of blocks. We
also perform experiments for Monarch where we are using absolute position encodings and
experiments where we are only applying the Monarch factorization to the attention layers and
the linear classification heads.
B.2 Quantization
Quantization Following Lotfi et al. [31], we apply post-training quantization of the trainable
weights that correspond to the subspace parameters and/or the LoRA, Kronecker, Monarch
parameters along with layer norm weights depending on the compression setup.
Experiments on QuIP-quantized Models. We compute token-level bounds on pretrained
LLaMA1 and LLaMA2 models [ 47] quantized with QuIP with publicly-available checkpoints
[42]. Although we do not know what data was used to pretrain these models, we can evaluate
the generalization bound on the Amber dataset and consider other tokens used in training as a
data-dependent prior.
20
B.3 Bounds Evaluation
In the sequence of text, we use end of text tokens (EOT) which separate the documents. In
this way, we can consider concatenating many documents together to form one long sequence.
As a result of the EOT tokens and the structure of the text, the distribution p(xi|x<i)can
be simplified into p(xi|xk, xk+1, . . . x i−1)where kis the index of the most recent EOT token
because the documents are sampled independently. In the evaluation of the LLM we likewise
have no dependence on tokens outside the given document in question.
To compute token-level bounds, we evaluate all of our generalization bounds with failure
probability δ= 0.05and subsample size of n= 10,0000tokens from the OpenWebText training
dataset of size m= 9billion tokens or the Amber dataset of size m= 1.2trillion tokens.
B.4 Correlation with Downstream Performance
We retrieve the downstream task performance of difference GPT2 variants ranging in scale
from 117M to 1.5B averaged over the downstream datasets as shown in Table 7. To obtain an
approximation of the conditional BPD expectation that we bound in Equation (2), we resample
xifrom a LLaMA2-7B given fixed training contexts x<ifrom the Amber dataset. We use a
sample size equal to 10,000samples.
Model
SizeLAMBADA
(PPL)LAMBADA
(ACC)CBT-CN
(ACC)CBT-NE
(ACC)WikiText2
(PPL)PTB
(PPL)WikiText103
(PPL)1BW
(PPL)
117M 35.13 45.99 87.65 83.4 29.41 65.85 37.50 75.20
345M 15.60 55.48 92.35 87.1 22.76 47.33 26.37 55.72
762M 10.87 60.12 93.45 88.0 19.93 40.31 22.05 44.575
1542M 8.63 63.24 93.30 89.05 18.34 35.76 17.48 42.16
Table 7: Zero-shot downstream task performance for GPT2 models with different model sizes as
reported in Radford et al. [39].
B.5 Markov Chain Comparison
For training the Markov chains, we reuse the Byte Pair Encoding (BPE) tokenization to separate
out the effect of the tokenizer. We apply prediction smoothing at level α= 0.1to the Markov
models to give them nonzero probability to ngrams that have not been seen in the training data
and limit the worst case NLL of a single token.
For constructing generalization bounds with the Markov chain, we upper bound the complexity
term log1/P(h)similarly to the large language models by performing quantization and com-
pression. We store and update the Markov chains sparsely, which becomes necessary when
considering the high order variants. In storing the model, we use a dictionary mapping each
prefix concatenated with the following token to a count. The counts can then be converted into
probabilities by normalizing by the count containing just the prefix. We quantize the counts
and store them in 16bits, and we store the keys using a basic encoding. For training, we train
on a subsample of 106tokens from the training corpus, sufficient for the performance of the
Markov chains to converge.
B.6 Memorization Experiment
Following Goldblum et al. [17], we select a complexity value of 4, which reflects the difficulty of
the task, and a sequence length of 30and generate 984sequences as the training dataset for
structured sequences. To build our baseline random sequences, we collect all unique integers in
the generated sequences into a set. We then sample integers IID from a uniform distribution
21
over the set of unique integers from the structured sequences to build the baseline dataset.
Our vocabulary size is 12as we only have integers, the beginning of text token, and an
additional delimiter token. The delimiter tokens are placed between distinct numbers during
our tokenization process. We use a GPT-2 Small model with 124M parameters and train it on
the structured and random sequences separately with a learning rate of 0.0001for1000epochs.
Our quantization procedure is the same as described in | Appendix A.1.
On the right-hand side of the bound is the conventional empirical risk: −1
mlog2ph(x≤m) =
−1
mP
ilog2ph(xi|x<i)onthemeasuredsequenceandacomplexityterm log1/P(h). Wedescribe
in detail how we sample sequence x≤mand compute the empirical risk in Section 4.2. The
quantity which we are bounding on the left-hand side is the expected next token negative
log-likelihood under resampling from the data generating process, averaged over the different
contexts that have been encountered in the training set. The bound ensures generalization on
contexts seen at training when the next tokens are resampled, but not on data with contexts
that are different. However, given how diffuse the distribution over next tokens is, e.g., at the
beginning of a new sentence, our bounds remain predictive of generalization and achieving a
non-vacuous bound requires generalization. We further discuss the interpretation of our bounds
in Section 4.3.
5
2 4 6
Entropy0100002000030000Frequency
0248161282565127681023
Token Index02468Entropy
108
109
Trainable Parameters20406080100120PPL / Acc (%)PPL
BPDACC
4.04.24.44.64.85.0
Bound Objective (BPD)Figure 2: Our bounds analyze a quantity that is meaningful and predictive of
generalization. Left: Using LLaMA2-7B, we compute the entropy of p(xi|x<i), where the
context x<iis fixed and sampled from the Amber training dataset. The distribution over next
tokens given a fixed context from the training data is indeed diffuse and characterized by high
entropy values. Middle: Entropy of p(xi|x<i)as a function of the token index ishown on the
x-axis for a context length L= 1024. The average entropy has a decreasing trend but remains
high overall; note that the average entropy for i= 768is as high as the average entropy for
i= 128.Right:On the left y-axis, we plot the average zero-shot accuracy (ACC) and perplexity
(PPL) achieved by GPT2 models ranging in scale from 117M to 1.5B averaged over downstream
datasets, as reported in Radford et al. [39]. On the right y-axis, we plot an approximation of
the conditional BPD expectation that we bound in Equation (2) where we resample xifrom a
LLaMA2-7B given fixed training contexts x<ifrom the Amber dataset. The approximation of
the BPD objective that we bound achieves 97.9%and99.1%correlation with the accuracy and
perplexity, respectively.
4.2 Sampling and Empirical Risk Evaluation
In this section, we more precisely define the sequence x≤mfor which we compute the empirical
risk in Equation (2). We construct a sample x≤mfrom the stochastic process pdataby first
sampling independent and identically distributed documents, e.g., the documents that form
the OpenWebText dataset. Then, we concatenate these documents deterministically using end
of text (EOT) tokens. Consequently, the ground truth stochastic process has the following
property:
pdata(xi|x<i) =pdata(xi|xk, ...., x i−1), (3)
where xkis the previous EOT token. This equality holds exactly due to how the stochastic
process is implemented.
On the other hand, it would not be guaranteed that a generative model ph(x)satisfies the
property in Equation (3) apriori if the model were allowed to attend to tokens x<k, even when
the data generating process has this property. However, we explicitly prohibit our generative
model hfrom attending to tokens x<kthrough the attention mask, as we have the flexibility to
do so in defining our hypothesis class and model family. Therefore, our model phthat we bound
also satisfies this property ph(xi|x<i) =ph(xi|xk, ...., x i−1)exactly, and not approximately.
In conclusion, the empirical risk for our generative model hand a sequence x≤msampled from
the stochastic process defined above can be written as follows:
−1
mlog2ph(x≤m) =−1
mX
ilog2ph(xi|x<i) =−1
mX
ilog2ph(xi|xk, . . . x i−1),
where xkis the nearest EOT token occurring before xi. Given the large size of the OpenWebText
and Amber datasets, containing 9 billions and 1.2 trillion tokens respectively, we use subsampling
for the evaluation of the empirical risk. More details can be found in Appendix A.2.
6
4.3 Token-level Bounds Are Predictive of Generalization
Token-level vs. document-level bounds. In contrast to document-level bounds, token-level
bounds increase the number of samples, driving down the size of the complexity term, and
do not require the IID assumption. Whereas the number of samples previously would be the
number of documents, it is now simply the number of tokens in the dataset, a far higher
number. As a consequence of decreasing the complexity term, the empirical risk will be a more
significant contributor to our bounds compared to document-level bounds. Therefore, we achieve
non-vacuous bounds for much larger and more performant models that generate high-quality
text. This development brings our theoretical bounds much closer to aligning with empirical
generalization.
Interpretation of token-level bounds. It is important to note the difference between the
quantity that we bound1
mPm
i=1E[−log2ph(Xi|x<i)|x<i], which is conditioned on contexts
seen at training, and the expected risk E[−log2ph(Xi|x<i)]under resampling from the data
generating process where new contexts can be sampled from this process. However, the
resampled next tokens xi|x<iare not necessarily from the training set, and to the extent that
the distribution over next tokens is entropic, we are measuring a different quantity than the
empirical training performance of the hypothesis h. Moreover, we know that the distribution
over next tokens is often indeed diffuse; for instance, many words have common synonyms. The
distribution over next tokens is especially diffuse when we start a new sentence, for example. We
demonstrate how diffuse the distribution p(xi|x<i)is for fixed contexts x<ifrom the publicly
available Amber training dataset [ 29] (see Appendix B.7) by sampling xi|x<iusing LLaMA2-7B
to approximate the generative process. Figure 2(Left) shows that, indeed, the distribution
p(xi|x<i)is characterized by a high entropy for a large number of tokens. In Figure 2(Middle),
we plot the entropy of p(xi|x<i)for each index iin a context of length 1024. This figure
confirms our intuition that the next token distribution is particularly diffuse at the beginning of
a sentence, while it decreases for later tokens but remains relatively high. Given how diffuse
the distribution is and the large number of possible sentences, it is broadly infeasible to make
predictions on new resampled tokens from the empirical distribution alone.
Our bounds are predictive of downstream performance. We compute an approximation
of the quantity that we bound in Equation (2) by sampling next tokens xiusing LLaMA2-7B
given fixed contexts x<ifrom the Amber dataset. We plot this quantity on the right y-axis of
Figure 2(Right), and show on the left y-axis the performance of GPT2 models of varying sizes
on downstream datasets as reported in Radford et al. [39]; see Appendix B.4 for more details.
Not only does the approximation of the BPD objective show the same trend as the downstream
performance for different GPT2 variants, but it also achieves 97.9%and99.1%correlation [ 4]
with downstream task accuracy and perplexity metrics, respectively.
In short, our bounds go significantly beyond the observation that the empirical distribution
converges to the true distribution, and are predictive of generalization on downstream tasks.
Achieving a non-vacuous token-level bound requires generalization. We provide further interpre-
tation of the bounds, including a protein application, in Section 6.
4.4 Token-Level Prediction Smoothing
Rather than using a single label smoothing αfor all data points, we propose to use the
network itself to determine which tokens warrant more confidence and which ones require more
smoothing to limit their worst-case behavior. We perform token-level prediction smoothing
by adding a linear head to the LLM that outputs the probability αfor each token, such that
ph(xi|x<i) =
1−αθ(x<i)
pθ(xi|x<i) +αθ(x<i)/V. The training objective corresponds to the
upper bound in Equation (2) rather than the empirical risk alone, where the αparameter factors
into the bound via the interval size ∆i= log2
1 + (1 −αθ(x<i))V/α θ(x<i)
. Therefore, the
values of αθ(x<i)are adjusted to achieve the best trade-off between the empirical risk and
7
106
107
Trainable Parameters8.59.510.5Bound Loss
Before Optimization
After Optimization
104
103
102
101
Prediction smoothing ()
8.08.48.8BPD Bound
Grid Search
Token-Dependent
0.05 0.10 0.15
Prediction smoothing ()
0500100015002000Empirical DistributionFigure 3: Token-level prediction smoothing improves our bounds. Left: After training,
we optimize a conservative upper bound on the generalization bound that we would get from
Equation (2) with respect to the αhead parameters. Doing so yields a noticeable reduction
in the value of the bound. Middle: BPD generalization bound as a function of a single
global parameter chosen from a discrete number of values vs. the generalization bound for the
token-dependent αafter optimization. Right:Histogram of the values taken by α(x<i)over
different inputs.
the compressed model size. We perform this optimization post-training using a subset of the
training dataset.
We demonstrate in Figure 3(Left) that using this token-dependent αsignificantly improves the
value of the bounds. In Figure 3 (Middle), we compare to the setting where the optimal α
is obtained through a grid search, and in Figure 3(Right) we examine the distribution of α
produced by the model.
5 Compressing LLMs to Minimize Complexity
In shifting from document-level to token-level bounds, the number of data points mincreases
considerably, and thus we can afford to pay significantly more bits in the complexity of the
compressed model. In this new regime, the SubLoRA compression technique, which consists of
training only a linear subspace of LoRA-parameterized weights in the attention layers, becomes
very restrictive. Therefore, we explore other less restrictive forms of compression.
5.1 Efficient Nonlinear Parametrizations
In addition to LoRA, we explore two expressive nonlinear parametrizations f(θ)that make
efficient use of the parameter space: Kronecker structures [ 15] and Monarch matrices [ 9]. We
can use these nonlinear parametrizations directly, or in conjunction with subspace compression,
parametrizing the full parameters as θ=θ0+f(Pw)for a projection matrix P∈RD×d. After
training, the parameters are quantized and coded using arithmetic coding. We describe these
structures below.
LoRA.With LoRA [ 19], the weight matrices of linear layers are parametrized via low rank
updates. Each weight matrix W∈Ra×bis parametrized W=W0+ABforA∈Ra×r, B∈Rr×b
with a small rank r, where W0is given by the initialization and A,Bform the trainable
parameters in each layer. Rather than considering only self-attention layer weights [ 19,32], we
extend SubLoRA to all linear layers in the model and compress the biases and layernorm weights
in the subspace projection. We define f(θ) =LoRA (θ)as the transformation that unpacks θ
intoAandB, multiplies the low rank matrices and adding the initialization to form Wand
reshaping them into the parameters in the usual way.
Kronecker Product. We can represent Was a Kronecker product W=A⊗B, where ⊗
is the Kronecker product, A∈Ra1×b1, B∈Ra2×b2anda1a2=a,b1b2=b, which reduces the
8
parameters over the dense layer. This approach has been used in recent work for parameter-
efficient finetuning [ 15] and as an alternative structure for pretraining. Similarly to LoRA, we
define f(θ) = Kron( θ)as this parametrization for all linear layers.
Monarch Matrices. We also consider Monarch matrices [ 9], which employ two block diagonal
matrices A, and Btypically with AandBformed by√ablocks of size√a×√
band a reshape or
permutation operation R:W=ARB. The matrix multiplication is implemented by reshaping
the input axis ainto(√a,√a), applying matrix Aas a batched matrix multiply on one axis,
and then applying Bto the other axis by permuting the axes. Monarch matrices have shown
considerable promise as an expressive and hardware-efficient replacement for linear layers. We
define f(θ) = Monarch( θ)for their application to each of the linear layers in the network.
In our experiments, we apply all three compression techniques, with and without subspace
compression, to all linear layers in the models.
5.2 QuIP 2-Bit Quantization of LLM
In addition to pretraining LLMs in efficient nonlinear subspaces, we explore recent post-training
quantization methods to reduce the model complexity. Quantization with Incoherence Process
(QuIP) compresses LLM weights to a smaller number of bits while preserving model performance
[6].
Adaptive Rounding. For a weight matrix W∈Ra×b, QuIP minimizes the proxy quadratic
objective ℓ(ˆW) =E[∥(ˆW−W)x∥2] =tr((ˆW−W)H(ˆW−W)⊤), where ˆW∈Ra×bare the
quantized weights, x∈Rbis a vector drawn randomly from a calibration set, and His the
second moment matrix of these vectors used as a proxy Hessian [6].
Incoherence Processing. Based on the observation that incoherences between the weights W
and the proxy Hessian Hbenefit quantization, QuIP further applies incoherence post-processing
using Kronecker products of random orthogonal matrices U∈Ra×a, V∈Rb×bsuch that
˜H←V HV⊤,˜W←UWV⊤. Here U=U1⊗ ··· ⊗ UkandV=V1⊗ ··· ⊗ Vk.
Subsequent work like QuIP# improves upon QuIP by using randomized Hadamard transform
and vector quantizations [ 48]. To compute the compressed size C(h)of QuIP-quantized models,
we use gzip[12] to compress the quantized model checkpoint and obtain the term C(h)as the
bits required for the storage afterwards.
6Non-Vacuous Bounds for LLMs with Billions of Parame-
ters
As described in the previous section, we compute generalization bounds for: (i) models that are
trained through non-linear subspace compression in the form of LoRA, Kronecker product or
Monarch matrices on the OpenWebText dataset, then quantized using the same setup as Lotfi
et al.[32], or (ii) models that are pretrained on a dataset other than the OpenWebText dataset
– or on datasets that might have the OpenWebText as a subset– and made publicly available.
For the pretrained models, we either apply aggressive quantization, which is the case for GPT2,
or use QuIP 2-bit, 3-bit and 4-bit publicly-available quantized models, which is the case for
LLaMA. In the pretrained LLMs setting, we evaluate our bounds for both the OpenWebText
(9B tokens) and Amber (1.2T tokens) datasets. In both settings, we obtain highly compressed
models that lead to non-vacuous generalization bounds.
In addition to reporting generalization bounds on BPD, we also report the bounds that we
obtain on the Top-1, Top-10 and Top-100 error. The Top- kerror refers to the 0-1error in
predicting the next token among the top- kpredictions of the model. For instance, the Top-1
error for token xiis defined as 1[argmax xjp(xj|x<i=x<i) =xi], where argmaxoperates over
tokens xjacross the vocabulary. We extend this definition to the Top-k error and define it
9
Compression Approach BPD Bound Top-1 Error Top-10 Error Top-100 Error
SubLoRA [32] 10.49 90.44 71.33 49.77
Enhanced SubLoRA (Ours) 10.44 89.38 69.54 49.84
Enhanced LoRA (Ours) 7.85 78.15 52.48 31.64
Monarch Only (Ours) 7.65 75.87 47.47 28.34
Kronecker Only (Ours) 8.03 80.80 52.77 30.14
Kronecker + Subspace (Ours) 10.02 88.75 67.91 47.14
Random Guess 15.62 99.99 99.98 99.80
Table 1:Non-vacuous generalization bounds using different compression techniques
for GPT2 pretraining. We find that with the larger complexity budget afforded by the
token-level bounds, subspace compression is no longer necessary or even beneficial for the bounds.
Of the structures we consider, the Monarch parametrization performs best.
as1[xi∈argmax xj,kp(xj|x<i=x<i)], where the argmaxoperator here selects the top- ktokens
predicted by the model according to its next token probability distribution p(xj|x<i=x<i).
Our bound in Equation (2) applies not only to the log likelihood but to any bounded risk, and
therefore can be computed for the Top- kerror since it is bounded between 0and1. We call a
Top-kerror bound vacuous when the bound is larger than the random guess top- kerror equal
to1−k/V, where Vis the vocabulary size.
We present our bounds in this section and contrast the quality of the text generated by our
best performing model in terms of the BPD bound to the text generated by Lotfi et al. [32]’s
best performing model. We also compute token-level generalization bounds for antibody design,
a task where conditioning on contexts from the training dataset arises naturally. Finally, we
investigate the effect of aggressive compression on memorization vs. reasoning in LLMs. We
provide all the experimental details in Appendix B.
6.1 Token-level Bounds via Nonlinear Parametrizations
As discussed in Section 5.1, we experiment with LoRA in addition to the Kronecker and
Monarch subspace parametrizations in order to train compressed versions of GPT2 small (124M
parameters). Compared to previous work, we enhance both LoRA and SubLoRA by not only
applying the low-rank decomposition to the attention layers and the linear head, but to all the
fully-connected layers in the LLM. Additionally, we train all the bias and layer normalization
parameters instead of keeping them fixed at their values at initialization. We also use rotary
position embeddings [ 46] to directly encode the positional information into the LLM. Combined
with our proposed token-level optimization of the label smoothing probability α, we significantly
improve upon the LoRA subspace compression, as shown in Table 1. It is worth noting the
LoRA alone led to vacuous BPD document-level bounds in Lotfi et al. [32]while our version is
non-vacuous.
Among all subspace compression strategies that we explore in Table 1, Monarch without subspace
leads to the tightest token-level bound. In fact, the substantial scale of our dataset, comprising 9
billion tokens, significantly changes the trade-off between the empirical risk and the compressed
model size compared to previous work, since the compressed size factor in the bound is divided
by the size of the dataset. Consequently, we have greater flexibility in selecting larger models
that achieve an improved empirical risk. In this setting, the Monarch parametrization achieves
the best trade-off between the empirical risk and the compressed size of the model as shown in
Table 1, followed by LoRA and Kronecker. Monarch and Kronecker also perform best in terms
of the validation loss, as shown in Figure 1(Right). The new trade-off between the empirical
risk and the compressed size of the model also explains why subspace compression is no longer
beneficial in obtaining tighter bounds compared to previous work, as further reducing the
10
Model BPDTop-1 Error (%) Top-100 Error (%)
GPT2 (124M) 7.61 74 .82 26 .98
GPT2 (355M) 8.50 79.19 32.72
GPT2 (774M) 10.47 89.50 44.23
Random Guess 15.62 99.99 99.80
Table 2:Non-vacuous token-level generalization bounds for open-source pretrained
GPT2 models. Pretrained GPT2 models achieve non-vacuous bounds for next token prediction
on OpenWebText through post-training quantization only and without altering the pretraining.
Model BPDTop-1 Error (%) Top-100 Error (%)
LLaMA2-7B 4.28 47 .50 12 .56
LLaMA2-13B 4.51 47.85 14.44
LLaMA2-70B 6.39 58.26 25.04
Random Guess 14.97 99.99 99.68
Table 3:Non-vacuous token-level generalization bounds for open-source pretrained
LLaMA2 models. Pretrained LLaMA2 models achieve non-vacuous token-level bounds for
next token prediction on the Amber dataset via 2-bit post-training QuIP quantization only.
number of trainable parameters through linear subspace projection leads to a worse trade-off
between the empirical performance of the compressed model and its compressed size.
6.2Non-vacuous Bounds for Pretrained LLMs: GPT2, LLaMA1 and
LLaMA2
Intensive quantization is another way we can achieve model compression, and therefore tighter
generalization bounds. We explore the setting where we only apply post-training quantization
to pretrained LLMs and compute the corresponding token-level generalization bounds.
Pretrained GPT2 models. We apply the post-training quantization [ 31] to the publicly
available GPT2 models [ 39] of sizes 124M (GPT2 small), 354M (GPT2 medium), and 773M
(GPT2 large) parameters that were pretrained on the WebText dataset and report the numbers
in Table 2. We find that GPT2 small not only yields non-vacuous bounds, but these bounds are
quite comparable to those obtained using aggressive compression techniques in Table 1. GPT2
medium and large also achieve non-vacuous bounds despite having almost a billion parameters.
Pretrained LLaMA models. In this set of experiments, we use pretrained and pre-quantized
publicly available LLaMA1, LLaMA2 and LLaMA2-Chat models and plug in their empirical
risk and compressed size directly into our token-level bounds. We report the bounds obtained
for 2-bit LLaMA2 in Table 3. The full set of results is reported in Table 8. The bounds
are computed for the next token prediction task on the Amber dataset, which contains 1.2T
tokens. We obtain non-vacuous bounds for these models despite their large scale, ranging from 7
billion to 70 billions parameters. Our experiments show that the LLaMA2-Chat models achieve
worse generalization bounds as reported in Table 8 and Figure 1(Left), demonstrating that
fine-tuning Chat models for dialogue use cases hurts their generalization performance on next
token prediction. Although we do not know what data was used to pretrain the LLaMA models,
our bounds remain valid since they do not require for the models to be trained on the same
data that the empirical risk is evaluated on.
High-quality text generation. One of the major benefits to achieving non-vacuous generaliza-
tion bounds for the original model without aggressive subspace training is to be able to generate
high-quality text with the model that achieves the best bounds. In fact, a significant limitation
of document-level bounds is that the SubLoRA model achieving the best document-level bound
generates un-grammatical, low-quality text as demonstrated by Lotfi et al. [32]and shown in
11
Compression Approach Bits Per Dimension Top-1 Error Top-10 Error Validation Loss
Mistral 377M 2.41 31.60 26.46 0.28
Mistral 212M 2.06 26.25 21.07 0.30
Mistral 94M 1.62 19.40 14.59 0.30
Random Guess 4.86 96.56 65.51 1.46
Table 4:Models pretrained on antibody sequences achieve non-vacuous token-level
generalization bounds. Language models based on the Mistral 7B architecture with scaled-
down sizes pretrained on antibody sequences achieves non-vacuous bounds for next token
prediction on a processed subset of Observed Antibody Sequences (OAS) through post-training
quantization only. The vocabulary size of an antibody LLM is 29.
Training Context Length 01241024
GPT2-S-Quantized 13.911.19.07.9 7.6
Markov Chain 11.310.515.322.4-
Table 5:GPT2 models achieve tighter bounds than Markov chains for large context
lengths. We evaluate the generalization bound BPD achieved when k= 0,1,2,4,1024previous
tokens are made visible to a GPT2 LLM during training when predicting the next token, and
we compare to a our bounds evaluated on a sparse k-th order Markov chain trained on the same
data; with 0th order being just the empirical token probabilities. Our LLM bounds provide a
much stronger statement than what would be explained by low order Markov models.
Table 9. Moreover, document-level bounds for the original model or for models with a sufficiently
high number of trainable parameters to generate high-quality text are vacuous, as shown in
Table 1 and Figure 1 of Lotfi et al. [32]. In contrast, our top-performing model in terms of
token-level BPD bounds on the OpenWebText dataset, which is the quantized GPT2 small
model, generates high-quality text, ensuring a unique combination of practical usefulness and
tight guarantees on the population risk.
6.3 Token-Level Generalization Bounds on Antibody Sequences
Inadditiontonaturallanguages, ourtoken-levelgeneralizationboundsareparticularlydescriptive
of antibody design in biology. An antibody sequence is usually composed of 20 different amino
acid tokens to bind to a target of interest. In therapeutic antibody design, biologists propose
mutations to existing antibody sequences by changing the amino acid tokens at specific positions
in the sequence. Recent works have shown that LLMs pretrained on large antibody datasets
can be used to propose mutations conditioned on starting antibody sequences [ 44,2]. Our
token-level generalization bounds match the settings by bounding the expected next amino acid
token negative log likelihood averaged over training contexts that serve as starting sequences
for iterative mutations. In Table 4, we show that language models based on the Mistral 7B
architecture pretrained on a processed subset of the Observed Antibody Sequences (OAS) from
scratch achieves non-vacuous token-level generalization bounds [ 20,35,2]. Details of these
experiments can be found in Appendix B.9
6.4 Contextualizing GPT2 Bounds Against Markov Chains
The best token-level bound that we achieve for BPD on the OpenWebText dataset is 7.6. But
what does this value exactly mean? One might consider the possibility that our bounds are
describing only the simplest components of fitting the data that exist in the model, such as the
predictions of a 0th or 1st order Markov chain [34].
12
In Table 5 we show that this is not the case, by explicitly training a sparse k-th order Markov
chain on OpenWebText and computing our token-level bounds for the result. Sweeping over
different numbers of n-grams to use for the Markov chains, our bounds for these models cap
out at 10.5BPD and rapidly degrade with higher order as more statistics need to be stored.
We also train and compress versions of GPT2 that are restricted to only seeing ktokens as
context, mirroring the restrictions of the Markov chains. We find that for the simple 0and1st
order Markov chains, our compression via the transformer is slightly worse. However, the LLM
performs much better for higher orders.
6.5 Memorization vs. Reasoning
Large language models are capable of memorizing facts from their pretraining data, but they
also can learn highly structured patterns. As we compress a model more and more, it must
lose its ability to recall memorized facts, but it may still remember patterns, since they are
compressible. In this section, we examine the difference between memorization and reasoning
by measuring the ability of LLMs to compress structured and unstructured sequence data.
25 50 75 100
Quantization Levels0.00.20.40.60.8Accuracy (%)
Structured Sequences
Random Sequences
Figure 4: As language models are com-
pressed, they retain their understanding
of patterns, but they forget highly ran-
dom and unstructured data rapidly. Exper-
imentsperformedonGPT2modelswithdatasets
created as detailed in Section 6.5. Compression
performed via post-training quantization where
lower quantization levels reflect more aggressive
compression.To generate structured sequences, we first use
short binary expression trees to generate nu-
merical sequences of integers [ 17]. These se-
quences are highly compressible as they are
generated using short and deterministic pro-
grams. To generate unstructured sequences,
we collect the set of all unique integers from
the structured sequences and form random
sequences composed of IID samples from the
set of unique integers (see Appendix B.6 for
details). We train standard GPT2 models
from scratch on structured and random se-
quences separately. In Figure 4, we show the
integer prediction training accuracy with vary-
ing degrees of post-training quantization. We
observe that as models are quantized more
aggressively, i.e. the number of quantization
levels decreases, they forget unstructured se-
quences far faster than structured sequences.
These results parallel the findings of Jin et al.
[21]who show that smaller models can retain
in-context learning capabilities but lose their
ability to recall facts.
7 Conclusion
In this work, we introduced novel token-level generalization bounds for LLMs which are able
to accommodate the non-IID nature of the tokens within the training corpus. Combined with
different compression techniques, we achieve non-vacuous generalization bounds for LLMs with
up to 70 billion parameters. The compressed models for which we construct our bounds are
capable of producing high quality text, unlike those in prior work. While there is still have a
gap to close between the typical validation BPD and the constraint of our bounds, our bounds
are predictive of generalization and provide insights into model behaviour.
In future work, one could envision constructing new bounds that make use of the independence
structure between documents and then the non-independent structure within documents to
achieve the best of both. It would also be exciting to further explore the development of these
13
bounds for new downstream predictive tasks, in the vein of the antibody design task we briefly
consider here.
Acknowledgements
We thank Alan Amin for helpful discussions and anonymous reviewers for helpful feedback.
This work is supported by NSF CAREER IIS-2145492, NSF CDS&E-MSS 2134216, NSF
HDR-2118310, BigHat Biosciences, Capital One, and an Amazon Research Award.
References
[1]V. Akinwande, Y. Jiang, D. Sam, and J. Z. Kolter. Understanding prompt engineering may
not require rethinking generalization. arXiv preprint arXiv:2310.03957 , 2023.
[2]Anonymous. Bayesian optimization of antibodies informed by a generative model of evolving
sequences. Manuscript , 2024.
[3]K. Azuma. Weighted sums of certain dependent random variables. Tohoku Mathematical
Journal, Second Series , 19(3):357–367, 1967.
[4]J. Benesty, J. Chen, Y. Huang, and I. Cohen. Pearson correlation coefficient. In Noise
reduction in speech processing , pages 37–40. Springer, 2009.
[5]O.Catoni. Pac-bayesiansupervisedclassification: thethermodynamicsofstatisticallearning.
arXiv preprint arXiv:0712.0248 , 2007.
[6]J. Chee, Y. Cai, V. Kuleshov, and C. D. Sa. Quip: 2-bit quantization of large language
models with guarantees, 2024.
[7]B. Chugg, H. Wang, and A. Ramdas. A unified recipe for deriving (time-uniform) pac-bayes
bounds. Journal of Machine Learning Research , 24(372):1–61, 2023.
[8]T. Computer. Redpajama: an open dataset for training large language models, 2023. URL
https://github .com/togethercomputer/RedPajama-Data .
[9]T. Dao, B. Chen, N. S. Sohoni, A. Desai, M. Poli, J. Grogan, A. Liu, A. Rao, A. Rudra,
and C. Ré. Monarch: Expressive structured matrices for efficient and accurate training. In
International Conference on Machine Learning , pages 4690–4721. PMLR, 2022.
[10]T. Dettmers, M. Lewis, S. Shleifer, and L. Zettlemoyer. 8-bit optimizers via block-wise
quantization, 2022.
[11]T. Dettmers, S. Shmitchell, A. Roberts, K. Lee, T. B. Brown, D. Song, and C. Raffel.
Qlora: Efficient finetuning of quantized llms. arXiv preprint arXiv:2305.14314 , 2023.
[12] P. Deutsch. Rfc1952: Gzip file format specification version 4.3, 1996.
[13]G. K. Dziugaite and D. M. Roy. Computing nonvacuous generalization bounds for deep
(stochastic) neural networks with many more parameters than training data. arXiv preprint
arXiv:1703.11008 , 2017.
[14]G. K. Dziugaite, K. Hsu, W. Gharbieh, G. Arpino, and D. Roy. On the role of data in
pac-bayes bounds. In International Conference on Artificial Intelligence and Statistics ,
pages 604–612. PMLR, 2021.
[15]A. Edalati, M. Tahaei, I. Kobyzev, V. P. Nia, J. J. Clark, and M. Rezagholizadeh. Krona:
Parameter efficient tuning with kronecker adapter. arXiv preprint arXiv:2212.10650 , 2022.
[16]Z. Frantal, A. Gruslys, and D. Kiela. Gptq: Accurate post-training quantization for
generative pre-trained transformers. arXiv preprint arXiv:2210.17323 , 2022.
14
[17]M. Goldblum, M. Finzi, K. Rowan, and A. G. Wilson. The no free lunch theorem,
kolmogorov complexity, and the role of inductive biases in machine learning. arXiv preprint
arXiv:2304.05366 , 2023.
[18]S. Hayou, B. He, and G. K. Dziugaite. Probabilistic fine-tuning of pruning masks and
pac-bayes self-bounded learning. arXiv preprint arXiv:2110.11804 , 2021.
[19]E. J. Hu, Y. Shen, P. Wallis, Z. Allen-Zhu, Y. Li, S. Wang, L. Wang, and W. Chen. Lora:
Low-rank adaptation of large language models. arXiv preprint arXiv:2106.09685 , 2021.
[20]A. Q. Jiang, A. Sablayrolles, A. Mensch, C. Bamford, D. S. Chaplot, D. d. l. Casas,
F. Bressand, G. Lengyel, G. Lample, L. Saulnier, et al. Mistral 7b. arXiv preprint
arXiv:2310.06825 , 2023.
[21]T. Jin, N. Clement, X. Dong, V. Nagarajan, M. Carbin, J. Ragan-Kelley, and G. K.
Dziugaite. The cost of down-scaling language models: Fact recall deteriorates before
in-context learning. arXiv preprint arXiv:2310.04680 , 2023.
[22]J. Kim, J. H. Lee, S. Kim, J. Park, K. M. Yoo, S. J. Kwon, and D. Lee. Memory-efficient
fine-tuning of compressed large language models via sub-4-bit integer quantization. arXiv
preprint arXiv:2305.14152 , 2023.
[23]A. N. Kolmogorov. On tables of random numbers. Sankhy¯ a: The Indian Journal of
Statistics, Series A , pages 369–376, 1963.
[24]V. Kuznetsov and M. Mohri. Generalization bounds for non-stationary mixing processes.
Machine Learning , 106(1):93–117, 2017.
[25]G. G. Langdon. An introduction to arithmetic coding. IBM Journal of Research and
Development , 28(2):135–149, 1984.
[26]R. Li, L. B. Allal, Y. Zi, N. Muennighoff, D. Kocetkov, C. Mou, M. Marone, C. Akiki,
J. Li, J. Chim, Q. Liu, E. Zheltonozhskii, T. Y. Zhuo, T. Wang, O. Dehaene, M. Davaadorj,
J. Lamy-Poirier, J. Monteiro, O. Shliazhko, N. Gontier, N. Meade, A. Zebaze, M.-H. Yee,
L. K. Umapathi, J. Zhu, B. Lipkin, M. Oblokulov, Z. Wang, R. Murthy, J. Stillerman, S. S.
Patel, D. Abulkhanov, M. Zocca, M. Dey, Z. Zhang, N. Fahmy, U. Bhattacharyya, W. Yu,
S. Singh, S. Luccioni, P. Villegas, M. Kunakov, F. Zhdanov, M. Romero, T. Lee, N. Timor,
J.Ding, C.Schlesinger, H.Schoelkopf, J.Ebert, T.Dao, M.Mishra, A.Gu, J.Robinson, C.J.
Anderson, B. Dolan-Gavitt, D. Contractor, S. Reddy, D. Fried, D. Bahdanau, Y. Jernite,
C. M. Ferrandis, S. Hughes, T. Wolf, A. Guha, L. von Werra, and H. de Vries. Starcoder:
may the source be with you!, 2023.
[27]Y. Li, M. E. Ildiz, D. Papailiopoulos, and S. Oymak. Transformers as algorithms: Gen-
eralization and stability in in-context learning. In International Conference on Machine
Learning , pages 19565–19594. PMLR, 2023.
[28]Y. Liu, Q. Xu, W. Xu, and J. Zhu. Llm-qat: Data-free quantization aware training for
large language models. arXiv preprint arXiv:2305.17888 , 2023.
[29]Z. Liu, A. Qiao, W. Neiswanger, H. Wang, B. Tan, T. Tao, J. Li, Y. Wang, S. Sun,
O. Pangarkar, R. Fan, Y. Gu, V. Miller, Y. Zhuang, G. He, H. Li, F. Koto, L. Tang,
N. Ranjan, Z. Shen, X. Ren, R. Iriondo, C. Mu, Z. Hu, M. Schulze, P. Nakov, T. Baldwin,
and E. P. Xing. Llm360: Towards fully transparent open-source llms, 2023.
[30]I. Loshchilov and F. Hutter. Decoupled weight decay regularization. arXiv preprint
arXiv:1711.05101 , 2017.
[31]S. Lotfi, M. Finzi, S. Kapoor, A. Potapczynski, M. Goldblum, and A. G. Wilson. Pac-bayes
compression bounds so tight that they can explain generalization. Advances in Neural
Information Processing Systems , 35:31459–31473, 2022.
15
[32]S. Lotfi, M. Finzi, Y. Kuang, T. G. Rudner, M. Goldblum, and A. G. Wilson. Non-vacuous
generalization bounds for large language models. arXiv preprint arXiv:2312.17173 , 2023.
[33]M. Mohri and A. Rostamizadeh. Stability bounds for non-iid processes. Advances in Neural
Information Processing Systems , 20, 2007.
[34] J. R. Norris. Markov chains . Number 2. Cambridge university press, 1998.
[35]T. H. Olsen, F. Boyles, and C. M. Deane. Observed antibody space: A diverse database of
cleaned, annotated, and translated unpaired and paired antibody sequences. Protein Sci. ,
31(1):141–146, Jan. 2022.
[36]G. Park, J. Kim, J. Kim, E. Choi, S. Kim, S. Kim, M. Lee, H. Shin, and J. Lee. Lut-gemm:
Quantized matrix multiplication based on luts for efficient inference in large-scale generative
language model. arXiv preprint arXiv:2206.09557 , 2022.
[37]G. Penedo, Q. Malartic, D. Hesslow, R. Cojocaru, A. Cappelli, H. Alobeidli, B. Pannier,
E. Almazrouei, and J. Launay. The refinedweb dataset for falcon llm: Outperforming
curated corpora with web data, and web data only, 2023.
[38]M. Pérez-Ortiz, O. Rivasplata, J. Shawe-Taylor, and C. Szepesvári. Tighter risk certificates
for neural networks. Journal of Machine Learning Research , 22(227):1–40, 2021.
[39]A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, I. Sutskever, et al. Language models
are unsupervised multitask learners. OpenAI blog , 1(8):9, 2019.
[40]A. Rakhlin and K. Sridharan. On equivalence of martingale tail bounds and deterministic
regret inequalities. In Conference on Learning Theory , pages 1704–1722. PMLR, 2017.
[41]L. Ralaivola, M. Szafranski, and G. Stempfel. Chromatic pac-bayes bounds for non-iid
data: Applications to ranking and stationary β-mixing processes. The Journal of Machine
Learning Research , 11:1927–1956, 2010.
[42]C. RelaxML. Quip#: Quip with lattice codebooks. https://github .com/Cornell-
RelaxML/quip-sharp , 2024.
[43]S. Shalev-Shwartz and S. Ben-David. Understanding machine learning: From theory to
algorithms . Cambridge university press, 2014.
[44]R. W. Shuai, J. A. Ruffolo, and J. J. Gray. Generative language modeling for antibody
design.bioRxiv, pages 2021–12, 2021.
[45]R. J. Solomonoff. A formal theory of inductive inference. part i. Information and control , 7
(1):1–22, 1964.
[46]J. Su, M. Ahmed, Y. Lu, S. Pan, W. Bo, and Y. Liu. Roformer: Enhanced transformer
with rotary position embedding. Neurocomputing , 568:127063, 2024.
[47]H.Touvron, L.Martin, K.Stone, P.Albert, A.Almahairi, Y.Babaei, N.Bashlykov, S.Batra,
P. Bhargava, S. Bhosale, D. Bikel, L. Blecher, C. C. Ferrer, M. Chen, G. Cucurull, D. Esiobu,
J. Fernandes, J. Fu, W. Fu, B. Fuller, C. Gao, V. Goswami, N. Goyal, A. Hartshorn,
S. Hosseini, R. Hou, H. Inan, M. Kardas, V. Kerkez, M. Khabsa, I. Kloumann, A. Korenev,
P. S. Koura, M.-A. Lachaux, T. Lavril, J. Lee, D. Liskovich, Y. Lu, Y. Mao, X. Martinet,
T. Mihaylov, P. Mishra, I. Molybog, Y. Nie, A. Poulton, J. Reizenstein, R. Rungta,
K. Saladi, A. Schelten, R. Silva, E. M. Smith, R. Subramanian, X. E. Tan, B. Tang,
R.Taylor, A.Williams, J.X.Kuan, P.Xu, Z.Yan, I.Zarov, Y.Zhang, A.Fan, M.Kambadur,
S. Narang, A. Rodriguez, R. Stojnic, S. Edunov, and T. Scialom. Llama 2: Open foundation
and fine-tuned chat models, 2023.
[48]A. Tseng, J. Chee, Q. Sun, V. Kuleshov, and C. De Sa. Quip#: Even better llm quantization
with hadamard incoherence and lattice codebooks. arXiv preprint arXiv:2402.04396 , 2024.
16
[49]K. Wang, X. Hu, and J. Zhang. Fast clonal family inference from large-scale B cell repertoire
sequencing data. Cell Rep Methods , 3(10):100601, Oct. 2023.
[50]Q. Xu, W. Xu, and J. Zhu. Tensorgpt: Efficient compression of the embedding layer in
llms based on the tensor-train decomposition. arXiv preprint arXiv:2307.00526 , 2023.
[51]C. Zhang, S. Bengio, M. Hardt, B. Recht, and O. Vinyals. Understanding deep learning
(still) requires rethinking generalization. Communications of the ACM , 64(3):107–115, 2021.
[52]R.-R. Zhang and M.-R. Amini. Generalization bounds for learning under graph-dependence:
A survey. arXiv preprint arXiv:2203.13534 , 2022.
[53]W. Zhou, V. Veitch, M. Austern, R. P. Adams, and P. Orbanz. Non-vacuous generalization
bounds at the imagenet scale: a pac-bayesian compression approach. In International
Conference on Learning Representations , 2019.
17
A Token-Level Martingale Bound
A.1 Proof of the Main Theorem
Theorem 2. With probability at least 1−δover the randomness in a sampled sequence
x1, x2, . . . , x m, if the negative log likelihood of a model h∈ Hcan be bounded −log2ph(·|x<i)∈
[a, a+ ∆ i]for some ∆i(possibly a function of h), then the negative log likelihood of the data of
a given hypothesis hsatisfies
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m,(4)
where ˆ∆=q
1
mPm
i=1∆2
i, the expectation is taken over Xi∼p(Xi|x<i)from the data generating
process, and P(h)is any normalized prior over a discrete hypothesis space Hthat does not
depend on {xi}m
i=1.
Proof sketch. The proof of Theorem 1 is an application of Azuma’s inequality [ 3] and can be
broken down into the following steps:
•Construct a martingale difference sequence from the difference between the NLL on token
xi, and its expectation given the tokens x<i. From the boundedness of NLL one can show
that the differences are bounded.
•Apply Azuma’s inequality for each hypothesis, choosing failure probability proportional to
the chosen prior P(h).
•Perform a union bound of the failure probabilities over all hypotheses. If all of the
hypotheses satisfy the bound simultaneously, then so does the data dependent hypothesis
h∗.
Proof.Given the autoregressive predictions R(h, xi, x<i) :=−log2ph(xi|x<i)where x<i:=
{x1, x2, . . . , x i−1}. Let{xi}denote the actual values of the sequence that were found empirically,
and{Xi}be the random variables for these quantities.
The collection of random variables (indexed by i)Zi=E[R(h, X i, x<i)|x<i]−R(h, X i, x<i)
form a Martingale difference sequence with respect to x<i. Note here that the expectation is
over the distribution Xi∼p(Xi|x<i). From the construction, E[Zi|x<i] = 0and the sequence
is bounded: Ai=E[R(h, X i, x<i)|x<i]−a≤Zi≤∆i+E[R(h, X i, x<i)|x<i]−a=Bi, with
Bi−Ai= ∆ i.
∆imay depend on x≥ibut only through it’s dependence on the hypothesis h({x}m
i=1). For a
fixed hwe may conclude thatPm
i=1Ziis bounded difference Martingale sequence (with respect
to{x<i}m
i=1), and we can apply Azuma’s inequality [3] to derive that for any t >0:
P mX
i=1Zi> mt
≤exp
−2m2t2/mX
i=1∆2
i
P 1
mmX
i=1Zi> t
≤exp
−2mt2/ˆ∆2
.
Judiciously choosing
t(h) =ˆ∆r
log 1/P(h) + log 1 /δ
2m,
18
we have that P 1
mPm
i=1Zi> t(h)
=P(h)δ.
Applying a union over the eventsS
h∈H1
mPm
i=1Zi(h)> t(h)
, we have
P 1
mmX
i=1Zi> t(h)
≤X
hP(h)δ=δ,
therefore P 1
mPm
i=1Zi≤t(h)
>1−δ. Unpacking the definition of Zi, we have that with
probability at least 1−δ
1
mmX
i=1E[R(h, X i, x<i)|x<i]≤1
mmX
i=1R(h, xi, x<i) +ˆ∆r
log 1/P(h) + log 1 /δ
2m.
Expressed in terms of the log likelihood, we can write this as:
1
mmX
i=1E[−log2ph(Xi|x<i)|x<i]≤ −1
mlog2ph(x≤m) +ˆ∆r
log 1/P(h) + log 1 /δ
2m
A.2 Empirical Risk Subsampling
We evaluate our bounds for the OpenWebtext and Amber datasets which contain 9 billion and
1.2 trillion tokens, respectively. Computing the exact empirical risk for these datasets would be
prohibitively expensive. Therefore, we use subsampling for the evaluation of the empirical risk
to accelerate bound computation. In Equation (2), we use the following inequality which holds
with probability at least 1−δ2:
−1
mlog2ph(x≤m)≤ −1
nnX
j=1log2ph(xσ(j)|x<σ(j)) +ˆ∆r
log 1/δ2
2n(5)
for a subsample of size nwhere σis a random permutation. We choose δ1in Equation (2) with
respect to a new overall failure probability δto be δ1=δn/(n+m)and choose δ2=δm/(n+m)
so that the overall failure probability is still δ. The proof is simple and similar to that provided
in Lotfi et al. [32].
B Experimental Details
B.1 Pretraining with Nonlinear Parametrizations
To achieve the necessary model compression level for computing non-vacuous bounds, we pretrain
GPT2 Small with 124 million parameters on the OpenWebText1dataset based on the nanoGPT
implementation2[39]. We parametrize the linear layers of CausalSelfAttention ,MLP, and the
LinearHead of the GPT2 models with our nonlinear compression techniques (LoRA, Kronecker,
Monarch), where we use a bias vector except for the LinearHead layer. For LoRA and Kronecker,
we use weight tying between the token embedding and the final LinearHead layer parameterized
by nonlinear compression techniques. We also train the layer norm parameters in addition to
all of the nonlinear projection parameters applied to the linear layers. For Monarch, we only
train the linear layers parameterized by Monarch matrices. We also combine the three nonlinear
parametrizations with linear subspace projection, where all the trainable parameters θare
projected into a subspace of parameters wusing a projection matrix P, such that θ=θ0+Pw.
We vary the dimension of was a hyperparameter in the bound evaluation.
1http://Skylion007 .github .io/OpenWebTextCorpus
2https://github .com/karpathy/nanoGPT
19
For all the pretraining experiments, we use a batch size of 8, a sequence length of 1024, and
a standard AdamW optimizer [ 30] with a learning rate of 0.0002. We perform a learning
rate warm-up for 500iterations, and we apply rotary embedding [ 46] to all three nonlinear
parametrizations.
B.1.1 Hyperparameter Sweeps for LoRA
LoRA.We sweep over LoRA rank values r∈ {1,4,16,32,64,128,256}. We choose a learning
rate of 0.0002with a LoRA dropout value of 0.1and LoRA alpha value of 32.
SubLoRA. We report the rank rand the corresponding subspace dimension values that we
sweep over for SubLoRA in Table 6.
Rank rSubspace Dimension d
1 25000
4 50000
8 50000
16 50000
32 10000, 750000
64 25000, 2000000
128 7000000, 15000000
Table 6: Hyperparameter sweep for SubLoRA. For all the SubLoRA pretraining experiments,
we use a learning rate of 0.0002, a LoRA dropout value of 0.1, and a LoRA alpha value of 32.
B.1.2 Hyperparameter Sweeps for Kronecker
For the Kronecker factorization W=A⊗B, we choose the matrices AandBsuch that
A∈Ra1×b1, B∈Ra2×b2where a1a2=aandb1b2=b. We sweep over all possible combinations
of{a1, a2}and{b1, b2}by performing prime factorizations with multiplicity on the numbers
a, band enumerating all possible combinations. All of our Kronecker pretraining experiments
use a learning rate of 0.0002.
B.1.3 Hyperparameter Sweeps for Monarch
For the Monarch parametrization, we relax the restriction for the number of blocks to be strictly√aand instead by a number divisible by ato sweep over different numbers of blocks. We
also perform experiments for Monarch where we are using absolute position encodings and
experiments where we are only applying the Monarch factorization to the attention layers and
the linear classification heads.
B.2 Quantization
Quantization Following Lotfi et al. [31], we apply post-training quantization of the trainable
weights that correspond to the subspace parameters and/or the LoRA, Kronecker, Monarch
parameters along with layer norm weights depending on the compression setup.
Experiments on QuIP-quantized Models. We compute token-level bounds on pretrained
LLaMA1 and LLaMA2 models [ 47] quantized with QuIP with publicly-available checkpoints
[42]. Although we do not know what data was used to pretrain these models, we can evaluate
the generalization bound on the Amber dataset and consider other tokens used in training as a
data-dependent prior.
20
B.3 Bounds Evaluation
In the sequence of text, we use end of text tokens (EOT) which separate the documents. In
this way, we can consider concatenating many documents together to form one long sequence.
As a result of the EOT tokens and the structure of the text, the distribution p(xi|x<i)can
be simplified into p(xi|xk, xk+1, . . . x i−1)where kis the index of the most recent EOT token
because the documents are sampled independently. In the evaluation of the LLM we likewise
have no dependence on tokens outside the given document in question.
To compute token-level bounds, we evaluate all of our generalization bounds with failure
probability δ= 0.05and subsample size of n= 10,0000tokens from the OpenWebText training
dataset of size m= 9billion tokens or the Amber dataset of size m= 1.2trillion tokens.
B.4 Correlation with Downstream Performance
We retrieve the downstream task performance of difference GPT2 variants ranging in scale
from 117M to 1.5B averaged over the downstream datasets as shown in Table 7. To obtain an
approximation of the conditional BPD expectation that we bound in Equation (2), we resample
xifrom a LLaMA2-7B given fixed training contexts x<ifrom the Amber dataset. We use a
sample size equal to 10,000samples.
Model
SizeLAMBADA
(PPL)LAMBADA
(ACC)CBT-CN
(ACC)CBT-NE
(ACC)WikiText2
(PPL)PTB
(PPL)WikiText103
(PPL)1BW
(PPL)
117M 35.13 45.99 87.65 83.4 29.41 65.85 37.50 75.20
345M 15.60 55.48 92.35 87.1 22.76 47.33 26.37 55.72
762M 10.87 60.12 93.45 88.0 19.93 40.31 22.05 44.575
1542M 8.63 63.24 93.30 89.05 18.34 35.76 17.48 42.16
Table 7: Zero-shot downstream task performance for GPT2 models with different model sizes as
reported in Radford et al. [39].
B.5 Markov Chain Comparison
For training the Markov chains, we reuse the Byte Pair Encoding (BPE) tokenization to separate
out the effect of the tokenizer. We apply prediction smoothing at level α= 0.1to the Markov
models to give them nonzero probability to ngrams that have not been seen in the training data
and limit the worst case NLL of a single token.
For constructing generalization bounds with the Markov chain, we upper bound the complexity
term log1/P(h)similarly to the large language models by performing quantization and com-
pression. We store and update the Markov chains sparsely, which becomes necessary when
considering the high order variants. In storing the model, we use a dictionary mapping each
prefix concatenated with the following token to a count. The counts can then be converted into
probabilities by normalizing by the count containing just the prefix. We quantize the counts
and store them in 16bits, and we store the keys using a basic encoding. For training, we train
on a subsample of 106tokens from the training corpus, sufficient for the performance of the
Markov chains to converge.
B.6 Memorization Experiment
Following Goldblum et al. [17], we select a complexity value of 4, which reflects the difficulty of
the task, and a sequence length of 30and generate 984sequences as the training dataset for
structured sequences. To build our baseline random sequences, we collect all unique integers in
the generated sequences into a set. We then sample integers IID from a uniform distribution
21
over the set of unique integers from the structured sequences to build the baseline dataset.
Our vocabulary size is 12as we only have integers, the beginning of text token, and an
additional delimiter token. The delimiter tokens are placed between distinct numbers during
our tokenization process. We use a GPT-2 Small model with 124M parameters and train it on
the structured and random sequences separately with a learning rate of 0.0001for1000epochs.
Our quantization procedure is the same as described in Appendix B.2. We show the results for
this experiment in Figure 4.
B.7 Amber Dataset
We use a subset of the pretraining dataset for Amber 7B LLM [ 29] for our bound evaluations.
This dataset contains RedPajama V1 [ 8] (arxiv, C4, GitHub, StackExchange, Wikipedia),
StarCoder [ 26] (The Stack), RefinedWeb [ 37] (CommonCrawl) with around 1.2 trillion tokens.
We tokenize the entire dataset using a LLaMA tokenizer and then sample tokens from a uniform
distribution over the tokenized dataset.
B.8 Compute Budget
For all our pretraining experiments with the three proposed compression techniques, we run
each experiment for 5days on 4 GPUs in parallel that are of type A100s or RTX8000. For
the bound computation experiments, we use a single GPU of any type and a subsample size of
10,000samples. The running time varies between 1to8hours depending on the model and the
dataset. All other experiments are performed on a single GPU of any type.
B.9 Bounds on Antibody Sequences
B.9.1 Datasets
An antibody consists of both the light chain and the heavy chain amino acid sequences. Among
these sequences, there are collections of sequences called the clonal family that our immune
systems developed to bind to targets. For our experiments, we select all human heavy chain
amino acid sequences from the Observed Antibody Space (OAS) and keep all the clonal families
with at least 25 sequences using the FastBCR filtering technique following [ 35,49,2]. The
processed dataset contains around 908 thousand heavy chain clonal families. A single example
in our dataset is thus a clonal family looking like [sequence 1 ,sequence 2 , ...,sequence N ]where
N≥25.
There are in total 29 different tokens with 20 of them corresponding to 20 different amino acids.
Let[ClSep ]be a separator token between sequences in a clonal family. We process our input
example by forming the string “sequence 1 [ClSep ]sequence 2 [ClSep ]...[ClSep ]sequence N ”
following [ 2]. This input example is tokenized and given to a language model using the next
token prediction training objective.
B.9.2 Language Models
We use language | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | model architectures that are based on the Mistral 7B architecture [ 20]. We scale
down the Mistral architecture using 24 layers with a varying hidden state size of (1024 ,768,512),
resulting in our Mistral 377M, Mistral 212M, and Mistral 94M models, respectively following
[2]. With a vocabulary size of 29 and a maximum context length of 2048, we train each of our
models using 4 NVIDIA A100s for 48 hours and perform post-training quantization following
Lotfi et al. [31].
22
ModelBits per
DimensionTop-1
Error (%)Top-10
Error (%)Top-100
Error (%)
2 bits
LLaMA1-7B 4.29 48.08 22.82 12.83
LLaMA1-13B 4.60 48.87 24.23 14.59
LLaMA1-30B 5.37 52.91 28.06 19.14
LLaMA1-65B 6.10 56.63 32.29 24.14
LLaMA2-7B 4.28 47.55 22 .48 12 .56
LLaMA2-Chat-7B 4.54 49.10 24.18 13.50
LLaMA2-13B 4.52 47.85 23.54 14.44
LLaMA2-Chat-13B 4.77 49.82 24.95 15.10
LLaMA2-70B 6.14 56.24 32.61 24.32
LLaMA2-Chat-70B 6.40 58.26 34.16 25.04
3 bits
LLaMA1-7B 4.37 47.42 22.87 13.63
LLaMA1-13B 4.80 48.97 25.23 16.14
LLaMA1-30B 5.70 53.54 29.91 21.63
LLaMA1-65B 6.73 59.56 36.14 28.08
LLaMA2-7B 4.35 47 .1522.75 13.62
LLaMA2-Chat-7B 4.65 48.84 24.23 14.24
LLaMA2-13B 4.76 48.45 24.67 15.95
LLaMA2-Chat-13B 5.06 50.90 26.26 16.66
LLaMA2-70B 6.77 59.35 36.27 28.56
LLaMA2-Chat-70B 7.08 61.66 38.00 29.30
4 bits
LLaMA1-7B 4.50 47.52 23.53 14.52
LLaMA1-13B 5.02 49.96 26.46 17.47
LLaMA1-30B 6.05 55.55 32.09 23.93
LLaMA1-65B 7.27 62.56 39.38 31.54
LLaMA2-7B 4.49 47.64 23.64 14.53
LLaMA2-Chat-7B 4.83 49.49 25.15 15.12
LLaMA2-13B 4.96 49.46 25.67 17.21
LLaMA2-Chat-13B 5.27 51.61 27.23 18.12
LLaMA2-70B 7.33 62.53 39.89 32.11
LLaMA2-Chat-70B 7.68 65.32 41.59 32.87
Random Guess 14.97 99.99 99.96 99.68
Table 8:Non-vacuous token-level generalization bounds for open-source pretrained
LLM checkpoints on the Amber dataset. All of these models were quantized post-training
using QuIP# to different numbers of bits as shown above. All the bounds are non-vacuous
compared to random guess performance.
C Additional Results
C.1 LLaMA Bounds on Amber
In Table 8, we have the complete bounds computation results for LLaMA1, LLaMA2, LLaMA2
Chat with 2 bits, 3 bits, and 4 bits quantization. The best bound is achieved by a LLaMA2
model with 2 bits quantization.
C.2 Generated Text
In Table 9, we show the generated text by the model achieving the best bounds: the quantized
GPT2 model that achieves the best token-level bounds on the OpenWebText dataset in our
23
Generated Text
GPT2 (124M)
Quantized
(BPD Bound: 7.61)The study, published in Proceedings of the National Academy of
Sciences, examined the relationships between brain activity, gene
expression and inflammation in diseases including Alzheimer’s dis-
ease, dementia, Parkinson’s disease, glioblastoma and Alzheimer’s
disease. "Our study demonstrates that omega-3 fatty acids play a
role in the link between inflammation and brain function," said
lead author Dr Richard Collins, PhD, of Duke University’s Duke
Center for Bioethomics and Bioengineering. After controlling for.
GPT2 (124M)
SubLoRA
[32]th he the startedt at its„ the a more be power and- by. S and, of
of -’s on. The UK I The, are the on the the under, but the then
the day,. The. The. It for the! a,. M an they first the the speak
have times. cover that ( illegal In the day where I The who when
and $ In We¨ :[{¨ : As she I WeP spirituality. The all And one which
a more says thought the other (ed 15: And P It as/ T - 2 But We
The The theah It who the full of that to was ’The they (It As We
A and each (. The It - We The M I“
Table9:Thebestnon-vacuoustoken-levelboundscorrespondtomodelsthatgenerate
high quality text. Examples of generated text from the GPT2 small quantized model that
achieves the best token-level bounds compared to the SubLoRA-pretrained GPT2 small model
in Lotfi et al. [32]. In contrast to the text generated by the best performing model in terms of
BPD bounds by Lotfi et al. [32], our quantized GPT2 small generates significantly higher-quality
text while simultaneously achieving the best BPD and Top- 1/10/100error bounds.
work, and the GPT2 model trained with SubLoRA that achieves the best document-level
bounds in Lotfi et al. [32]. The text generated by the model achieving the best generalization
bounds in our work is visibly more coherent and grammatically correct. By switching from
document-level to token-level bounds, obtaining non-vacuous bounds requires less restrictive
compression techniques and therefore can be achieved for highly performant models that generate
high-quality text and can be deployed in practice.
24 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18178v1 | http://arxiv.org/pdf/2407.18178v1 | PianoMime: Learning a Generalist, Dexterous Piano Player from Internet Demonstrations | Cheng Qian, Julen Urain, Kevin Zakka, Jan Peters | 2024-07-25 | Abstract: In this work, we introduce PianoMime, a framework for training a
piano-playing agent using internet demonstrations. The internet is a promising
source of large-scale demonstrations for training our robot agents. In particular,
for the case of piano-playing, Youtube is full of videos of professional pianists
playing a wide myriad of songs. In our work, we leverage these demonstrations to
learn a generalist piano-playing agent capable of playing any arbitrary song. Our
framework is divided into three parts: a data preparation phase to extract the in-
formative features from the Youtube videos, a policy learning phase to train song-
specific expert policies from the demonstrations and a policy distillation phase to
distil the policies into a single generalist agent. We explore different policy de-
signs to represent the agent and evaluate the influence of the amount of training
data on the generalization capability of the agent to novel songs not available in
the dataset. We show that we are able to learn a policy with up to 56% F1 score
on unseen songs. Project website: https://pianomime.github.io/
Keywords: Imitation Learning, Reinforcement Learning, Dexterous Manipula-
tion, Learning from Observations
1 | Introduction
The Internet is a promising source of large-scale data for training generalist robot agents. If properly
exploited, it is full of demonstrations (video, text, audio) of humans solving an infinite amount of
tasks [1, 2, 3] that could inform our robot agents on how to behave. However, learning from these
databases is challenging for several reasons. First, unlike teleoperation demonstrations, video data
does not specify the actions applied by the robot, usually requiring the use of reinforcement learning
to induce the robot actions [4, 2, 5]. Second, videos typically show a human performing the task,
while the learned policy is deployed on a robot. This often requires to re-target the human motion
to the robot body [5, 6, 7]. Finally, as pointed in [2], if we aim to learn a generalist agent, we must
select a task for which large-scale databases are available and that allows an unlimited variety of
open-ended goals.
From opening doors [6] to rope manipulation [8] or pick and place tasks [9, 10], previous works have
successfully taught robot manipulation skills through observations. However, these approaches have
been limited to low dexterity in the robots or to a small variety of goals.
In this work, we focus on the task of learning a generalist piano player from Internet demon-
strations . Piano-playing is a highly dexterous open-ended task [11]. Given two multi-fingered robot
hands and a desired song, the goal of a piano-playing agent is to press the correct keys and only the
correct keys at the proper timing. Moreover, the task can be conditioned on arbitrary songs, allowing
for a large, and high-dimensional goal conditioning.
Additionally, the Internet is full of videos of professional piano players performing a wide myriad of
songs. Interestingly, these piano players often record themselves from a top-view allowing an easy
observation of the demonstrations. Additionally, they usually share the MIDI files of the song they
play, facilitating the extraction of relevant information.arXiv:2407.18178v1 [cs.CV] 25 Jul 2024
Figure 1: The goal of this work is to train a generalist piano-playing agent (PianoMime) from
Youtube videos. We collect a set of videos and accompanying MIDI files and train a single agent to
play any song, combining reinforcement learning and behavioral cloning.
To learn a generalist piano-playing agent from internet data, we introduce PianoMime , a framework
to train a single policy capable of playing any song (See Figure 1). In its essence, the PianoMime
agent is a goal-conditioned policy that generates configuration space actions given the desired song
to be played. At each timestep, the agent receives as goal input a trajectory of the keys to be pressed.
Then, the policy generates a trajectory of actions and executes them in chunk.
To learn the agent, we combine both reinforcement learning with imitation learning. We train
individual song-specific expert policies by using reinforcement learning in conjunction with Youtube
demonstrations and we distill all the expert policies into a single generalist behavioral cloning policy.
To represent the agent, we perform ablations of different architectural design strategies to model
the behavioral cloning policy. We investigate the benefit of incorporating representation learning to
enhance the geometric information of the goal input. Additionally, we explore the effectiveness of a
hierarchical policy that combines a high-level policy generating fingertip trajectories with a learned
cross-domain inverse dynamics model generating joint-space actions. We show that the learned
agent is able to play arbitrary songs not included in the training dataset with around 56% F1-score.
In summary, the main contribution of this work is a framework for training a generalist piano-
playing agent using Internet demonstration data. To achieve this goal, we:
• Introduce a method to learn policies from the internet demonstrations by decoupling the
human motion information from the task-related information.
• Present a reinforcement learning approach that combines residual policy learning strate-
gies [12, 13] with style reward-based strategies [5].
• Explore different policy architecture designs, introducing novel strategies to learn geomet-
rically consistent latent features and conducting ablations on different architectural designs.
Finally, we are releasing the dataset and the trained models as a benchmark for testing internet-data-
driven dexterous manipulation.
2 | Section not found | Related Work
Robotic Piano Playing Several studies have investigated the development of robots capable of play-
ing the piano. In [14], multiple-targets Inverse Kinematics (IK) and offline trajectory planning are
utilized to position the fingers above the intended keys. In [15], a Reinforcement Learning (RL)
agent is trained to control a single Allegro hand to play the piano using tactile sensor feedback.
However, the piano pieces used in these studies are relatively simple. Subsequently, in [11], an RL
agent is trained to control two Shadow Hands to play complex piano pieces by designing a reward
function comprising a fingering reward, a task reward, and an energy reward. In contrast with pre-
vious approaches, our approach exploits Youtube piano-playing videos, enabling faster training and
more accurate and human-like robot behavior.
Motion Retargeting and Reinforcement Learning Our work shares similarities with motion re-
targeting [16], specifically with those works that combine motion retargeting with RL to learn con-
trol policies [17, 18, 5, 19, 6]. Given a mocap demonstration, it has been common to exploit the
2
demonstration rather as a reward function [5, 19] or as a nominal behavior for residual policy learn-
ing [18, 6]. In our work, we not only extract the mocap information, but also task-related information
(piano states) allowing the agent to balance between mimicking the demonstrations and solving the
task.
3 Method
The PianoMime framework is composed of three phases: data preparation, policy learning, and pol-
icy distillation.
In the data preparation phase , given the raw video demonstration, we extract the informative sig-
nals needed to train the policies. Specifically, we extract fingertip trajectories and a MIDI file that
informs the piano state at every time instant.
In the policy learning phase , we train song-specific policies via RL. This step is essential for gener-
ating the robot actions that are missing in the demonstrations. The policy is trained with two reward
functions: a style reward and a task reward. The style reward aims to match the robot’s finger move-
ments with those of the human in the demonstrations to preserve the human style, while the task
reward encourages the robot to press the correct keys at the proper timing.
In the policy distillation phase , we train a single behavioral cloning policy to mimic all the song-
specific policies. The goal of this phase is to train a single generalist policy capable of playing any
song. We explore different policy designs and the representation learning of goals to improve the
generalization capability of the policy.
3.1 Data preparation: From raw data to human and piano state trajectories
We generate the training dataset by web scraping. We download YouTube videos of professional
piano artists playing various songs. We particularly choose YouTube channels that also upload MIDI
files of the played songs. The MIDI files represent trajectories of the piano state (pressed/unpressed
keys) throughout the song. We use the video to extract the motion of human pianists and the MIDI
file to inform about the goal state of piano during the execution of the song.
We select the fingertip position as the essential signal to mimic with the robot hand. While several
dexterous tasks might require the use of the palm (e.g. grasping a bottle), we consider mimicking the
fingertip motion to be sufficient for the task of piano playing. This will also reduce the constraints
applied to the robot, allowing it to adapt its embodiment more freely.
To extract the fingertip motion from videos, we use MediaPipe [20], an open-source framework
for perception. Given a frame from the demonstration videos, MediaPipe outputs the skeleton of
the hand. We find that the classical top-view recording in piano-playing YouTube videos is highly
beneficial for obtaining an accurate estimate of the fingertip positions.
Notice that given the videos are RGB, we lack depth signal. Therefore, we predict the 3D fingertip
positions based on the piano state. The detailed procedure is explained in Appendix A.
3.2 Policy learning: generating robot actions from observations
Through the data preparation phase, we extract two trajectories: a human fingertip trajectory τx
and a piano state trajectory τˇ “(. The human fingertip trajectory τx:px1, . . . ,xTqis aT-step
trajectory of two hands’ 3D fingertip positions xPR3ˆ10(10 fingers). The piano state trajectory
τˇ “(:p ˇ “(1, . . . , ˇ “(Tqis aT-step trajectory of piano states ˇ “(PB88, represented with an 88-dimensional
binary variable representing which keys should be pressed.
Given the R OBOPIANIST [11] environment, our goal is to learn a goal-conditioned policy πθthat
plays the song defined by τˇ “(while matching the fingertip motion given by τx. Notice that satisfying
both | Section not found | Section not found | Section not found | objectives jointly might be impossible. Tracking perfectly the fingertip trajectory τxmight not
necessarily lead to playing the song correctly. Although both trajectories are collected from the same
source, errors in hand tracking and embodiment mismatches might lead to deviations, resulting in
poor song performance. Thus, we propose using τxas a style guiding behavior.
3
Observation
Encoder
Fingertip
PolicyInverse
Model
FK
Figure 2: Proposed distillation policy architecture. Given a L steps window of a target song τt
ˇ “(:
p ˇ “(t:t`Lqat time t, a latent representation τt
zis computed given a pre-trained observation encoder.
Then, the policy is decoupled between a high-level fingertip predictor that generates a trajectory of
fingertip positions τt
xand a low-level inverse dynamics model that generates a trajectory of target
joint position τt
q.
Similarly to [11], we formulate the piano playing as an Markov Decision Process (MDP) with the
horizon of the episode H, being the duration of the song to be played. The state observation is
defined by the robot’s proprioception sand the goal state gt. The goal state gtat time tinforms the
desired piano key configurations ˇ “(in the future gt“p ˇ “(t`1, . . . , ˇ “(t`Lq, with Lbeing the lookahead
horizon. As claimed in [11], to successfully learn how to play, the agent needs to be aware of several
steps into the future to plan its actions. The action ais defined as the desired configuration for both
hands qPR23ˆ2`1, each with 23 joint angles and one dimension for the sustain pedal.
We propose solving the reinforcement learning problem by combining residual policy learning [12,
13, 6] and style mimicking rewards [5, 19].
Residual policy architecture. Given the fingertip trajectory τx, we solve an IK [21] problem to
obtain a trajectory of desired joint angles τik
q:pqik
0, . . . ,qik
Tqfor the robot hands. Then, we represent
the policy πθpa|s,gtq“πr
θpa|s,gtq`qik
t`1as a combination of a nominal behavior (given by the IK
solution) and a residual policy πr
θ. Given the goal state at time t, the nominal behavior is defined as
the next desired joint angle qik
t`1. We then only learn the residual term around the nominal behavior.
In practice, we initialize the robot at qik
0and roll both the goal state and the nominal behavior with a
sliding window along τˇ “(andτik
qrespectively.
Style-mimicking reward. We also integrate a style-mimicking reward to preserve the human style
in the trained robot actions. The reward function r“rˇ “(`rxis composed of a task reward rˇ “(and
a style-mimicking reward rx. While the task reward rˇ “(encourages the agent to press the correct
keys, the style reward rxencourages the agent to move its fingertips similar to the demonstration
τx. We provide further details in Appendix C.
3.3 Policy distillation: learning a generalist piano-playing agent
Through the policy learning phase, we train song-specific expert policies from which we roll out
state and action trajectories τs:ps0, . . . ,sTqandτq:pq0, . . . ,qTq. Then, we generate a dataset D:
pτi
s, τi
q, τi
x, τi
ˇ “(qN
i“1withNbeing the number of learned songs. Given the dataset D, we apply Be-
havioral Cloning (BC) to learn a single generalist piano-playing agent πθpqt:t`L,xt:t`L|st, ˇ “(t:t`Lq
that outputs configuration-space actions qt:t`Land fingertip motion xt:t`Lconditioned on the cur-
rent state stand the future desired piano state ˇ “(t:t`L.
We explore different strategies to represent and learn the behavioral cloning policy and improve
its generalization capabilities. In particular, we explore ( 1) representation learning approaches to
induce spatially informative features, ( 2) a hierarchical policy structure for sample-efficient training,
and ( 3) expressive generative models [22, 23, 24] to capture the multimodality of the data. Also,
inspired by current behavioral cloning approaches [22, 25], we train policies that output sequences
of actions rather than single-step actions and execute them in chunks.
Representation Learning. We pre-train an observation encoder over the piano state ˇ “(to learn
spatially consistent latent features. We hypothesize that two piano states that are spatially close
4
should lead to latent features that are close. Using these latent features as goal should induce better
generalization. To obtain the observation encoder, we train an autoencoder with a reconstruction loss
over a Signed Distance Field (SDF) defined on the piano state. Specifically, the encoder compresses
the binary vector of the goal into a latent space, while the decoder predicts the SDF function value
of a randomly sampled query point (the distance between the query point and the closest ”on” piano
key). We provide further details in Appendix E.
Hierarchical Policy. We represent the piano-playing agent with a hierarchical policy. The high-
level policy receives a sequence of desired future piano states ˇ “(and outputs a trajectory of human
fingertip positions x. Then, a low-level policy takes the fingertip and piano state trajectories as
input and outputs a trajectory of desired joint angles q. On one hand, while fingertip trajectory
data is easily available from the Internet, obtaining low-level joint trajectories requires solving a
computationally expensive RL problem. On the other hand, while the high-level mapping ( ˇ “(ÞÑx)
is complex, which involves fingerings, the low-level mapping ( xÞÑq) is relatively simpler, which
addresses a cross-embodiment inverse dynamics problem. This decoupling allows us to train the
more complex high-level mapping on large cheap datasets and the simpler low-level mapping on
smaller expensive ones. We visualize the policy in Figure 2.
Expressive Generative Models. Considering that the human demonstration data of piano playing
is highly multi-modal, we explore using expressive generative models to better represent this multi-
modality. We compare the performance of different deep generative models based policies, e.g.,
Diffusion Policies [22] and Behavioral Transformer [23], as well as a deterministic policy.
4 Experimental Results
We split the experimental evaluation into three parts. In the first part, we explore the performance of
our proposed framework in learning song-specific policies via RL. In the second part, we perform
ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three | Section not found | Section not found | Section not found | methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also | Section not found | Section not found | Section not found | Results
We split the experimental evaluation into three parts. In the first part, we explore the performance of
our proposed framework in learning song-specific policies via RL. In the second part, we perform
ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three
methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also results
in a larger discrepancy between the fingertip trajectory of the robot and the human. Thus, the weight
of the style-mimicking reward can be viewed as a parameter that controls the human likeness of the
learned robot actions.
Qualitative comparison. We present a qualitative comparison of the human likeness of the robot
motion in Figure 4 and the attached videos. We inspect the hand poses for certain frames and ob-
serve that the IK nominal behavior leads the robot to place the fingers in positions similar to those in
Youtube videos. The RL policy then slightly adapts the fingertip positions to press the keys correctly.
4.2 Evaluation of model design strategies for policy distillation
This section focuses on the evaluation of policy distillation for playing different songs. We evaluate
the influence of different policy design strategies on the agent’s performance. We aim to assess ( 1)
the impact of integrating a pre-trained observation encoder to induce spatially consistent features,
(2) the impact of a hierarchical design of the policy, and ( 3) the performance of different generative
models on piano-playing data.
6
Multi-RL BC-MSE Two-Stage Diff -res w/o SDF One-Stage BeTTrainP 0.85 0.56 0.87 0.89 0.86 0.53 0.63
R 0.20 0.29 0.78 0.80 0.76 0.34 0.42
F1 0.12 0.30 0.81 0.82 0.78 0.35 0.49TestP 0.95 0.54 0.69 0.71 0.66 0.58 0.53
R 0.18 0.22 0.54 0.55 0.49 0.27 0.30
F1 0.13 0.21 0.56 0.57 0.51 0.26 0.31
Table 1: Quantitative results evaluated on Training and Test Datasets. Test datasets consist of 12
clips unseen in the training dataset. We report Precision (P), Recall (R) and F1-score (F1).
We propose two base policies, Two-stage Diff andTwo-stage Diff-res policy. Both of them utilize
hierarchical policies and goal representation learning, as described in Section 3.3. The only differ-
ence between them is: the low-level policy of Two-stage Diff directly predicts the target joints, while
Two-stage Diff-res predicts the residual term of an IK solver. Both high- and low-level policies
are trained with Denoising Diffusion Probabilistic Models (DDPM) [28]. The high-level policy is
trained to predict the fingertip trajectory for 4 timesteps given the SDF embedding (See Appendix E)
of goals over 10 timesteps, while the low-level policy predicts the robot actions or residuals for 4
timesteps given the fingertip trajectory. Note that the entire dataset is used for training the high-level
policy, while only around 40 % of the collected clips (110K state-action pairs) are trained with RL
and further used for training the low-level policy. The detailed network implementation is described
in Appendix F.
Then, to analyze the impact of each variable, we design four variants of the Two-stage Diffusion
policy. To evaluate ( 1) the impact of integrating a pre-trained observation encoder, we train a model
without the SDF embedding representation for the goal ( w/o SDF ). To evaluate ( 2) the impact of the
hierarchical architecture, we train a One-stage Diffusion policy that directly predict the joint space
actions given the goal. Finally, to evaluate ( 3) the influence of using different generative models, we
train a Two-stage BeT, that replaces Diffusion models with Behavior-Transformers [23]. We also
consider as baselines a Multi-task RL policy and a BCpolicy with MSE Loss. We provide further
details of the models in Appendix G.
Results As shown in Table 1, despite that Multi-task RL has the highest precision on the test dataset
(this is because it barely presses any keys), our methods (Two-stage Diff and Two-stage Diff-res)
outperform the others in all metrics on both training and test datasets. We also observe that the
incorporation of SDF embedding for goal representation leads to better performance, especially
on the test dataset, which demonstrates the impact of goal representation on policy generalization.
Furthermore, we observe a slight performance enhancement when the model predicts the residual
term of IK (Two-stage Diff-res). We speculate that this improvement stems from our training data
being generated through residual RL, which leverages the output of the IK solver as a prior. This
approach likely causes the learned actions to correlate with the outputs of the IK solver.
4.3 Evaluations on the impact of the data in the generalization
In this section, we investigate the impact of scaling training data on the generalization capabilities
of the agent. We evaluate three policy designs ( One-stage Diff ,Two-stage Diff , and Two-stage
Diff-res ). We train them using various proportions of the dataset, and evaluate their performance on
the test dataset (see Figure 5 Top). Note that One-stage Diff uses the same dataset as the low-level
policy of Two-stage Diff.
Results. We observe that both Two-stage Diff and Two-stage Diff-res show consistent performance
improvement with increasing used data. This trend implies that the two-stage policies have not yet
reached their performance saturation with the given data and could potentially continue to benefit
from additional training data in future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 | Section not found | Section not found | Section not found | Section not found | Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. | future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. Future works can employ faster diffusion models, e.g., DDIM [29],
to speed up the inference.
Out-of-distribution Data Most of the songs in our collected dataset are of modern style. When
evaluating the model on the dataset from [11], which mainly contains classical songs, the perfor-
mance degrades. This discrepancy implies the model’s limited generalization across songs of differ-
ent styles. Future work can collect more diverse training data to improve this aspect.
Acoustic Experience Although the policy achieves up to 56% F1-score on unseen songs, we found
that higher accuracy is still necessary to make the song acoustically appealing and recognizable.
Future work should focus on improving this accuracy to enhance the overall acoustic experience.
5 | Conclusion
In this work, we present PianoMime, a framework for training a generalist robotic pianist using in-
ternet video sources. We start by training song-specific policies with residual RL, enabling the robot
to master individual songs by mimicking human pianists. Subsequently, we train a single behavioral
cloning policy that mimics these song-specific policies to play unseen songs. The policy leverages
three key techniques: goal representation learning, policy hierarchy, and expressive generative mod-
els. The resulting policy demonstrates an impressive generalization capability, achieving an average
F1-score of 70% on unseen songs. This also highlights that leveraging internet data can be highly
useful for training generalist robotic agents.
8 | summary, the main contribution of this work is a framework for training a generalist piano-
playing agent using Internet demonstration data. To achieve this goal, we:
• Introduce a method to learn policies from the internet demonstrations by decoupling the
human motion information from the task-related information.
• Present a reinforcement learning approach that combines residual policy learning strate-
gies [12, 13] with style reward-based strategies [5].
• Explore different policy architecture designs, introducing novel strategies to learn geomet-
rically consistent latent features and conducting ablations on different architectural designs.
Finally, we are releasing the dataset and the trained models as a benchmark for testing internet-data-
driven dexterous manipulation.
2 Related Work
Robotic Piano Playing Several studies have investigated the development of robots capable of play-
ing the piano. In [14], multiple-targets Inverse Kinematics (IK) and offline trajectory planning are
utilized to position the fingers above the intended keys. In [15], a Reinforcement Learning (RL)
agent is trained to control a single Allegro hand to play the piano using tactile sensor feedback.
However, the piano pieces used in these studies are relatively simple. Subsequently, in [11], an RL
agent is trained to control two Shadow Hands to play complex piano pieces by designing a reward
function comprising a fingering reward, a task reward, and an energy reward. In contrast with pre-
vious approaches, our approach exploits Youtube piano-playing videos, enabling faster training and
more accurate and human-like robot behavior.
Motion Retargeting and Reinforcement Learning Our work shares similarities with motion re-
targeting [16], specifically with those works that combine motion retargeting with RL to learn con-
trol policies [17, 18, 5, 19, 6]. Given a mocap demonstration, it has been common to exploit the
2
demonstration rather as a reward function [5, 19] or as a nominal behavior for residual policy learn-
ing [18, 6]. In our work, we not only extract the mocap information, but also task-related information
(piano states) allowing the agent to balance between mimicking the demonstrations and solving the
task.
3 Method
The PianoMime framework is composed of three phases: data preparation, policy learning, and pol-
icy distillation.
In the data preparation phase , given the raw video demonstration, we extract the informative sig-
nals needed to train the policies. Specifically, we extract fingertip trajectories and a MIDI file that
informs the piano state at every time instant.
In the policy learning phase , we train song-specific policies via RL. This step is essential for gener-
ating the robot actions that are missing in the demonstrations. The policy is trained with two reward
functions: a style reward and a task reward. The style reward aims to match the robot’s finger move-
ments with those of the human in the demonstrations to preserve the human style, while the task
reward encourages the robot to press the correct keys at the proper timing.
In the policy distillation phase , we train a single behavioral cloning policy to mimic all the song-
specific policies. The goal of this phase is to train a single generalist policy capable of playing any
song. We explore different policy designs and the representation learning of goals to improve the
generalization capability of the policy.
3.1 Data preparation: From raw data to human and piano state trajectories
We generate the training dataset by web scraping. We download YouTube videos of professional
piano artists playing various songs. We particularly choose YouTube channels that also upload MIDI
files of the played songs. The MIDI files represent trajectories of the piano state (pressed/unpressed
keys) throughout the song. We use the video to extract the motion of human pianists and the MIDI
file to inform about the goal state of piano during the execution of the song.
We select the fingertip position as the essential signal to mimic with the robot hand. While several
dexterous tasks might require the use of the palm (e.g. grasping a bottle), we consider mimicking the
fingertip motion to be sufficient for the task of piano playing. This will also reduce the constraints
applied to the robot, allowing it to adapt its embodiment more freely.
To extract the fingertip motion from videos, we use MediaPipe [20], an open-source framework
for perception. Given a frame from the demonstration videos, MediaPipe outputs the skeleton of
the hand. We find that the classical top-view recording in piano-playing YouTube videos is highly
beneficial for obtaining an accurate estimate of the fingertip positions.
Notice that given the videos are RGB, we lack depth signal. Therefore, we predict the 3D fingertip
positions based on the piano state. The detailed procedure is explained in Appendix A.
3.2 Policy learning: generating robot actions from observations
Through the data preparation phase, we extract two trajectories: a human fingertip trajectory τx
and a piano state trajectory τˇ “(. The human fingertip trajectory τx:px1, . . . ,xTqis aT-step
trajectory of two hands’ 3D fingertip positions xPR3ˆ10(10 fingers). The piano state trajectory
τˇ “(:p ˇ “(1, . . . , ˇ “(Tqis aT-step trajectory of piano states ˇ “(PB88, represented with an 88-dimensional
binary variable representing which keys should be pressed.
Given the R OBOPIANIST [11] environment, our goal is to learn a goal-conditioned policy πθthat
plays the song defined by τˇ “(while matching the fingertip motion given by τx. Notice that satisfying
both objectives jointly might be impossible. Tracking perfectly the fingertip trajectory τxmight not
necessarily lead to playing the song correctly. Although both trajectories are collected from the same
source, errors in hand tracking and embodiment mismatches might lead to deviations, resulting in
poor song performance. Thus, we propose using τxas a style guiding behavior.
3
Observation
Encoder
Fingertip
PolicyInverse
Model
FK
Figure 2: Proposed distillation policy architecture. Given a L steps window of a target song τt
ˇ “(:
p ˇ “(t:t`Lqat time t, a latent representation τt
zis computed given a pre-trained observation encoder.
Then, the policy is decoupled between a high-level fingertip predictor that generates a trajectory of
fingertip positions τt
xand a low-level inverse dynamics model that generates a trajectory of target
joint position τt
q.
Similarly to [11], we formulate the piano playing as an Markov Decision Process (MDP) with the
horizon of the episode H, being the duration of the song to be played. The state observation is
defined by the robot’s proprioception sand the goal state gt. The goal state gtat time tinforms the
desired piano key configurations ˇ “(in the future gt“p ˇ “(t`1, . . . , ˇ “(t`Lq, with Lbeing the lookahead
horizon. As claimed in [11], to successfully learn how to play, the agent needs to be aware of several
steps into the future to plan its actions. The action ais defined as the desired configuration for both
hands qPR23ˆ2`1, each with 23 joint angles and one dimension for the sustain pedal.
We propose solving the reinforcement learning problem by combining residual policy learning [12,
13, 6] and style mimicking rewards [5, 19].
Residual policy architecture. Given the fingertip trajectory τx, we solve an IK [21] problem to
obtain a trajectory of desired joint angles τik
q:pqik
0, . . . ,qik
Tqfor the robot hands. Then, we represent
the policy πθpa|s,gtq“πr
θpa|s,gtq`qik
t`1as a combination of a nominal behavior (given by the IK
solution) and a residual policy πr
θ. Given the goal state at time t, the nominal behavior is defined as
the next desired joint angle qik
t`1. We then only learn the residual term around the nominal behavior.
In practice, we initialize the robot at qik
0and roll both the goal state and the nominal behavior with a
sliding window along τˇ “(andτik
qrespectively.
Style-mimicking reward. We also integrate a style-mimicking reward to preserve the human style
in the trained robot actions. The reward function r“rˇ “(`rxis composed of a task reward rˇ “(and
a style-mimicking reward rx. While the task reward rˇ “(encourages the agent to press the correct
keys, the style reward rxencourages the agent to move its fingertips similar to the demonstration
τx. We provide further details in Appendix C.
3.3 Policy distillation: learning a generalist piano-playing agent
Through the policy learning phase, we train song-specific expert policies from which we roll out
state and action trajectories τs:ps0, . . . ,sTqandτq:pq0, . . . ,qTq. Then, we generate a dataset D:
pτi
s, τi
q, τi
x, τi
ˇ “(qN
i“1withNbeing the number of learned songs. Given the dataset D, we apply Be-
havioral Cloning (BC) to learn a single generalist piano-playing agent πθpqt:t`L,xt:t`L|st, ˇ “(t:t`Lq
that outputs configuration-space actions qt:t`Land fingertip motion xt:t`Lconditioned on the cur-
rent state stand the future desired piano state ˇ “(t:t`L.
We explore different strategies to represent and learn the behavioral cloning policy and improve
its generalization capabilities. In particular, we explore ( 1) representation learning approaches to
induce spatially informative features, ( 2) a hierarchical policy structure for sample-efficient training,
and ( 3) expressive generative models [22, 23, 24] to capture the multimodality of the data. Also,
inspired by current behavioral cloning approaches [22, 25], we train policies that output sequences
of actions rather than single-step actions and execute them in chunks.
Representation Learning. We pre-train an observation encoder over the piano state ˇ “(to learn
spatially consistent latent features. We hypothesize that two piano states that are spatially close
4
should lead to latent features that are close. Using these latent features as goal should induce better
generalization. To obtain the observation encoder, we train an autoencoder with a reconstruction loss
over a Signed Distance Field (SDF) defined on the piano state. Specifically, the encoder compresses
the binary vector of the goal into a latent space, while the decoder predicts the SDF function value
of a randomly sampled query point (the distance between the query point and the closest ”on” piano
key). We provide further details in Appendix E.
Hierarchical Policy. We represent the piano-playing agent with a hierarchical policy. The high-
level policy receives a sequence of desired future piano states ˇ “(and outputs a trajectory of human
fingertip positions x. Then, a low-level policy takes the fingertip and piano state trajectories as
input and outputs a trajectory of desired joint angles q. On one hand, while fingertip trajectory
data is easily available from the Internet, obtaining low-level joint trajectories requires solving a
computationally expensive RL problem. On the other hand, while the high-level mapping ( ˇ “(ÞÑx)
is complex, which involves fingerings, the low-level mapping ( xÞÑq) is relatively simpler, which
addresses a cross-embodiment inverse dynamics problem. This decoupling allows us to train the
more complex high-level mapping on large cheap datasets and the simpler low-level mapping on
smaller expensive ones. We visualize the policy in Figure 2.
Expressive Generative Models. Considering that the human demonstration data of piano playing
is highly multi-modal, we explore using expressive generative models to better represent this multi-
modality. We compare the performance of different deep generative models based policies, e.g.,
Diffusion Policies [22] and Behavioral Transformer [23], as well as a deterministic policy.
4 Experimental Results
We split the experimental evaluation into three parts. In the first part, we explore the performance of
our proposed framework in learning song-specific policies via RL. In the second part, we perform
ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three
methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also results
in a larger discrepancy between the fingertip trajectory of the robot and the human. Thus, the weight
of the style-mimicking reward can be viewed as a parameter that controls the human likeness of the
learned robot actions.
Qualitative comparison. We present a qualitative comparison of the human likeness of the robot
motion in Figure 4 and the attached videos. We inspect the hand poses for certain frames and ob-
serve that the IK nominal behavior leads the robot to place the fingers in positions similar to those in
Youtube videos. The RL policy then slightly adapts the fingertip positions to press the keys correctly.
4.2 Evaluation of model design strategies for policy distillation
This section focuses on the evaluation of policy distillation for playing different songs. We evaluate
the influence of different policy design strategies on the agent’s performance. We aim to assess ( 1)
the impact of integrating a pre-trained observation encoder to induce spatially consistent features,
(2) the impact of a hierarchical design of the policy, and ( 3) the performance of different generative
models on piano-playing data.
6
Multi-RL BC-MSE Two-Stage Diff -res w/o SDF One-Stage BeTTrainP 0.85 0.56 0.87 0.89 0.86 0.53 0.63
R 0.20 0.29 0.78 0.80 0.76 0.34 0.42
F1 0.12 0.30 0.81 0.82 0.78 0.35 0.49TestP 0.95 0.54 0.69 0.71 0.66 0.58 0.53
R 0.18 0.22 0.54 0.55 0.49 0.27 0.30
F1 0.13 0.21 0.56 0.57 0.51 0.26 0.31
Table 1: Quantitative results evaluated on Training and Test Datasets. Test datasets consist of 12
clips unseen in the training dataset. We report Precision (P), Recall (R) and F1-score (F1).
We propose two base policies, Two-stage Diff andTwo-stage Diff-res policy. Both of them utilize
hierarchical policies and goal representation learning, as described in Section 3.3. The only differ-
ence between them is: the low-level policy of Two-stage Diff directly predicts the target joints, while
Two-stage Diff-res predicts the residual term of an IK solver. Both high- and low-level policies
are trained with Denoising Diffusion Probabilistic Models (DDPM) [28]. The high-level policy is
trained to predict the fingertip trajectory for 4 timesteps given the SDF embedding (See Appendix E)
of goals over 10 timesteps, while the low-level policy predicts the robot actions or residuals for 4
timesteps given the fingertip trajectory. Note that the entire dataset is used for training the high-level
policy, while only around 40 % of the collected clips (110K state-action pairs) are trained with RL
and further used for training the low-level policy. The detailed network implementation is described
in Appendix F.
Then, to analyze the impact of each variable, we design four variants of the Two-stage Diffusion
policy. To evaluate ( 1) the impact of integrating a pre-trained observation encoder, we train a model
without the SDF embedding representation for the goal ( w/o SDF ). To evaluate ( 2) the impact of the
hierarchical architecture, we train a One-stage Diffusion policy that directly predict the joint space
actions given the goal. Finally, to evaluate ( 3) the influence of using different generative models, we
train a Two-stage BeT, that replaces Diffusion models with Behavior-Transformers [23]. We also
consider as baselines a Multi-task RL policy and a BCpolicy with MSE Loss. We provide further
details of the models in Appendix G.
Results As shown in Table 1, despite that Multi-task RL has the highest precision on the test dataset
(this is because it barely presses any keys), our methods (Two-stage Diff and Two-stage Diff-res)
outperform the others in all metrics on both training and test datasets. We also observe that the
incorporation of SDF embedding for goal representation leads to better performance, especially
on the test dataset, which demonstrates the impact of goal representation on policy generalization.
Furthermore, we observe a slight performance enhancement when the model predicts the residual
term of IK (Two-stage Diff-res). We speculate that this improvement stems from our training data
being generated through residual RL, which leverages the output of the IK solver as a prior. This
approach likely causes the learned actions to correlate with the outputs of the IK solver.
4.3 Evaluations on the impact of the data in the generalization
In this section, we investigate the impact of scaling training data on the generalization capabilities
of the agent. We evaluate three policy designs ( One-stage Diff ,Two-stage Diff , and Two-stage
Diff-res ). We train them using various proportions of the dataset, and evaluate their performance on
the test dataset (see Figure 5 Top). Note that One-stage Diff uses the same dataset as the low-level
policy of Two-stage Diff.
Results. We observe that both Two-stage Diff and Two-stage Diff-res show consistent performance
improvement with increasing used data. This trend implies that the two-stage policies have not yet
reached their performance saturation with the given data and could potentially continue to benefit
from additional training data in future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. Future works can employ faster diffusion models, e.g., DDIM [29],
to speed up the inference.
Out-of-distribution Data Most of the songs in our collected dataset are of modern style. When
evaluating the model on the dataset from [11], which mainly contains classical songs, the perfor-
mance degrades. This discrepancy implies the model’s limited generalization across songs of differ-
ent styles. Future work can collect more diverse training data to improve this aspect.
Acoustic Experience Although the policy achieves up to 56% F1-score on unseen songs, we found
that higher accuracy is still necessary to make the song acoustically appealing and recognizable.
Future work should focus on improving this accuracy to enhance the overall acoustic experience.
5 Conclusion
In this work, we present PianoMime, a framework for training a generalist robotic pianist using in-
ternet video sources. We start by training song-specific policies with residual RL, enabling the robot
to master individual songs by mimicking human pianists. Subsequently, we train a single behavioral
cloning policy that mimics these song-specific policies to play unseen songs. The policy leverages
three key techniques: goal representation learning, policy hierarchy, and expressive generative mod-
els. The resulting policy demonstrates an impressive generalization capability, achieving an average
F1-score of 70% on unseen songs. This also highlights that leveraging internet data can be highly
useful for training generalist robotic agents.
8 | Acknowledgments
If a paper is accepted, the final camera-ready version will (and probably should) include acknowl-
edgments. All acknowledgments go at the end of the paper, including thanks to reviewers who gave
useful comments, to colleagues who contributed to the ideas, and to funding agencies and corporate
sponsors that provided financial support. | References
[1] M. V ¨olske, M. Potthast, S. Syed, and B. Stein. Tl; dr: Mining reddit to learn automatic
summarization. In Proceedings of the Workshop on New Frontiers in Summarization , pages
59–63, 2017.
[2] L. Fan, G. Wang, Y . Jiang, A. Mandlekar, Y . Yang, H. Zhu, A. Tang, D.-A. Huang, Y . Zhu,
and A. Anandkumar. Minedojo: Building open-ended embodied agents with internet-scale
knowledge. Advances in Neural Information Processing Systems , 35:18343–18362, 2022.
[3] K. Grauman, A. Westbury, E. Byrne, Z. Chavis, A. Furnari, R. Girdhar, J. Hamburger, H. Jiang,
M. Liu, X. Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition , pages
18995–19012, 2022.
[4] F. Torabi, G. Warnell, and P. Stone. Recent advances in imitation learning from observation.
arXiv preprint arXiv:1905.13566 , 2019.
[5] X. B. Peng, P. Abbeel, S. Levine, and M. Van de Panne. Deepmimic: Example-guided deep re-
inforcement learning of physics-based character skills. ACM Transactions On Graphics (TOG) ,
37(4):1–14, 2018.
[6] G. Garcia-Hernando, E. Johns, and T.-K. Kim. Physics-based dexterous manipulations with
estimated hand poses and residual reinforcement learning. In 2020 IEEE/RSJ International
Conference on Intelligent Robots and Systems (IROS) , pages 9561–9568. IEEE, 2020.
[7] X. B. Peng, E. Coumans, T. Zhang, T.-W. Lee, J. Tan, and S. Levine. Learning agile robotic
locomotion skills by imitating animals. Robotics: Science and Systems (RSS) , 2020.
[8] A. Nair, D. Chen, P. Agrawal, P. Isola, P. Abbeel, J. Malik, and S. Levine. Combining self-
supervised learning and imitation for vision-based rope manipulation. In 2017 IEEE interna-
tional conference on robotics and automation (ICRA) , pages 2146–2153. IEEE, 2017.
[9] L. Shao, T. Migimatsu, Q. Zhang, K. Yang, and J. Bohg. Concept2robot: Learning manip-
ulation concepts from instructions and human demonstrations. The International Journal of
Robotics Research , 40(12-14):1419–1434, 2021.
[10] Y . J. Ma, S. Sodhani, D. Jayaraman, O. Bastani, V . Kumar, and A. Zhang. Vip: Towards
universal visual reward and representation via value-implicit pre-training. arXiv preprint
arXiv:2210.00030 , 2022.
[11] K. Zakka, P. Wu, L. Smith, N. Gileadi, T. Howell, X. B. Peng, S. Singh, Y . Tassa, P. Florence,
A. Zeng, et al. Robopianist: Dexterous piano playing with deep reinforcement learning. In
Conference on Robot Learning , pages 2975–2994. PMLR, 2023.
[12] T. Silver, K. Allen, J. Tenenbaum, and L. Kaelbling. Residual policy learning. arXiv preprint
arXiv:1812.06298 , 2018.
[13] T. Johannink, S. Bahl, A. Nair, J. Luo, A. Kumar, M. Loskyll, J. A. Ojea, E. Solowjow, and
S. Levine. Residual reinforcement learning for robot control. In 2019 international conference
on robotics and automation (ICRA) , pages 6023–6029. IEEE, 2019.
9
[14] B. Scholz. Playing piano with a shadow dexterous hand. PhD thesis, Universitat Hamburg ,
2019.
[15] H. Xu, Y . Luo, S. Wang, T. Darrell, and R. Calandra. Towards learning to play piano with
dexterous hands and touch. In 2022 IEEE/RSJ International Conference on Intelligent Robots
and Systems (IROS) , pages 10410–10416. IEEE, 2022.
[16] T. Geijtenbeek, M. Van De Panne, and A. F. Van Der Stappen. Flexible muscle-based locomo-
tion for bipedal creatures. ACM Transactions on Graphics (TOG) , 32(6):1–11, 2013.
[17] N. Chentanez, M. M ¨uller, M. Macklin, V . Makoviychuk, and S. Jeschke. Physics-based mo-
tion capture imitation with deep reinforcement learning. In Proceedings of the 11th ACM
SIGGRAPH Conference on Motion, Interaction and Games , pages 1–10, 2018.
[18] L. Liu and J. Hodgins. Learning basketball dribbling skills using trajectory optimization and
deep reinforcement learning. ACM Transactions on Graphics (TOG) , 37(4):1–14, 2018.
[19] X. B. Peng, Z. Ma, P. Abbeel, S. Levine, and A. Kanazawa. Amp: Adversarial motion priors
for stylized physics-based character control. ACM Transactions on Graphics (ToG) , 40(4):
1–20, 2021.
[20] C. Lugaresi, J. Tang, H. Nash, C. McClanahan, E. Uboweja, M. Hays, F. Zhang, C.-L. Chang,
M. G. Yong, J. Lee, et al. Mediapipe: A framework for building perception pipelines. arXiv
preprint arXiv:1906.08172 , 2019.
[21] S. Caron, Y . De Mont-Marin, R. Budhiraja, and S. H. Bang. Pink: Python inverse kinematics
based on Pinocchio, 2024. URL https://github.com/stephane-caron/pink .
[22] C. Chi, S. Feng, Y . Du, Z. Xu, E. Cousineau, B. Burchfiel, and S. Song. Diffusion policy:
Visuomotor policy learning via action diffusion. arXiv preprint arXiv:2303.04137 , 2023.
[23] N. M. Shafiullah, Z. Cui, A. A. Altanzaya, and L. Pinto. Behavior transformers: Cloning k
modes with one stone. Advances in neural information processing systems , 35:22955–22968,
2022.
[24] P. Florence, C. Lynch, A. Zeng, O. A. Ramirez, A. Wahid, L. Downs, A. Wong, J. Lee, I. Mor-
datch, and J. Tompson. Implicit behavioral cloning. In Conference on Robot Learning , pages
158–168. PMLR, 2022.
[25] T. Z. Zhao, V . Kumar, S. Levine, and C. Finn. Learning fine-grained bimanual manipulation
with low-cost hardware. arXiv preprint arXiv:2304.13705 , 2023.
[26] E. Todorov, T. Erez, and Y . Tassa. Mujoco: A physics engine for model-based control. In
2012 IEEE/RSJ International Conference on Intelligent Robots and Systems , pages 5026–
5033, 2012. doi:10.1109/IROS.2012.6386109.
[27] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization
algorithms. arXiv preprint arXiv:1707.06347 , 2017.
[28] J. Ho, A. Jain, and P. Abbeel. Denoising diffusion probabilistic models. Advances in neural
information processing systems , 33:6840–6851, 2020.
[29] J. Song, C. Meng, and S. Ermon. Denoising diffusion implicit models. arXiv preprint
arXiv:2010.02502 , 2020.
[30] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
10
[31] D. Hendrycks and K. Gimpel. Gaussian error linear units (gelus). arXiv preprint
arXiv:1606.08415 , 2016.
[32] E. Perez, F. Strub, H. De Vries, V . Dumoulin, and A. Courville. Film: Visual reasoning with
a general conditioning layer. In Proceedings of the AAAI conference on artificial intelligence ,
volume 32, 2018.
[33] T. Haarnoja, A. Zhou, P. Abbeel, and S. Levine. Soft actor-critic: Off-policy maximum entropy
deep reinforcement learning with a stochastic actor. In International conference on machine
learning , pages 1861–1870. PMLR, 2018.
11
𝐻3×3Youtube MujocoFigure 6: Compute homography matrix given 8 correspondence feature points.
A Retargeting: From human hand to robot hand
To retarget from the human hand to robot hand, we follow a structured process.
Step 1: Homography Matrix Computation Given a top-view piano demonstration video, we
firstly choose ndifferent feature points on the piano. These points could be center points of specific
keys, edges, or other identifiable parts of the keys that are easily recognizable (See Figure 6).
Due to the uniform design of pianos, these points represent the same physical positions in both
the video and Mujoco. Given the chosen points, we follow the Eight-point Algorithm to compute
the Homography Matrix Hthat transforms the pixel coordinate in videos to the x-y coordinate in
Mujoco (z-axis is the vertical axis).
Step 2: Transformation of Fingertip Trajectory We then obtain the human fingertip tra-
jectory with MediaPipe [20]. We collect the fingertips positions every 0.05 seconds. Then we
transform the human fingertip trajectory within pixel coordinate into the Mujoco x-y 2D coordinate
using the computed homography matrix H.
Step 3: Heuristic Adjustment for Physical Alignment We found that the transformed fin-
gertip trajectory might not physically align with the notes, which means there might be no detected
fingertip that physically locates at the keys to be pressed or the detected fingertip might locate at the
border of the key (normally human presses the middle point of the horizontal axis of the key). This
misalignment could be due to the inaccuracy of the hand-tracking algorithm and the homography
matrix. Therefore, we perform a simple heuristic adjustment on the trajectory to improve the
physical alignment. Specifically, at each timestep of the video, we check whether there is any
fingertip that physically locates at the key to be pressed. If there is, we adjust its y-axis value to
the middle point of the corresponding key. Otherwise, we search within a small range, specifically
the neighboring two keys, to find the nearest fingertip. If no fingertip is found in the range or
the found fingertip has been assigned to another key to be pressed, we then leave it. Otherwise,
we adjust its y-axis value to the center of the corresponding key to ensure proper physical alignment.
Step 4: Z-axis Value Assignment Lastly, we assign the z-axis value for the fingertips. For
the fingertips that press keys, we set their z-axis values to 0. For other fingertips, we set their z-axis
value to 2¨hkey, where hkeyis the height of the keys in Mujoco.
B Implementation of Inverse Kinematics Solver
The implementation of the IK solver is based on the approach of [21]. The solver addresses multiple
tasks simultaneously by formulating an optimization problem and find the optimal joint velocities
that minimize the objective function. The optimization problem is given by:
min
9qÿ
iwi}Ji9q´Kivi}2, (1)
12
where wiis the weight of each task, Kiis the proportional gain and viis the velocity residual. We
define a set of 10 tasks, each specifying the desired position of one of the robot fingertips. We do not
specify the desired quaternions. All the weights wiare set to be equal. We use quadprog2to solve
the optimization problem with quadratic programming. The other parameters are listed in Table 2.
Table 2: The parameters of IK solver
Parameter Value
Gain 1.0
Limit Gain 0.05
Damping 1e-6
Levenberg-Marquardt Damping 1e-6
C Detailed MDP Formulation of Song-specific Policy
Table 3: The detailed reward function to train the song-specific policy. The Key Press reward is the
same as in [11], where ksandkgrepresent the current and the goal states of the key respectively,
and g is a function that transforms the distances to rewards in the [0, 1] range. pd fandprfrepresent
the fingertip positions of human demonstrator and robot respectively.
Reward Formula Weight Explanation
Key Press 0.5¨gp}ks´kg}2q`0.5¨p1´1false positiveq2/3 Press the right keys and
only the right keys
Mimic gp}pd f´prf}2q 1/3 Mimic the demonstrator’s
fingertip trajectory
Table 4: The observation space of song-specific agent.
Observation Unit Size
Hand and Forearm Joint Positions Rad 52
Hand and forearm Joint Velocities Rad/s 52
Piano Key Joint Positions Rad 88
Piano key Goal State Discrete 88
Demonstrator Forearm and Fingertips Cartesian Positions m 36
Prior control input ˜u(solved by IK) Rad 52
Sustain Pedal state Discrete 1
D Training Details of Song-specific Policy
We use PPO [27] (implemented by StableBaseline 3 [30]) to train the song-specific policy with resid-
ual RL(See Algorithm 1). All of the experiments are conducted using the same network architecture
and tested using 3 different seeds. Both actor and critic networks are of the same architecture, con-
taining 2 MLP hidden layers with 1024 and 256 nodes, respectively, and GELU [31] as activation
functions. The detailed hyperparameters of the networks are listed in Table 7.
2https://github.com/quadprog/quadprog
13
Table 5: The action space of song-specific agent.
Action Unit Size
Target Joint Positions Rad 46
Sustain Pedal Discrete 1
Table 6: The Hyperparameters of PPO
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Exponential Decay
Decay Rate 0.999
Actor Hidden Units 1024, 256
Actor Activation GELU
Critic Hidden Units 1024, 256
Critic Activation GELU
Discount Factor 0.99
Steps per Update 8192
GAE Lambda 0.95
Entropy Coefficient 0.0
Maximum Gradient Norm 0.5
Batch Size 1024
Number of Epochs per Iteration 10
Clip Range 0.2
Number of Iterations 2000
Optimizer Adam
E Representation Learning of Goal
We train an autoencoder to learn a geometrically continuous representation of the goal (See Figure
7 and Algorithm 2). During the training phase, the encoder E, encodes the original 88-dimensional
binary representation of a goal piano state ˇ “(tinto a 16-dimensional latent code z. The positional
encoding of a randomly sampled 3D query coordinate xis then concatenated with the latent code z
and passed through the decoder D. We use positional encoding here to represent the query coordinate
more expressively. The decoder is trained to predict the SDF fpx, ˇ “(tq. We define the SDF value of
xwith respect to ˇ “(tas the Euclidean distance between the xand the nearest key that is supposed to
be pressed in ˇ “(t, mathematically expressed as:
SDFpx, ˇ “(tq“ min
pPtpi| ˇ “(t,i“1u}x´p}, (2)
where pirepresents the position of the i-th key on the piano. The encoder and decoder are jointly
optimized to minimize the reconstruction loss:
Lpx, , ˇ “(tq“p SDFpx, ˇ “(tq´DpEpv, xqqq2. (3)
We pre-train the autoencoder using the GiantMIDI dataset3, which contains 10K piano MIDI files
of 2,786 composers. The pre-trained encoder maps the ˇ “(tinto the 16-dimensional latent code,
which serves as the latent goal for behavioral cloning. The encoder network is composed of four
3https://github.com/bytedance/GiantMIDI-Piano
14
Algorithm 1: Training of the song-specific policy with residual RL
1:Initialize actor network πθ
2:Initialize critic network vϕ
3:fori“1 :Niteration do
4: # Collect trajectories
5: fort“1 :Tdo
6: Get human demonstrator fingertip position xtand observation ot
7: Compute the prior control signal that tracks xtwith the IK controller ˜ut“ikpxt, otq
8: Run policy to get the residual term rt“πθpotq
9: Compute the adapted control signal ut“˜ut`rt
10: Execute utin environment and collect st, ut, rt, st`1
11: end for
12: # Update networks
13: forn“1 :Ndo
14: Sample a batch of transitions tpsj, uj, rj, sj`1qufrom the collected trajectories
15: Update the actor and critic network with PPO
16: end for
17:end for
Query
Coordinate
Positional
Embedding
SDF Encoder
...1
0
10
188-dimensional
binary vector
Latent
Code+
Figure 7: 1) Encoding: The encoder compresses the binary representation of the goal into latent
code. 2) Decoding: A 3D query coordinate xis randomly sampled. A neural network predicts the
SDF value given the positional encoding of xand the latent code.
1D-convolutional layers, followed by a linear layer. Each successive 1D-convolutional layer has an
increasing number of filters, specifically 2, 4, 8, and 16 filters, respectively. All convolutional layers
utilize a kernel size of 3. The linear layer transforms the flattened output from the convolutional
layers into a 16-dimensional latent code. The decoder network is a MLP with 2 hidden layers, each
with 16 neurons. We train the autoencoder for 100 epochs with a learning rate of 1e´3.
F Training Details of Diffusion Model
All the diffusion models utilized in this work, including One-stage Diff, the high-level and
low-level policies of Two-stage Diff, Two-stage Diff-res and Two-stage Diff w/o SDF, share
15
Algorithm 2: Training of the goal autoencoder
1:Initialize encoder Eϕ
2:Initialize decoder Dψ
3:fori“1 :Nepoch do
4: forj“1 :Nbatch do
5: foreach goal vin batch do
6: Compute the latent code z“Eψp ˇ “(tq
7: Sample a 3D coordinate as query x“Sample3DCoordinate()
8: Compute the positional encoding of query pe“PositionalEncoding( xq
9: Compute the output of the decoder conditioned by the query Dϕpz, peq
10: Compute the SDF value of query SDF px, ˇ “(tq
11: Compute the reconstruction loss L
12: end for
13: Compute the sum of the loss
14: Compute the gradient
15: Update network parameter ϕ, ψ
16: end for
17:end for
the same network architecture. The network architecture are the same as the U-net diffusion
policy in [22] and optimized with DDPM [28], except that we use temporal convolutional net-
works (TCNs) as the observation encoder, taking the concatenated goals (high-level policy) or
fingertip positions (low-level policy) of several timesteps as input to extract the features on tem-
poral dimension. Each level of U-net is then conditioned by the outputs of TCNs through FiLM [32].
High-level policies take the goals over 10 timesteps and the current fingertip position as in-
put and predict the human fingertip positions. In addition, we add a standard gaussian noise on the
current fingertip position during training to facilitate generalization. We further adjust the y-axis
value of the fingertips pressing the keys in the predicted high-level trajectories to the midpoint
of the keys. This adjustment ensures closer alignment with the data distribution of the training
dataset. Low-level policies take the predicted fingertip positions and the goals over 4 timesteps, the
proprioception state as input predict the robot actions. The proprioception state includes the robot
joint positions and velocities, as well as the piano joint positions. We use 100 diffusion steps during
training. To achieve high-quality results during inference, we find that at least 80 diffusion steps are
required for high-level policies and 50 steps for low-level policies.
Table 7: The Hyperparameters of DDPM
Hyperparameter Value
Initial Learning Rate 1e-4
Learning Rate Scheduler Cosine
U-Net Filters Number 256, 512, 1024
U-Net Kernel Size 5
TCN Filters Number 32, 64
TCN Kernel Size 3
Diffusion Steps Number 100
Batch Size 256
Number of Iterations 800
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
16
G Policy Distillation Experiment
Two-stage Diff w/o SDF We directly use the binary representation of goal instead of the SDF
embedding representation to condition the high-level and low-level policies.
Two-stage Diff-res We employ an IK solver to compute the target joints given the fingertip
positions predicted by the high-level policy. The low-level policy predicts the residual terms of IK
solver instead of the robot actions.
Two-stage BeT We train both high-level and low-level policies with Behavior Transformer
[23] instead of DDPM. The hyperparameter of Bet is listed in Table 8.
One-stage Diff We train a single diffusion model to predict the robot actions given the SDF
embedding representation of goals and the proprioception state.
Multi-task RL We create a multi-task environment where for each episode a random song is
sampled from the dataset. Consequently, we use Soft-Actor-Critic (SAC) [33] to train a single agent
within the environment. Both the actor and critic networks are MLPs, each with 3 hidden layers,
and each hidden layer contains 256 neurons. The reward function is the same as that in [11].
BC-MSE We train a feedforward network to predict the robot action of next timestep con-
ditioned on the binary representation of goal and proprioception state with MSE loss. The
feedforward network is a MLP with 3 hidden layers, each with 1024 neurons.
Table 8: The Hyperparameters of Behavior Transformer
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Cosine
Number of Discretization Bins 64
Number of Transformer Heads 8
Number of Transformer Layers 8
Embedding Dimension 120
Batch Size 256
Number of Iterations 1200
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
H F1 Score of All Trained Song-Specific Policies
Figure 8 shows the F1 score of all song-specific policies we trained.
I Detailed Results on Test Dataset
In Table 9 and Table 10, we show the Precision, Recall and F1 score of each song in our collected
test dataset and the Etude-12 dataset from [11], achieved by Two-stage Diff and Two-stage Diff-res,
respectively. We observe an obvious performance degradation when testing on Etude-12 dataset.
We suspect that the reason is due to out-of-distribution data, as the songs in the Etude-12 dataset are
all classical, whereas our training and test dataset primarily consists of modern songs.
17
Table 9: Quantitative results of each song in the our collected test dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
Forester 0.81 0.70 0.68 0.79 0.71 0.67
Wednesday 0.66 0.57 0.58 0.67 0.54 0.55
Alone 0.80 0.62 0.66 0.83 0.65 0.67
Somewhere Only We Know 0.63 0.53 0.58 0.67 0.57 0.59
Eyes Closed 0.60 0.52 0.53 0.61 0.45 0.50
Pedro 0.70 0.58 0.60 0.67 0.56 0.47
Ohne Dich 0.73 0.55 0.58 0.75 0.56 0.62
Paradise 0.66 0.42 0.43 0.68 0.45 0.47
Hope 0.74 0.55 0.57 0.76 0.58 0.62
No Time To Die 0.77 0.53 0.55 0.79 0.57 0.60
The Spectre 0.64 0.52 0.54 0.67 0.50 0.52
Numb 0.55 0.44 0.45 0.57 0.47 0.48
Mean 0.69 0.54 0.56 0.71 0.55 0.57
Table 10: Quantitative results of each song in the Etude-12 dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
FrenchSuiteNo1Allemande 0.45 0.31 0.34 0.39 0.27 0.30
FrenchSuiteNo5Sarabande 0.29 0.23 0.24 0.24 0.18 0.19
PianoSonataD8451StMov 0.58 0.52 0.52 0.60 0.50 0.51
PartitaNo26 0.35 0.22 0.24 0.40 0.24 0.26
WaltzOp64No1 0.44 0.31 0.33 0.43 0.28 0.31
BagatelleOp3No4 0.45 0.30 0.33 0.45 0.28 0.32
KreislerianaOp16No8 0.43 0.34 0.36 0.49 0.34 0.36
FrenchSuiteNo5Gavotte 0.34 0.29 0.33 0.41 0.31 0.33
PianoSonataNo232NdMov 0.35 0.24 0.25 0.29 0.19 0.21
GolliwoggsCakewalk 0.60 0.43 0.45 0.57 0.40 0.42
PianoSonataNo21StMov 0.32 0.22 0.25 0.36 0.23 0.25
PianoSonataK279InCMajor1StMov 0.43 0.35 0.35 0.53 0.38 0.39
Mean 0.42 0.31 0.33 0.43 0.30 0.32
18
Figure 8: F1 score of all 184 trained song-specific policies (descending order)
19 | Appendix A.
3.2 Policy learning: generating robot actions from observations
Through the data preparation phase, we extract two trajectories: a human fingertip trajectory τx
and a piano state trajectory τˇ “(. The human fingertip trajectory τx:px1, . . . ,xTqis aT-step
trajectory of two hands’ 3D fingertip positions xPR3ˆ10(10 fingers). The piano state trajectory
τˇ “(:p ˇ “(1, . . . , ˇ “(Tqis aT-step trajectory of piano states ˇ “(PB88, represented with an 88-dimensional
binary variable representing which keys should be pressed.
Given the R OBOPIANIST [11] environment, our goal is to learn a goal-conditioned policy πθthat
plays the song defined by τˇ “(while matching the fingertip motion given by τx. Notice that satisfying
both objectives jointly might be impossible. Tracking perfectly the fingertip trajectory τxmight not
necessarily lead to playing the song correctly. Although both trajectories are collected from the same
source, errors in hand tracking and embodiment mismatches might lead to deviations, resulting in
poor song performance. Thus, we propose using τxas a style guiding behavior.
3
Observation
Encoder
Fingertip
PolicyInverse
Model
FK
Figure 2: Proposed distillation policy architecture. Given a L steps window of a target song τt
ˇ “(:
p ˇ “(t:t`Lqat time t, a latent representation τt
zis computed given a pre-trained observation encoder.
Then, the policy is decoupled between a high-level fingertip predictor that generates a trajectory of
fingertip positions τt
xand a low-level inverse dynamics model that generates a trajectory of target
joint position τt
q.
Similarly to [11], we formulate the piano playing as an Markov Decision Process (MDP) with the
horizon of the episode H, being the duration of the song to be played. The state observation is
defined by the robot’s proprioception sand the goal state gt. The goal state gtat time tinforms the
desired piano key configurations ˇ “(in the future gt“p ˇ “(t`1, . . . , ˇ “(t`Lq, with Lbeing the lookahead
horizon. As claimed in [11], to successfully learn how to play, the agent needs to be aware of several
steps into the future to plan its actions. The action ais defined as the desired configuration for both
hands qPR23ˆ2`1, each with 23 joint angles and one dimension for the sustain pedal.
We propose solving the reinforcement learning problem by combining residual policy learning [12,
13, 6] and style mimicking rewards [5, 19].
Residual policy architecture. Given the fingertip trajectory τx, we solve an IK [21] problem to
obtain a trajectory of desired joint angles τik
q:pqik
0, . . . ,qik
Tqfor the robot hands. Then, we represent
the policy πθpa|s,gtq“πr
θpa|s,gtq`qik
t`1as a combination of a nominal behavior (given by the IK
solution) and a residual policy πr
θ. Given the goal state at time t, the nominal behavior is defined as
the next desired joint angle qik
t`1. We then only learn the residual term around the nominal behavior.
In practice, we initialize the robot at qik
0and roll both the goal state and the nominal behavior with a
sliding window along τˇ “(andτik
qrespectively.
Style-mimicking reward. We also integrate a style-mimicking reward to preserve the human style
in the trained robot actions. The reward function r“rˇ “(`rxis composed of a task reward rˇ “(and
a style-mimicking reward rx. While the task reward rˇ “(encourages the agent to press the correct
keys, the style reward rxencourages the agent to move its fingertips similar to the demonstration
τx. We provide further details in Appendix C.
3.3 Policy distillation: learning a generalist piano-playing agent
Through the policy learning phase, we train song-specific expert policies from which we roll out
state and action trajectories τs:ps0, . . . ,sTqandτq:pq0, . . . ,qTq. Then, we generate a dataset D:
pτi
s, τi
q, τi
x, τi
ˇ “(qN
i“1withNbeing the number of learned songs. Given the dataset D, we apply Be-
havioral Cloning (BC) to learn a single generalist piano-playing agent πθpqt:t`L,xt:t`L|st, ˇ “(t:t`Lq
that outputs configuration-space actions qt:t`Land fingertip motion xt:t`Lconditioned on the cur-
rent state stand the future desired piano state ˇ “(t:t`L.
We explore different strategies to represent and learn the behavioral cloning policy and improve
its generalization capabilities. In particular, we explore ( 1) representation learning approaches to
induce spatially informative features, ( 2) a hierarchical policy structure for sample-efficient training,
and ( 3) expressive generative models [22, 23, 24] to capture the multimodality of the data. Also,
inspired by current behavioral cloning approaches [22, 25], we train policies that output sequences
of actions rather than single-step actions and execute them in chunks.
Representation Learning. We pre-train an observation encoder over the piano state ˇ “(to learn
spatially consistent latent features. We hypothesize that two piano states that are spatially close
4
should lead to latent features that are close. Using these latent features as goal should induce better
generalization. To obtain the observation encoder, we train an autoencoder with a reconstruction loss
over a Signed Distance Field (SDF) defined on the piano state. Specifically, the encoder compresses
the binary vector of the goal into a latent space, while the decoder predicts the SDF function value
of a randomly sampled query point (the distance between the query point and the closest ”on” piano
key). We provide further details in Appendix E.
Hierarchical Policy. We represent the piano-playing agent with a hierarchical policy. The high-
level policy receives a sequence of desired future piano states ˇ “(and outputs a trajectory of human
fingertip positions x. Then, a low-level policy takes the fingertip and piano state trajectories as
input and outputs a trajectory of desired joint angles q. On one hand, while fingertip trajectory
data is easily available from the Internet, obtaining low-level joint trajectories requires solving a
computationally expensive RL problem. On the other hand, while the high-level mapping ( ˇ “(ÞÑx)
is complex, which involves fingerings, the low-level mapping ( xÞÑq) is relatively simpler, which
addresses a cross-embodiment inverse dynamics problem. This decoupling allows us to train the
more complex high-level mapping on large cheap datasets and the simpler low-level mapping on
smaller expensive ones. We visualize the policy in Figure 2.
Expressive Generative Models. Considering that the human demonstration data of piano playing
is highly multi-modal, we explore using expressive generative models to better represent this multi-
modality. We compare the performance of different deep generative models based policies, e.g.,
Diffusion Policies [22] and Behavioral Transformer [23], as well as a deterministic policy.
4 Experimental Results
We split the experimental evaluation into three parts. In the first part, we explore the performance of
our proposed framework in learning song-specific policies via RL. In the second part, we perform
ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three
methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also results
in a larger discrepancy between the fingertip trajectory of the robot and the human. Thus, the weight
of the style-mimicking reward can be viewed as a parameter that controls the human likeness of the
learned robot actions.
Qualitative comparison. We present a qualitative comparison of the human likeness of the robot
motion in Figure 4 and the attached videos. We inspect the hand poses for certain frames and ob-
serve that the IK nominal behavior leads the robot to place the fingers in positions similar to those in
Youtube videos. The RL policy then slightly adapts the fingertip positions to press the keys correctly.
4.2 Evaluation of model design strategies for policy distillation
This section focuses on the evaluation of policy distillation for playing different songs. We evaluate
the influence of different policy design strategies on the agent’s performance. We aim to assess ( 1)
the impact of integrating a pre-trained observation encoder to induce spatially consistent features,
(2) the impact of a hierarchical design of the policy, and ( 3) the performance of different generative
models on piano-playing data.
6
Multi-RL BC-MSE Two-Stage Diff -res w/o SDF One-Stage BeTTrainP 0.85 0.56 0.87 0.89 0.86 0.53 0.63
R 0.20 0.29 0.78 0.80 0.76 0.34 0.42
F1 0.12 0.30 0.81 0.82 0.78 0.35 0.49TestP 0.95 0.54 0.69 0.71 0.66 0.58 0.53
R 0.18 0.22 0.54 0.55 0.49 0.27 0.30
F1 0.13 0.21 0.56 0.57 0.51 0.26 0.31
Table 1: Quantitative results evaluated on Training and Test Datasets. Test datasets consist of 12
clips unseen in the training dataset. We report Precision (P), Recall (R) and F1-score (F1).
We propose two base policies, Two-stage Diff andTwo-stage Diff-res policy. Both of them utilize
hierarchical policies and goal representation learning, as described in Section 3.3. The only differ-
ence between them is: the low-level policy of Two-stage Diff directly predicts the target joints, while
Two-stage Diff-res predicts the residual term of an IK solver. Both high- and low-level policies
are trained with Denoising Diffusion Probabilistic Models (DDPM) [28]. The high-level policy is
trained to predict the fingertip trajectory for 4 timesteps given the SDF embedding (See Appendix E)
of goals over 10 timesteps, while the low-level policy predicts the robot actions or residuals for 4
timesteps given the fingertip trajectory. Note that the entire dataset is used for training the high-level
policy, while only around 40 % of the collected clips (110K state-action pairs) are trained with RL
and further used for training the low-level policy. The detailed network implementation is described
in Appendix F.
Then, to analyze the impact of each variable, we design four variants of the Two-stage Diffusion
policy. To evaluate ( 1) the impact of integrating a pre-trained observation encoder, we train a model
without the SDF embedding representation for the goal ( w/o SDF ). To evaluate ( 2) the impact of the
hierarchical architecture, we train a One-stage Diffusion policy that directly predict the joint space
actions given the goal. Finally, to evaluate ( 3) the influence of using different generative models, we
train a Two-stage BeT, that replaces Diffusion models with Behavior-Transformers [23]. We also
consider as baselines a Multi-task RL policy and a BCpolicy with MSE Loss. We provide further
details of the models in Appendix G.
Results As shown in Table 1, despite that Multi-task RL has the highest precision on the test dataset
(this is because it barely presses any keys), our methods (Two-stage Diff and Two-stage Diff-res)
outperform the others in all metrics on both training and test datasets. We also observe that the
incorporation of SDF embedding for goal representation leads to better performance, especially
on the test dataset, which demonstrates the impact of goal representation on policy generalization.
Furthermore, we observe a slight performance enhancement when the model predicts the residual
term of IK (Two-stage Diff-res). We speculate that this improvement stems from our training data
being generated through residual RL, which leverages the output of the IK solver as a prior. This
approach likely causes the learned actions to correlate with the outputs of the IK solver.
4.3 Evaluations on the impact of the data in the generalization
In this section, we investigate the impact of scaling training data on the generalization capabilities
of the agent. We evaluate three policy designs ( One-stage Diff ,Two-stage Diff , and Two-stage
Diff-res ). We train them using various proportions of the dataset, and evaluate their performance on
the test dataset (see Figure 5 Top). Note that One-stage Diff uses the same dataset as the low-level
policy of Two-stage Diff.
Results. We observe that both Two-stage Diff and Two-stage Diff-res show consistent performance
improvement with increasing used data. This trend implies that the two-stage policies have not yet
reached their performance saturation with the given data and could potentially continue to benefit
from additional training data in future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. Future works can employ faster diffusion models, e.g., DDIM [29],
to speed up the inference.
Out-of-distribution Data Most of the songs in our collected dataset are of modern style. When
evaluating the model on the dataset from [11], which mainly contains classical songs, the perfor-
mance degrades. This discrepancy implies the model’s limited generalization across songs of differ-
ent styles. Future work can collect more diverse training data to improve this aspect.
Acoustic Experience Although the policy achieves up to 56% F1-score on unseen songs, we found
that higher accuracy is still necessary to make the song acoustically appealing and recognizable.
Future work should focus on improving this accuracy to enhance the overall acoustic experience.
5 Conclusion
In this work, we present PianoMime, a framework for training a generalist robotic pianist using in-
ternet video sources. We start by training song-specific policies with residual RL, enabling the robot
to master individual songs by mimicking human pianists. Subsequently, we train a single behavioral
cloning policy that mimics these song-specific policies to play unseen songs. The policy leverages
three key techniques: goal representation learning, policy hierarchy, and expressive generative mod-
els. The resulting policy demonstrates an impressive generalization capability, achieving an average
F1-score of 70% on unseen songs. This also highlights that leveraging internet data can be highly
useful for training generalist robotic agents.
8
Acknowledgments
If a paper is accepted, the final camera-ready version will (and probably should) include acknowl-
edgments. All acknowledgments go at the end of the paper, including thanks to reviewers who gave
useful comments, to colleagues who contributed to the ideas, and to | Section not found | Section not found | funding agencies and corporate
sponsors that provided financial support.
References
[1] M. V ¨olske, M. Potthast, S. Syed, and B. Stein. Tl; dr: Mining reddit to learn automatic
summarization. In Proceedings of the Workshop on New Frontiers in Summarization , pages
59–63, 2017.
[2] L. Fan, G. Wang, Y . Jiang, A. Mandlekar, Y . Yang, H. Zhu, A. Tang, D.-A. Huang, Y . Zhu,
and A. Anandkumar. Minedojo: Building open-ended embodied agents with internet-scale
knowledge. Advances in Neural Information Processing Systems , 35:18343–18362, 2022.
[3] K. Grauman, A. Westbury, E. Byrne, Z. Chavis, A. Furnari, R. Girdhar, J. Hamburger, H. Jiang,
M. Liu, X. Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition , pages
18995–19012, 2022.
[4] F. Torabi, G. Warnell, and P. Stone. Recent advances in imitation learning from observation.
arXiv preprint arXiv:1905.13566 , 2019.
[5] X. B. Peng, P. Abbeel, S. Levine, and M. Van de Panne. Deepmimic: Example-guided deep re-
inforcement learning of physics-based character skills. ACM Transactions On Graphics (TOG) ,
37(4):1–14, 2018.
[6] G. Garcia-Hernando, E. Johns, and T.-K. Kim. Physics-based dexterous manipulations with
estimated hand poses and residual reinforcement learning. In 2020 IEEE/RSJ International
Conference on Intelligent Robots and Systems (IROS) , pages 9561–9568. IEEE, 2020.
[7] X. B. Peng, E. Coumans, T. Zhang, T.-W. Lee, J. Tan, and S. Levine. Learning agile robotic
locomotion skills by imitating animals. Robotics: Science and Systems (RSS) , 2020.
[8] A. Nair, D. Chen, P. Agrawal, P. Isola, P. Abbeel, J. Malik, and S. Levine. Combining self-
supervised learning and imitation for vision-based rope manipulation. In 2017 IEEE interna-
tional conference on robotics and automation (ICRA) , pages 2146–2153. IEEE, 2017.
[9] L. Shao, T. Migimatsu, Q. Zhang, K. Yang, and J. Bohg. Concept2robot: Learning manip-
ulation concepts from instructions and human demonstrations. The International Journal of
Robotics Research , 40(12-14):1419–1434, 2021.
[10] Y . J. Ma, S. Sodhani, D. Jayaraman, O. Bastani, V . Kumar, and A. Zhang. Vip: Towards
universal visual reward and representation via value-implicit pre-training. arXiv preprint
arXiv:2210.00030 , 2022.
[11] K. Zakka, P. Wu, L. Smith, N. Gileadi, T. Howell, X. B. Peng, S. Singh, Y . Tassa, P. Florence,
A. Zeng, et al. Robopianist: Dexterous piano playing with deep reinforcement learning. In
Conference on Robot Learning , pages 2975–2994. PMLR, 2023.
[12] T. Silver, K. Allen, J. Tenenbaum, and L. Kaelbling. Residual policy learning. arXiv preprint
arXiv:1812.06298 , 2018.
[13] T. Johannink, S. Bahl, A. Nair, J. Luo, A. Kumar, M. Loskyll, J. A. Ojea, E. Solowjow, and
S. Levine. Residual reinforcement learning for robot control. In 2019 international conference
on robotics and automation (ICRA) , pages 6023–6029. IEEE, 2019.
9
[14] B. Scholz. Playing piano with a shadow dexterous hand. PhD thesis, Universitat Hamburg ,
2019.
[15] H. Xu, Y . Luo, S. Wang, T. Darrell, and R. Calandra. Towards learning to play piano with
dexterous hands and touch. In 2022 IEEE/RSJ International Conference on Intelligent Robots
and Systems (IROS) , pages 10410–10416. IEEE, 2022.
[16] T. Geijtenbeek, M. Van De Panne, and A. F. Van Der Stappen. Flexible muscle-based locomo-
tion for bipedal creatures. ACM Transactions on Graphics (TOG) , 32(6):1–11, 2013.
[17] N. Chentanez, M. M ¨uller, M. Macklin, V . Makoviychuk, and S. Jeschke. Physics-based mo-
tion capture imitation with deep reinforcement learning. In Proceedings of the 11th ACM
SIGGRAPH Conference on Motion, Interaction and Games , pages 1–10, 2018.
[18] L. Liu and J. Hodgins. Learning basketball dribbling skills using trajectory optimization and
deep reinforcement learning. ACM Transactions on Graphics (TOG) , 37(4):1–14, 2018.
[19] X. B. Peng, Z. Ma, P. Abbeel, S. Levine, and A. Kanazawa. Amp: Adversarial motion priors
for stylized physics-based character control. ACM Transactions on Graphics (ToG) , 40(4):
1–20, 2021.
[20] C. Lugaresi, J. Tang, H. Nash, C. McClanahan, E. Uboweja, M. Hays, F. Zhang, C.-L. Chang,
M. G. Yong, J. Lee, et al. Mediapipe: A framework for building perception pipelines. arXiv
preprint arXiv:1906.08172 , 2019.
[21] S. Caron, Y . De Mont-Marin, R. Budhiraja, and S. H. Bang. Pink: Python inverse kinematics
based on Pinocchio, 2024. URL https://github.com/stephane-caron/pink .
[22] C. Chi, S. Feng, Y . Du, Z. Xu, E. Cousineau, B. Burchfiel, and S. Song. Diffusion policy:
Visuomotor policy learning via action diffusion. arXiv preprint arXiv:2303.04137 , 2023.
[23] N. M. Shafiullah, Z. Cui, A. A. Altanzaya, and L. Pinto. Behavior transformers: Cloning k
modes with one stone. Advances in neural information processing systems , 35:22955–22968,
2022.
[24] P. Florence, C. Lynch, A. Zeng, O. A. Ramirez, A. Wahid, L. Downs, A. Wong, J. Lee, I. Mor-
datch, and J. Tompson. Implicit behavioral cloning. In Conference on Robot Learning , pages
158–168. PMLR, 2022.
[25] T. Z. Zhao, V . Kumar, S. Levine, and C. Finn. Learning fine-grained bimanual manipulation
with low-cost hardware. arXiv preprint arXiv:2304.13705 , 2023.
[26] E. Todorov, T. Erez, and Y . Tassa. Mujoco: A physics engine for model-based control. In
2012 IEEE/RSJ International Conference on Intelligent Robots and Systems , pages 5026–
5033, 2012. doi:10.1109/IROS.2012.6386109.
[27] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization
algorithms. arXiv preprint arXiv:1707.06347 , 2017.
[28] J. Ho, A. Jain, and P. Abbeel. Denoising diffusion probabilistic models. Advances in neural
information processing systems , 33:6840–6851, 2020.
[29] J. Song, C. Meng, and S. Ermon. Denoising diffusion implicit models. arXiv preprint
arXiv:2010.02502 , 2020.
[30] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
10
[31] D. Hendrycks and K. Gimpel. Gaussian error linear units (gelus). arXiv preprint
arXiv:1606.08415 , 2016.
[32] E. Perez, F. Strub, H. De Vries, V . Dumoulin, and A. Courville. Film: Visual reasoning with
a general conditioning layer. In Proceedings of the AAAI conference on artificial intelligence ,
volume 32, 2018.
[33] T. Haarnoja, A. Zhou, P. Abbeel, and S. Levine. Soft actor-critic: Off-policy maximum entropy
deep reinforcement learning with a stochastic actor. In International conference on machine
learning , pages 1861–1870. PMLR, 2018.
11
𝐻3×3Youtube MujocoFigure 6: Compute homography matrix given 8 correspondence feature points.
A Retargeting: From human hand to robot hand
To retarget from the human hand to robot hand, we follow a structured process.
Step 1: Homography Matrix Computation Given a top-view piano demonstration video, we
firstly choose ndifferent feature points on the piano. These points could be center points of specific
keys, edges, or other identifiable parts of the keys that are easily recognizable (See Figure 6).
Due to the uniform design of pianos, these points represent the same physical positions in both
the video and Mujoco. Given the chosen points, we follow the Eight-point Algorithm to compute
the Homography Matrix Hthat transforms the pixel coordinate in videos to the x-y coordinate in
Mujoco (z-axis is the vertical axis).
Step 2: Transformation of Fingertip Trajectory We then obtain the human fingertip tra-
jectory with MediaPipe [20]. We collect the fingertips positions every 0.05 seconds. Then we
transform the human fingertip trajectory within pixel coordinate into the Mujoco x-y 2D coordinate
using the computed homography matrix H.
Step 3: Heuristic Adjustment for Physical Alignment We found that the transformed fin-
gertip trajectory might not physically align with the notes, which means there might be no detected
fingertip that physically locates at the keys to be pressed or the detected fingertip might locate at the
border of the key (normally human presses the middle point of the horizontal axis of the key). This
misalignment could be due to the inaccuracy of the hand-tracking algorithm and the homography
matrix. Therefore, we perform a simple heuristic adjustment on the trajectory to improve the
physical alignment. Specifically, at each timestep of the video, we check whether there is any
fingertip that physically locates at the key to be pressed. If there is, we adjust its y-axis value to
the middle point of the corresponding key. Otherwise, we search within a small range, specifically
the neighboring two keys, to find the nearest fingertip. If no fingertip is found in the range or
the found fingertip has been assigned to another key to be pressed, we then leave it. Otherwise,
we adjust its y-axis value to the center of the corresponding key to ensure proper physical alignment.
Step 4: Z-axis Value Assignment Lastly, we assign the z-axis value for the fingertips. For
the fingertips that press keys, we set their z-axis values to 0. For other fingertips, we set their z-axis
value to 2¨hkey, where hkeyis the height of the keys in Mujoco.
B Implementation of Inverse Kinematics Solver
The implementation of the IK solver is based on the approach of [21]. The solver addresses multiple
tasks simultaneously by formulating an optimization problem and find the optimal joint velocities
that minimize the objective function. The optimization problem is given by:
min
9qÿ
iwi}Ji9q´Kivi}2, (1)
12
where wiis the weight of each task, Kiis the proportional gain and viis the velocity residual. We
define a set of 10 tasks, each specifying the desired position of one of the robot fingertips. We do not
specify the desired quaternions. All the weights wiare set to be equal. We use quadprog2to solve
the optimization problem with quadratic programming. The other parameters are listed in Table 2.
Table 2: The parameters of IK solver
Parameter Value
Gain 1.0
Limit Gain 0.05
Damping 1e-6
Levenberg-Marquardt Damping 1e-6
C Detailed MDP Formulation of Song-specific Policy
Table 3: The detailed reward function to train the song-specific policy. The Key Press reward is the
same as in [11], where ksandkgrepresent the current and the goal states of the key respectively,
and g is a function that transforms the distances to rewards in the [0, 1] range. pd fandprfrepresent
the fingertip positions of human demonstrator and robot respectively.
Reward Formula Weight Explanation
Key Press 0.5¨gp}ks´kg}2q`0.5¨p1´1false positiveq2/3 Press the right keys and
only the right keys
Mimic gp}pd f´prf}2q 1/3 Mimic the demonstrator’s
fingertip trajectory
Table 4: The observation space of song-specific agent.
Observation Unit Size
Hand and Forearm Joint Positions Rad 52
Hand and forearm Joint Velocities Rad/s 52
Piano Key Joint Positions Rad 88
Piano key Goal State Discrete 88
Demonstrator Forearm and Fingertips Cartesian Positions m 36
Prior control input ˜u(solved by IK) Rad 52
Sustain Pedal state Discrete 1
D Training Details of Song-specific Policy
We use PPO [27] (implemented by StableBaseline 3 [30]) to train the song-specific policy with resid-
ual RL(See Algorithm 1). All of the experiments are conducted using the same network architecture
and tested using 3 different seeds. Both actor and critic networks are of the same architecture, con-
taining 2 MLP hidden layers with 1024 and 256 nodes, respectively, and GELU [31] as activation
functions. The detailed hyperparameters of the networks are listed in Table 7.
2https://github.com/quadprog/quadprog
13
Table 5: The action space of song-specific agent.
Action Unit Size
Target Joint Positions Rad 46
Sustain Pedal Discrete 1
Table 6: The Hyperparameters of PPO
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Exponential Decay
Decay Rate 0.999
Actor Hidden Units 1024, 256
Actor Activation GELU
Critic Hidden Units 1024, 256
Critic Activation GELU
Discount Factor 0.99
Steps per Update 8192
GAE Lambda 0.95
Entropy Coefficient 0.0
Maximum Gradient Norm 0.5
Batch Size 1024
Number of Epochs per Iteration 10
Clip Range 0.2
Number of Iterations 2000
Optimizer Adam
E Representation Learning of Goal
We train an autoencoder to learn a geometrically continuous representation of the goal (See Figure
7 and Algorithm 2). During the training phase, the encoder E, encodes the original 88-dimensional
binary representation of a goal piano state ˇ “(tinto a 16-dimensional latent code z. The positional
encoding of a randomly sampled 3D query coordinate xis then concatenated with the latent code z
and passed through the decoder D. We use positional encoding here to represent the query coordinate
more expressively. The decoder is trained to predict the SDF fpx, ˇ “(tq. We define the SDF value of
xwith respect to ˇ “(tas the Euclidean distance between the xand the nearest key that is supposed to
be pressed in ˇ “(t, mathematically expressed as:
SDFpx, ˇ “(tq“ min
pPtpi| ˇ “(t,i“1u}x´p}, (2)
where pirepresents the position of the i-th key on the piano. The encoder and decoder are jointly
optimized to minimize the reconstruction loss:
Lpx, , ˇ “(tq“p SDFpx, ˇ “(tq´DpEpv, xqqq2. (3)
We pre-train the autoencoder using the GiantMIDI dataset3, which contains 10K piano MIDI files
of 2,786 composers. The pre-trained encoder maps the ˇ “(tinto the 16-dimensional latent code,
which serves as the latent goal for behavioral cloning. The encoder network is composed of four
3https://github.com/bytedance/GiantMIDI-Piano
14
Algorithm 1: Training of the song-specific policy with residual RL
1:Initialize actor network πθ
2:Initialize critic network vϕ
3:fori“1 :Niteration do
4: # Collect trajectories
5: fort“1 :Tdo
6: Get human demonstrator fingertip position xtand observation ot
7: Compute the prior control signal that tracks xtwith the IK controller ˜ut“ikpxt, otq
8: Run policy to get the residual term rt“πθpotq
9: Compute the adapted control signal ut“˜ut`rt
10: Execute utin environment and collect st, ut, rt, st`1
11: end for
12: # Update networks
13: forn“1 :Ndo
14: Sample a batch of transitions tpsj, uj, rj, sj`1qufrom the collected trajectories
15: Update the actor and critic network with PPO
16: end for
17:end for
Query
Coordinate
Positional
Embedding
SDF Encoder
...1
0
10
188-dimensional
binary vector
Latent
Code+
Figure 7: 1) Encoding: The encoder compresses the binary representation of the goal into latent
code. 2) Decoding: A 3D query coordinate xis randomly sampled. A neural network predicts the
SDF value given the positional encoding of xand the latent code.
1D-convolutional layers, followed by a linear layer. Each successive 1D-convolutional layer has an
increasing number of filters, specifically 2, 4, 8, and 16 filters, respectively. All convolutional layers
utilize a kernel size of 3. The linear layer transforms the flattened output from the convolutional
layers into a 16-dimensional latent code. The decoder network is a MLP with 2 hidden layers, each
with 16 neurons. We train the autoencoder for 100 epochs with a learning rate of 1e´3.
F Training Details of Diffusion Model
All the diffusion models utilized in this work, including One-stage Diff, the high-level and
low-level policies of Two-stage Diff, Two-stage Diff-res and Two-stage Diff w/o SDF, share
15
Algorithm 2: Training of the goal autoencoder
1:Initialize encoder Eϕ
2:Initialize decoder Dψ
3:fori“1 :Nepoch do
4: forj“1 :Nbatch do
5: foreach goal vin batch do
6: Compute the latent code z“Eψp ˇ “(tq
7: Sample a 3D coordinate as query x“Sample3DCoordinate()
8: Compute the positional encoding of query pe“PositionalEncoding( xq
9: Compute the output of the decoder conditioned by the query Dϕpz, peq
10: Compute the SDF value of query SDF px, ˇ “(tq
11: Compute the reconstruction loss L
12: end for
13: Compute the sum of the loss
14: Compute the gradient
15: Update network parameter ϕ, ψ
16: end for
17:end for
the same network architecture. The network architecture are the same as the U-net diffusion
policy in [22] and optimized with DDPM [28], except that we use temporal convolutional net-
works (TCNs) as the observation encoder, taking the concatenated goals (high-level policy) or
fingertip positions (low-level policy) of several timesteps as input to extract the features on tem-
poral dimension. Each level of U-net is then conditioned by the outputs of TCNs through FiLM [32].
High-level policies take the goals over 10 timesteps and the current fingertip position as in-
put and predict the human fingertip positions. In addition, we add a standard gaussian noise on the
current fingertip position during training to facilitate generalization. We further adjust the y-axis
value of the fingertips pressing the keys in the predicted high-level trajectories to the midpoint
of the keys. This adjustment ensures closer alignment with the data distribution of the training
dataset. Low-level policies take the predicted fingertip positions and the goals over 4 timesteps, the
proprioception state as input predict the robot actions. The proprioception state includes the robot
joint positions and velocities, as well as the piano joint positions. We use 100 diffusion steps during
training. To achieve high-quality results during inference, we find that at least 80 diffusion steps are
required for high-level policies and 50 steps for low-level policies.
Table 7: The Hyperparameters of DDPM
Hyperparameter Value
Initial Learning Rate 1e-4
Learning Rate Scheduler Cosine
U-Net Filters Number 256, 512, 1024
U-Net Kernel Size 5
TCN Filters Number 32, 64
TCN Kernel Size 3
Diffusion Steps Number 100
Batch Size 256
Number of Iterations 800
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
16
G Policy Distillation Experiment
Two-stage Diff w/o SDF We directly use the binary representation of goal instead of the SDF
embedding representation to condition the high-level and low-level policies.
Two-stage Diff-res We employ an IK solver to compute the target joints given the fingertip
positions predicted by the high-level policy. The low-level policy predicts the residual terms of IK
solver instead of the robot actions.
Two-stage BeT We train both high-level and low-level policies with Behavior Transformer
[23] instead of DDPM. The hyperparameter of Bet is listed in Table 8.
One-stage Diff We train a single diffusion model to predict the robot actions given the SDF
embedding representation of goals and the proprioception state.
Multi-task RL We create a multi-task environment where for each episode a random song is
sampled from the dataset. Consequently, we use Soft-Actor-Critic (SAC) [33] to train a single agent
within the environment. Both the actor and critic networks are MLPs, each with 3 hidden layers,
and each hidden layer contains 256 neurons. The reward function is the same as that in [11].
BC-MSE We train a feedforward network to predict the robot action of next timestep con-
ditioned on the binary representation of goal and proprioception state with MSE loss. The
feedforward network is a MLP with 3 hidden layers, each with 1024 neurons.
Table 8: The Hyperparameters of Behavior Transformer
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Cosine
Number of Discretization Bins 64
Number of Transformer Heads 8
Number of Transformer Layers 8
Embedding Dimension 120
Batch Size 256
Number of Iterations 1200
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
H F1 Score of All Trained Song-Specific Policies
Figure 8 shows the F1 score of all song-specific policies we trained.
I Detailed Results on Test Dataset
In Table 9 and Table 10, we show the Precision, Recall and F1 score of each song in our collected
test dataset and the Etude-12 dataset from [11], achieved by Two-stage Diff and Two-stage Diff-res,
respectively. We observe an obvious performance degradation when testing on Etude-12 dataset.
We suspect that the reason is due to out-of-distribution data, as the songs in the Etude-12 dataset are
all classical, whereas our training and test dataset primarily consists of modern songs.
17
Table 9: Quantitative results of each song in the our collected test dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
Forester 0.81 0.70 0.68 0.79 0.71 0.67
Wednesday 0.66 0.57 0.58 0.67 0.54 0.55
Alone 0.80 0.62 0.66 0.83 0.65 0.67
Somewhere Only We Know 0.63 0.53 0.58 0.67 0.57 0.59
Eyes Closed 0.60 0.52 0.53 0.61 0.45 0.50
Pedro 0.70 0.58 0.60 0.67 0.56 0.47
Ohne Dich 0.73 0.55 0.58 0.75 0.56 0.62
Paradise 0.66 0.42 0.43 0.68 0.45 0.47
Hope 0.74 0.55 0.57 0.76 0.58 0.62
No Time To Die 0.77 0.53 0.55 0.79 0.57 0.60
The Spectre 0.64 0.52 0.54 0.67 0.50 0.52
Numb 0.55 0.44 0.45 0.57 0.47 0.48
Mean 0.69 0.54 0.56 0.71 0.55 0.57
Table 10: Quantitative results of each song in the Etude-12 dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
FrenchSuiteNo1Allemande 0.45 0.31 0.34 0.39 0.27 0.30
FrenchSuiteNo5Sarabande 0.29 0.23 0.24 0.24 0.18 0.19
PianoSonataD8451StMov 0.58 0.52 0.52 0.60 0.50 0.51
PartitaNo26 0.35 0.22 0.24 0.40 0.24 0.26
WaltzOp64No1 0.44 0.31 0.33 0.43 0.28 0.31
BagatelleOp3No4 0.45 0.30 0.33 0.45 0.28 0.32
KreislerianaOp16No8 0.43 0.34 0.36 0.49 0.34 0.36
FrenchSuiteNo5Gavotte 0.34 0.29 0.33 0.41 0.31 0.33
PianoSonataNo232NdMov 0.35 0.24 0.25 0.29 0.19 0.21
GolliwoggsCakewalk 0.60 0.43 0.45 0.57 0.40 0.42
PianoSonataNo21StMov 0.32 0.22 0.25 0.36 0.23 0.25
PianoSonataK279InCMajor1StMov 0.43 0.35 0.35 0.53 0.38 0.39
Mean 0.42 0.31 0.33 0.43 0.30 0.32
18
Figure 8: F1 score of all 184 trained song-specific policies (descending order)
19 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three
methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also results
in a larger discrepancy between the fingertip trajectory of the robot and the human. Thus, the weight
of the style-mimicking reward can be viewed as a parameter that controls the human likeness of the
learned robot actions.
Qualitative comparison. We present a qualitative comparison of the human likeness of the robot
motion in Figure 4 and the attached videos. We inspect the hand poses for certain frames and ob-
serve that the IK nominal behavior leads the robot to place the fingers in positions similar to those in
Youtube videos. The RL policy then slightly adapts the fingertip positions to press the keys correctly.
4.2 Evaluation of model design strategies for policy distillation
This section focuses on the evaluation of policy distillation for playing different songs. We evaluate
the influence of different policy design strategies on the agent’s performance. We aim to assess ( 1)
the impact of integrating a pre-trained observation encoder to induce spatially consistent features,
(2) the impact of a hierarchical design of the policy, and ( 3) the performance of different generative
models on piano-playing data.
6
Multi-RL BC-MSE Two-Stage Diff -res w/o SDF One-Stage BeTTrainP 0.85 0.56 0.87 0.89 0.86 0.53 0.63
R 0.20 0.29 0.78 0.80 0.76 0.34 0.42
F1 0.12 0.30 0.81 0.82 0.78 0.35 0.49TestP 0.95 0.54 0.69 0.71 0.66 0.58 0.53
R 0.18 0.22 0.54 0.55 0.49 0.27 0.30
F1 0.13 0.21 0.56 0.57 0.51 0.26 0.31
Table 1: Quantitative results evaluated on Training and Test Datasets. Test datasets consist of 12
clips unseen in the training dataset. We report Precision (P), Recall (R) and F1-score (F1).
We propose two base policies, Two-stage Diff andTwo-stage Diff-res policy. Both of them utilize
hierarchical policies and goal representation learning, as described in Section 3.3. The only differ-
ence between them is: the low-level policy of Two-stage Diff directly predicts the target joints, while
Two-stage Diff-res predicts the residual term of an IK solver. Both high- and low-level policies
are trained with Denoising Diffusion Probabilistic Models (DDPM) [28]. The high-level policy is
trained to predict the fingertip trajectory for 4 timesteps given the SDF embedding (See Appendix E)
of goals over 10 timesteps, while the low-level policy predicts the robot actions or residuals for 4
timesteps given the fingertip trajectory. Note that the entire dataset is used for training the high-level
policy, while only around 40 % of the collected clips (110K state-action pairs) are trained with RL
and further used for training the low-level policy. The detailed network implementation is described
in Appendix F.
Then, to analyze the impact of each variable, we design four variants of the Two-stage Diffusion
policy. To evaluate ( 1) the impact of integrating a pre-trained observation encoder, we train a model
without the SDF embedding representation for the goal ( w/o SDF ). To evaluate ( 2) the impact of the
hierarchical architecture, we train a One-stage Diffusion policy that directly predict the joint space
actions given the goal. Finally, to evaluate ( 3) the influence of using different generative models, we
train a Two-stage BeT, that replaces Diffusion models with Behavior-Transformers [23]. We also
consider as baselines a Multi-task RL policy and a BCpolicy with MSE Loss. We provide further
details of the models in Appendix G.
Results As shown in Table 1, despite that Multi-task RL has the highest precision on the test dataset
(this is because it barely presses any keys), our methods (Two-stage Diff and Two-stage Diff-res)
outperform the others in all metrics on both training and test datasets. We also observe that the
incorporation of SDF embedding for goal representation leads to better performance, especially
on the test dataset, which demonstrates the impact of goal representation on policy generalization.
Furthermore, we observe a slight performance enhancement when the model predicts the residual
term of IK (Two-stage Diff-res). We speculate that this improvement stems from our training data
being generated through residual RL, which leverages the output of the IK solver as a prior. This
approach likely causes the learned actions to correlate with the outputs of the IK solver.
4.3 Evaluations on the impact of the data in the generalization
In this section, we investigate the impact of scaling training data on the generalization capabilities
of the agent. We evaluate three policy designs ( One-stage Diff ,Two-stage Diff , and Two-stage
Diff-res ). We train them using various proportions of the dataset, and evaluate their performance on
the test dataset (see Figure 5 Top). Note that One-stage Diff uses the same dataset as the low-level
policy of Two-stage Diff.
Results. We observe that both Two-stage Diff and Two-stage Diff-res show consistent performance
improvement with increasing used data. This trend implies that the two-stage policies have not yet
reached their performance saturation with the given data and could potentially continue to benefit
from additional training data in future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. Future works can employ faster diffusion models, e.g., DDIM [29],
to speed up the inference.
Out-of-distribution Data Most of the songs in our collected dataset are of modern style. When
evaluating the model on the dataset from [11], which mainly contains classical songs, the perfor-
mance degrades. This discrepancy implies the model’s limited generalization across songs of differ-
ent styles. Future work can collect more diverse training data to improve this aspect.
Acoustic Experience Although the policy achieves up to 56% F1-score on unseen songs, we found
that higher accuracy is still necessary to make the song acoustically appealing and recognizable.
Future work should focus on improving this accuracy to enhance the overall acoustic experience.
5 Conclusion
In this work, we present PianoMime, a framework for training a generalist robotic pianist using in-
ternet video sources. We start by training song-specific policies with residual RL, enabling the robot
to master individual songs by mimicking human pianists. Subsequently, we train a single behavioral
cloning policy that mimics these song-specific policies to play unseen songs. The policy leverages
three key techniques: goal representation learning, policy hierarchy, and expressive generative mod-
els. The resulting policy demonstrates an impressive generalization capability, achieving an average
F1-score of 70% on unseen songs. This also highlights that leveraging internet data can be highly
useful for training generalist robotic agents.
8
Acknowledgments
If a paper is accepted, the final camera-ready version will (and probably should) include acknowl-
edgments. All acknowledgments go at the end of the paper, including thanks to reviewers who gave
useful comments, to colleagues who contributed to the ideas, and to funding agencies and corporate
sponsors that provided financial support.
References
[1] M. V ¨olske, M. Potthast, S. Syed, and B. Stein. Tl; dr: Mining reddit to learn automatic
summarization. In Proceedings of the Workshop on New Frontiers in Summarization , pages
59–63, 2017.
[2] L. Fan, G. Wang, Y . Jiang, A. Mandlekar, Y . Yang, H. Zhu, A. Tang, D.-A. Huang, Y . Zhu,
and A. Anandkumar. Minedojo: Building open-ended embodied agents with internet-scale
knowledge. Advances in Neural Information Processing Systems , 35:18343–18362, 2022.
[3] K. Grauman, A. Westbury, E. Byrne, Z. Chavis, A. Furnari, R. Girdhar, J. Hamburger, H. Jiang,
M. Liu, X. Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition , pages
18995–19012, 2022.
[4] F. Torabi, G. Warnell, and P. Stone. Recent advances in imitation learning from observation.
arXiv preprint arXiv:1905.13566 , 2019.
[5] X. B. Peng, P. Abbeel, S. Levine, and M. Van de Panne. Deepmimic: Example-guided deep re-
inforcement learning of physics-based character skills. ACM Transactions On Graphics (TOG) ,
37(4):1–14, 2018.
[6] G. Garcia-Hernando, E. Johns, and T.-K. Kim. Physics-based dexterous manipulations with
estimated hand poses and residual reinforcement learning. In 2020 IEEE/RSJ International
Conference on Intelligent Robots and Systems (IROS) , pages 9561–9568. IEEE, 2020.
[7] X. B. Peng, E. Coumans, T. Zhang, T.-W. Lee, J. Tan, and S. Levine. Learning agile robotic
locomotion skills by imitating animals. Robotics: Science and Systems (RSS) , 2020.
[8] A. Nair, D. Chen, P. Agrawal, P. Isola, P. Abbeel, J. Malik, and S. Levine. Combining self-
supervised learning and imitation for vision-based rope manipulation. In 2017 IEEE interna-
tional conference on robotics and automation (ICRA) , pages 2146–2153. IEEE, 2017.
[9] L. Shao, T. Migimatsu, Q. Zhang, K. Yang, and J. Bohg. Concept2robot: Learning manip-
ulation concepts from instructions and human demonstrations. The International Journal of
Robotics Research , 40(12-14):1419–1434, 2021.
[10] Y . J. Ma, S. Sodhani, D. Jayaraman, O. Bastani, V . Kumar, and A. Zhang. Vip: Towards
universal visual reward and representation via value-implicit pre-training. arXiv preprint
arXiv:2210.00030 , 2022.
[11] K. Zakka, P. Wu, L. Smith, N. Gileadi, T. Howell, X. B. Peng, S. Singh, Y . Tassa, P. Florence,
A. Zeng, et al. Robopianist: Dexterous piano playing with deep reinforcement learning. In
Conference on Robot Learning , pages 2975–2994. PMLR, 2023.
[12] T. Silver, K. Allen, J. Tenenbaum, and L. Kaelbling. Residual policy learning. arXiv preprint
arXiv:1812.06298 , 2018.
[13] T. Johannink, S. Bahl, A. Nair, J. Luo, A. Kumar, M. Loskyll, J. A. Ojea, E. Solowjow, and
S. Levine. Residual reinforcement learning for robot control. In 2019 international conference
on robotics and automation (ICRA) , pages 6023–6029. IEEE, 2019.
9
[14] B. Scholz. Playing piano with a shadow dexterous hand. PhD thesis, Universitat Hamburg ,
2019.
[15] H. Xu, Y . Luo, S. Wang, T. Darrell, and R. Calandra. Towards learning to play piano with
dexterous hands and touch. In 2022 IEEE/RSJ International Conference on Intelligent Robots
and Systems (IROS) , pages 10410–10416. IEEE, 2022.
[16] T. Geijtenbeek, M. Van De Panne, and A. F. Van Der Stappen. Flexible muscle-based locomo-
tion for bipedal creatures. ACM Transactions on Graphics (TOG) , 32(6):1–11, 2013.
[17] N. Chentanez, M. M ¨uller, M. Macklin, V . Makoviychuk, and S. Jeschke. Physics-based mo-
tion capture imitation with deep reinforcement learning. In Proceedings of the 11th ACM
SIGGRAPH Conference on Motion, Interaction and Games , pages 1–10, 2018.
[18] L. Liu and J. Hodgins. Learning basketball dribbling skills using trajectory optimization and
deep reinforcement learning. ACM Transactions on Graphics (TOG) , 37(4):1–14, 2018.
[19] X. B. Peng, Z. Ma, P. Abbeel, S. Levine, and A. Kanazawa. Amp: Adversarial motion priors
for stylized physics-based character control. ACM Transactions on Graphics (ToG) , 40(4):
1–20, 2021.
[20] C. Lugaresi, J. Tang, H. Nash, C. McClanahan, E. Uboweja, M. Hays, F. Zhang, C.-L. Chang,
M. G. Yong, J. Lee, et al. Mediapipe: A framework for building perception pipelines. arXiv
preprint arXiv:1906.08172 , 2019.
[21] S. Caron, Y . De Mont-Marin, R. Budhiraja, and S. H. Bang. Pink: Python inverse kinematics
based on Pinocchio, 2024. URL https://github.com/stephane-caron/pink .
[22] C. Chi, S. Feng, Y . Du, Z. Xu, E. Cousineau, B. Burchfiel, and S. Song. Diffusion policy:
Visuomotor policy learning via action diffusion. arXiv preprint arXiv:2303.04137 , 2023.
[23] N. M. Shafiullah, Z. Cui, A. A. Altanzaya, and L. Pinto. Behavior transformers: Cloning k
modes with one stone. Advances in neural information processing systems , 35:22955–22968,
2022.
[24] P. Florence, C. Lynch, A. Zeng, O. A. Ramirez, A. Wahid, L. Downs, A. Wong, J. Lee, I. Mor-
datch, and J. Tompson. Implicit behavioral cloning. In Conference on Robot Learning , pages
158–168. PMLR, 2022.
[25] T. Z. Zhao, V . Kumar, S. Levine, and C. Finn. Learning fine-grained bimanual manipulation
with low-cost hardware. arXiv preprint arXiv:2304.13705 , 2023.
[26] E. Todorov, T. Erez, and Y . Tassa. Mujoco: A physics engine for model-based control. In
2012 IEEE/RSJ International Conference on Intelligent Robots and Systems , pages 5026–
5033, 2012. doi:10.1109/IROS.2012.6386109.
[27] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization
algorithms. arXiv preprint arXiv:1707.06347 , 2017.
[28] J. Ho, A. Jain, and P. Abbeel. Denoising diffusion probabilistic models. Advances in neural
information processing systems , 33:6840–6851, 2020.
[29] J. Song, C. Meng, and S. Ermon. Denoising diffusion implicit models. arXiv preprint
arXiv:2010.02502 , 2020.
[30] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
10
[31] D. Hendrycks and K. Gimpel. Gaussian error linear units (gelus). arXiv preprint
arXiv:1606.08415 , 2016.
[32] E. Perez, F. Strub, H. De Vries, V . Dumoulin, and A. Courville. Film: Visual reasoning with
a general conditioning layer. In Proceedings of the AAAI conference on artificial intelligence ,
volume 32, 2018.
[33] T. Haarnoja, A. Zhou, P. Abbeel, and S. Levine. Soft actor-critic: Off-policy maximum entropy
deep reinforcement learning with a stochastic actor. In International conference on machine
learning , pages 1861–1870. PMLR, 2018.
11
𝐻3×3Youtube MujocoFigure 6: Compute homography matrix given 8 correspondence feature points.
A Retargeting: From human hand to robot hand
To retarget from the human hand to robot hand, we follow a structured process.
Step 1: Homography Matrix Computation Given a top-view piano demonstration video, we
firstly choose ndifferent feature points on the piano. These points could be center points of specific
keys, edges, or other identifiable parts of the keys that are easily recognizable (See Figure 6).
Due to the uniform design of pianos, these points represent the same physical positions in both
the video and Mujoco. Given the chosen points, we follow the Eight-point Algorithm to compute
the Homography Matrix Hthat transforms the pixel coordinate in videos to the x-y coordinate in
Mujoco (z-axis is the vertical axis).
Step 2: Transformation of Fingertip Trajectory We then obtain the human fingertip tra-
jectory with MediaPipe [20]. We collect the fingertips positions every 0.05 seconds. Then we
transform the human fingertip trajectory within pixel coordinate into the Mujoco x-y 2D coordinate
using the computed homography matrix H.
Step 3: Heuristic Adjustment for Physical Alignment We found that the transformed fin-
gertip trajectory might not physically align with the notes, which means there might be no detected
fingertip that physically locates at the keys to be pressed or the detected fingertip might locate at the
border of the key (normally human presses the middle point of the horizontal axis of the key). This
misalignment could be due to the inaccuracy of the hand-tracking algorithm and the homography
matrix. Therefore, we perform a simple heuristic adjustment on the trajectory to improve the
physical alignment. Specifically, at each timestep of the video, we check whether there is any
fingertip that physically locates at the key to be pressed. If there is, we adjust its y-axis value to
the middle point of the corresponding key. Otherwise, we search within a small range, specifically
the neighboring two keys, to find the nearest fingertip. If no fingertip is found in the range or
the found fingertip has been assigned to another key to be pressed, we then leave it. Otherwise,
we adjust its y-axis value to the center of the corresponding key to ensure proper physical alignment.
Step 4: Z-axis Value Assignment Lastly, we assign the z-axis value for the fingertips. For
the fingertips that press keys, we set their z-axis values to 0. For other fingertips, we set their z-axis
value to 2¨hkey, where hkeyis the height of the keys in Mujoco.
B Implementation of Inverse Kinematics Solver
The implementation of the IK solver is based on the approach of [21]. The solver addresses multiple
tasks simultaneously by formulating an optimization problem and find the optimal joint velocities
that minimize the objective function. The optimization problem is given by:
min
9qÿ
iwi}Ji9q´Kivi}2, (1)
12
where wiis the weight of each task, Kiis the proportional gain and viis the velocity residual. We
define a set of 10 tasks, each specifying the desired position of one of the robot fingertips. We do not
specify the desired quaternions. All the weights wiare set to be equal. We use quadprog2to solve
the optimization problem with quadratic programming. The other parameters are listed in Table 2.
Table 2: The parameters of IK solver
Parameter Value
Gain 1.0
Limit Gain 0.05
Damping 1e-6
Levenberg-Marquardt Damping 1e-6
C Detailed MDP Formulation of Song-specific Policy
Table 3: The detailed reward function to train the song-specific policy. The Key Press reward is the
same as in [11], where ksandkgrepresent the current and the goal states of the key respectively,
and g is a function that transforms the distances to rewards in the [0, 1] range. pd fandprfrepresent
the fingertip positions of human demonstrator and robot respectively.
Reward Formula Weight Explanation
Key Press 0.5¨gp}ks´kg}2q`0.5¨p1´1false positiveq2/3 Press the right keys and
only the right keys
Mimic gp}pd f´prf}2q 1/3 Mimic the demonstrator’s
fingertip trajectory
Table 4: The observation space of song-specific agent.
Observation Unit Size
Hand and Forearm Joint Positions Rad 52
Hand and forearm Joint Velocities Rad/s 52
Piano Key Joint Positions Rad 88
Piano key Goal State Discrete 88
Demonstrator Forearm and Fingertips Cartesian Positions m 36
Prior control input ˜u(solved by IK) Rad 52
Sustain Pedal state Discrete 1
D Training Details of Song-specific Policy
We use PPO [27] (implemented by StableBaseline 3 [30]) to train the song-specific policy with resid-
ual RL(See Algorithm 1). All of the experiments are conducted using the same network architecture
and tested using 3 different seeds. Both actor and critic networks are of the same architecture, con-
taining 2 MLP hidden layers with 1024 and 256 nodes, respectively, and GELU [31] as activation
functions. The detailed hyperparameters of the networks are listed in Table 7.
2https://github.com/quadprog/quadprog
13
Table 5: The action space of song-specific agent.
Action Unit Size
Target Joint Positions Rad 46
Sustain Pedal Discrete 1
Table 6: The Hyperparameters of PPO
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Exponential Decay
Decay Rate 0.999
Actor Hidden Units 1024, 256
Actor Activation GELU
Critic Hidden Units 1024, 256
Critic Activation GELU
Discount Factor 0.99
Steps per Update 8192
GAE Lambda 0.95
Entropy Coefficient 0.0
Maximum Gradient Norm 0.5
Batch Size 1024
Number of Epochs per Iteration 10
Clip Range 0.2
Number of Iterations 2000
Optimizer Adam
E Representation Learning of Goal
We train an autoencoder to learn a geometrically continuous representation of the goal (See Figure
7 and Algorithm 2). During the training phase, the encoder E, encodes the original 88-dimensional
binary representation of a goal piano state ˇ “(tinto a 16-dimensional latent code z. The positional
encoding of a randomly sampled 3D query coordinate xis then concatenated with the latent code z
and passed through the decoder D. We use positional encoding here to represent the query coordinate
more expressively. The decoder is trained to predict the SDF fpx, ˇ “(tq. We define the SDF value of
xwith respect to ˇ “(tas the Euclidean distance between the xand the nearest key that is supposed to
be pressed in ˇ “(t, mathematically expressed as:
SDFpx, ˇ “(tq“ min
pPtpi| ˇ “(t,i“1u}x´p}, (2)
where pirepresents the position of the i-th key on the piano. The encoder and decoder are jointly
optimized to minimize the reconstruction loss:
Lpx, , ˇ “(tq“p SDFpx, ˇ “(tq´DpEpv, xqqq2. (3)
We pre-train the autoencoder using the GiantMIDI dataset3, which contains 10K piano MIDI files
of 2,786 composers. The pre-trained encoder maps the ˇ “(tinto the 16-dimensional latent code,
which serves as the latent goal for behavioral cloning. The encoder network is composed of four
3https://github.com/bytedance/GiantMIDI-Piano
14
Algorithm 1: Training of the song-specific policy with residual RL
1:Initialize actor network πθ
2:Initialize critic network vϕ
3:fori“1 :Niteration do
4: # Collect trajectories
5: fort“1 :Tdo
6: Get human demonstrator fingertip position xtand observation ot
7: Compute the prior control signal that tracks xtwith the IK controller ˜ut“ikpxt, otq
8: Run policy to get the residual term rt“πθpotq
9: Compute the adapted control signal ut“˜ut`rt
10: Execute utin environment and collect st, ut, rt, st`1
11: end for
12: # Update networks
13: forn“1 :Ndo
14: Sample a batch of transitions tpsj, uj, rj, sj`1qufrom the collected trajectories
15: Update the actor and critic network with PPO
16: end for
17:end for
Query
Coordinate
Positional
Embedding
SDF Encoder
...1
0
10
188-dimensional
binary vector
Latent
Code+
Figure 7: 1) Encoding: The encoder compresses the binary representation of the goal into latent
code. 2) Decoding: A 3D query coordinate xis randomly sampled. A neural network predicts the
SDF value given the positional encoding of xand the latent code.
1D-convolutional layers, followed by a linear layer. Each successive 1D-convolutional layer has an
increasing number of filters, specifically 2, 4, 8, and 16 filters, respectively. All convolutional layers
utilize a kernel size of 3. The linear layer transforms the flattened output from the convolutional
layers into a 16-dimensional latent code. The decoder network is a MLP with 2 hidden layers, each
with 16 neurons. We train the autoencoder for 100 epochs with a learning rate of 1e´3.
F Training Details of Diffusion Model
All the diffusion models utilized in this work, including One-stage Diff, the high-level and
low-level policies of Two-stage Diff, Two-stage Diff-res and Two-stage Diff w/o SDF, share
15
Algorithm 2: Training of the goal autoencoder
1:Initialize encoder Eϕ
2:Initialize decoder Dψ
3:fori“1 :Nepoch do
4: forj“1 :Nbatch do
5: foreach goal vin batch do
6: Compute the latent code z“Eψp ˇ “(tq
7: Sample a 3D coordinate as query x“Sample3DCoordinate()
8: Compute the positional encoding of query pe“PositionalEncoding( xq
9: Compute the output of the decoder conditioned by the query Dϕpz, peq
10: Compute the SDF value of query SDF px, ˇ “(tq
11: Compute the reconstruction loss L
12: end for
13: Compute the sum of the loss
14: Compute the gradient
15: Update network parameter ϕ, ψ
16: end for
17:end for
the same network architecture. The network architecture are the same as the U-net diffusion
policy in [22] and optimized with DDPM [28], except that we use temporal convolutional net-
works (TCNs) as the observation encoder, taking the concatenated goals (high-level policy) or
fingertip positions (low-level policy) of several timesteps as input to extract the features on tem-
poral dimension. Each level of U-net is then conditioned by the outputs of TCNs through FiLM [32].
High-level policies take the goals over 10 timesteps and the current fingertip position as in-
put and predict the human fingertip positions. In addition, we add a standard gaussian noise on the
current fingertip position during training to facilitate generalization. We further adjust the y-axis
value of the fingertips pressing the keys in the predicted high-level trajectories to the midpoint
of the keys. This adjustment ensures closer alignment with the data distribution of the training
dataset. Low-level policies take the predicted fingertip positions and the goals over 4 timesteps, the
proprioception state as input predict the robot actions. The proprioception state includes the robot
joint positions and velocities, as well as the piano joint positions. We use 100 diffusion steps during
training. To achieve high-quality results during inference, we find that at least 80 diffusion steps are
required for high-level policies and 50 steps for low-level policies.
Table 7: The Hyperparameters of DDPM
Hyperparameter Value
Initial Learning Rate 1e-4
Learning Rate Scheduler Cosine
U-Net Filters Number 256, 512, 1024
U-Net Kernel Size 5
TCN Filters Number 32, 64
TCN Kernel Size 3
Diffusion Steps Number 100
Batch Size 256
Number of Iterations 800
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
16
G Policy Distillation Experiment
Two-stage Diff w/o SDF We directly use the binary representation of goal instead of the SDF
embedding representation to condition the high-level and low-level policies.
Two-stage Diff-res We employ an IK solver to compute the target joints given the fingertip
positions predicted by the high-level policy. The low-level policy predicts the residual terms of IK
solver instead of the robot actions.
Two-stage BeT We train both high-level and low-level policies with Behavior Transformer
[23] instead of DDPM. The hyperparameter of Bet is listed in Table 8.
One-stage Diff We train a single diffusion model to predict the robot actions given the SDF
embedding representation of goals and the proprioception state.
Multi-task RL We create a multi-task environment where for each episode a random song is
sampled from the dataset. Consequently, we use Soft-Actor-Critic (SAC) [33] to train a single agent
within the environment. Both the actor and critic networks are MLPs, each with 3 hidden layers,
and each hidden layer contains 256 neurons. The reward function is the same as that in [11].
BC-MSE We train a feedforward network to predict the robot action of next timestep con-
ditioned on the binary representation of goal and proprioception state with MSE loss. The
feedforward network is a MLP with 3 hidden layers, each with 1024 neurons.
Table 8: The Hyperparameters of Behavior Transformer
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Cosine
Number of Discretization Bins 64
Number of Transformer Heads 8
Number of Transformer Layers 8
Embedding Dimension 120
Batch Size 256
Number of Iterations 1200
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
H F1 Score of All Trained Song-Specific Policies
Figure 8 shows the F1 score of all song-specific policies we trained.
I Detailed Results on Test Dataset
In Table 9 and Table 10, we show the Precision, Recall and F1 score of each song in our collected
test dataset and the Etude-12 dataset from [11], achieved by Two-stage Diff and Two-stage Diff-res,
respectively. We observe an obvious performance degradation when testing on Etude-12 dataset.
We suspect that the reason is due to out-of-distribution data, as the songs in the Etude-12 dataset are
all classical, whereas our training and test dataset primarily consists of modern songs.
17
Table 9: Quantitative results of each song in the our collected test dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
Forester 0.81 0.70 0.68 0.79 0.71 0.67
Wednesday 0.66 0.57 0.58 0.67 0.54 0.55
Alone 0.80 0.62 0.66 0.83 0.65 0.67
Somewhere Only We Know 0.63 0.53 0.58 0.67 0.57 0.59
Eyes Closed 0.60 0.52 0.53 0.61 0.45 0.50
Pedro 0.70 0.58 0.60 0.67 0.56 0.47
Ohne Dich 0.73 0.55 0.58 0.75 0.56 0.62
Paradise 0.66 0.42 0.43 0.68 0.45 0.47
Hope 0.74 0.55 0.57 0.76 0.58 0.62
No Time To Die 0.77 0.53 0.55 0.79 0.57 0.60
The Spectre 0.64 0.52 0.54 0.67 0.50 0.52
Numb 0.55 0.44 0.45 0.57 0.47 0.48
Mean 0.69 0.54 0.56 0.71 0.55 0.57
Table 10: Quantitative results of each song in the Etude-12 dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
FrenchSuiteNo1Allemande 0.45 0.31 0.34 0.39 0.27 0.30
FrenchSuiteNo5Sarabande 0.29 0.23 0.24 0.24 0.18 0.19
PianoSonataD8451StMov 0.58 0.52 0.52 0.60 0.50 0.51
PartitaNo26 0.35 0.22 0.24 0.40 0.24 0.26
WaltzOp64No1 0.44 0.31 0.33 0.43 0.28 0.31
BagatelleOp3No4 0.45 0.30 0.33 0.45 0.28 0.32
KreislerianaOp16No8 0.43 0.34 0.36 0.49 0.34 0.36
FrenchSuiteNo5Gavotte 0.34 0.29 0.33 0.41 0.31 0.33
PianoSonataNo232NdMov 0.35 0.24 0.25 0.29 0.19 0.21
GolliwoggsCakewalk 0.60 0.43 0.45 0.57 0.40 0.42
PianoSonataNo21StMov 0.32 0.22 0.25 0.36 0.23 0.25
PianoSonataK279InCMajor1StMov 0.43 0.35 0.35 0.53 0.38 0.39
Mean 0.42 0.31 0.33 0.43 0.30 0.32
18
Figure 8: F1 score of all 184 trained song-specific policies (descending order)
19 | Section not found | Section not found | Section not found | Section not found | Section not found | Experimental Results
We split the experimental evaluation into three parts. In the first part, we explore the performance of
our proposed framework in learning song-specific policies via RL. In the second part, we perform
ablation studies on policy designs for learning a generalist piano-playing agent by distilling the pre-
viously learned policies via BC. Finally, in the third part, we explore the influence of the amount of
training data on the performance of the test environments.
Dataset and Evaluation Metrics All experiments are conducted on our collected dataset, which
contains the notes and the corresponding demonstration videos and fingertip trajectories of 60 piano
songs from a Youtube channel PianoX1. To standardize the length of each task, each song is di-
vided into several clips, each with a duration of 30 seconds (The dataset contains totally 431 clips,
258K state-action pairs). Furthermore, we choose 12 unseen clips to investigate the generalization
capability of the generalist policy. We use the same evaluation metrics from RoboPianist [11], i.e.,
precision, recall, and F1 score.
Simulation Environment Our experiment setup utilizes R OBOPIANIST simulation environment
[11], conducted in Mujoco physics simulator [26]. The agent predicts target joint angles at 20Hz
and the targets are converted to torques using PD controllers running at 500Hz. We use the same
physical setting as [11] with two modifications: 1) The z-axis sliding joints fixed on both forearms
are enabled to allow more versatile hand movement. Therefore, the action space of our agent is 47
dimensional (45 dimensional in [11]). 2) We increase the proportional gain of the PD controller
for the x-axis sliding joints to enable faster horizontal movement, which we find essential for some
fast-paced piano songs.
4.1 Evaluation on learning song-specific policies from demonstrations
In this section, we evaluate the song-specific policy learning and aim to answer the following ques-
tions: ( 1) Does integrating human demonstrations with RL help in achieving better performance?
(2) What elements of the learning algorithm are the most influential in achieving good performance?
We use Proximal Point Optimization (PPO) [27], because we find that it performs the best compared
to other RL algorithms. We compare our model against two baselines:
Robopianist [11] We use the RL method introduced in [11]. We maintain the same reward functions
1https://www.youtube.com/channel/UCsR6ZEA0AbBhrF-NCeET6vQ
5
Baseline
OursMethod
Baseline IK Ours
Without Both Without Residual
Without Mimic With Both
0.20.40.60.81.0F1 Score
Figure 3: Left: Qualitative comparison of hand postures. Middle: The F1 score achieved by three
methods for 10 chosen clips; Right: The F1 score achieved by excluding different elements in RL.
as the original work and manually label the fingering from the demonstrations videos to provide the
fingering reward.
Inverse Kinematics (IK) [21] Given a demonstration fingertip trajectory τx, a Quadratic
Programming-based IK solver [21] is used to compute a target joint position trajectory and exe-
cute it open-loop.
Figure 4: Qualitative comparison of hand poses.
Top: Youtube video, Middle: IK solution given
the video. Bottom: After residual RL.We select 10 clips with diverse levels of diffi-
culty from the collected dataset. We individu-
ally train specialized policies for each of the 10
clips using both the baseline and our methods.
Subsequently, we assess and compare their per-
formance based on the achieved F1 Score.
Performance. As shown in Figure 3, our
method consistently outperforms the Robopi-
anist baseline for all 10 clips, achieving an aver-
age F1 score of 0.94 compared to the baseline’s
0.75. We attribute this improvement to the in-
corporation of human priors, which narrows
the RL search space to a favorable subspace,
thereby encouraging the algorithm to converge
towards more optimal policies. Additionally,
the IK method achieves an average F1 score of
0.72, only slightly lower than the baseline. This demonstrates the effectiveness of incorporating
human priors, providing a strong starting point for RL.
Impact of Elements. Our RL method incorporates two main elements: Style-mimicking reward and
Residual learning. We individually exclude each element to investigate their respective influences
on policy performance (See Figure 3). We clearly observe the critical role of residual learning im-
plying the benefit of exploiting human demonstrations as nominal behavior. We observe a marginal
performance increase of 0.03 when excluding the style-mimicking reward; however, this also results
in a larger discrepancy between the fingertip trajectory of the robot and the human. Thus, the weight
of the style-mimicking reward can be viewed as a parameter that controls the human likeness of the
learned robot actions.
Qualitative comparison. We present a qualitative comparison of the human likeness of the robot
motion in Figure 4 and the attached videos. We inspect the hand poses for certain frames and ob-
serve that the IK nominal behavior leads the robot to place the fingers in positions similar to those in
Youtube videos. The RL policy then slightly adapts the fingertip positions to press the keys correctly.
4.2 Evaluation of model design strategies for policy distillation
This section focuses on the evaluation of policy distillation for playing different songs. We evaluate
the influence of different policy design strategies on the agent’s performance. We aim to assess ( 1)
the impact of integrating a pre-trained observation encoder to induce spatially consistent features,
(2) the impact of a hierarchical design of the policy, and ( 3) the performance of different generative
models on piano-playing data.
6
Multi-RL BC-MSE Two-Stage Diff -res w/o SDF One-Stage BeTTrainP 0.85 0.56 0.87 0.89 0.86 0.53 0.63
R 0.20 0.29 0.78 0.80 0.76 0.34 0.42
F1 0.12 0.30 0.81 0.82 0.78 0.35 0.49TestP 0.95 0.54 0.69 0.71 0.66 0.58 0.53
R 0.18 0.22 0.54 0.55 0.49 0.27 0.30
F1 0.13 0.21 0.56 0.57 0.51 0.26 0.31
Table 1: Quantitative results evaluated on Training and Test Datasets. Test datasets consist of 12
clips unseen in the training dataset. We report Precision (P), Recall (R) and F1-score (F1).
We propose two base policies, Two-stage Diff andTwo-stage Diff-res policy. Both of them utilize
hierarchical policies and goal representation learning, as described in Section 3.3. The only differ-
ence between them is: the low-level policy of Two-stage Diff directly predicts the target joints, while
Two-stage Diff-res predicts the residual term of an IK solver. Both high- and low-level policies
are trained with Denoising Diffusion Probabilistic Models (DDPM) [28]. The high-level policy is
trained to predict the fingertip trajectory for 4 timesteps given the SDF embedding (See Appendix E)
of goals over 10 timesteps, while the low-level policy predicts the robot actions or residuals for 4
timesteps given the fingertip trajectory. Note that the entire dataset is used for training the high-level
policy, while only around 40 % of the collected clips (110K state-action pairs) are trained with RL
and further used for training the low-level policy. The detailed network implementation is described
in Appendix F.
Then, to analyze the impact of each variable, we design four variants of the Two-stage Diffusion
policy. To evaluate ( 1) the impact of integrating a pre-trained observation encoder, we train a model
without the SDF embedding representation for the goal ( w/o SDF ). To evaluate ( 2) the impact of the
hierarchical architecture, we train a One-stage Diffusion policy that directly predict the joint space
actions given the goal. Finally, to evaluate ( 3) the influence of using different generative models, we
train a Two-stage BeT, that replaces Diffusion models with Behavior-Transformers [23]. We also
consider as baselines a Multi-task RL policy and a BCpolicy with MSE Loss. We provide further
details of the models in Appendix G.
Results As shown in Table 1, despite that Multi-task RL has the highest precision on the test dataset
(this is because it barely presses any keys), our methods (Two-stage Diff and Two-stage Diff-res)
outperform the others in all metrics on both training and test datasets. We also observe that the
incorporation of SDF embedding for goal representation leads to better performance, especially
on the test dataset, which demonstrates the impact of goal representation on policy generalization.
Furthermore, we observe a slight performance enhancement when the model predicts the residual
term of IK (Two-stage Diff-res). We speculate that this improvement stems from our training data
being generated through residual RL, which leverages the output of the IK solver as a prior. This
approach likely causes the learned actions to correlate with the outputs of the IK solver.
4.3 Evaluations on the impact of the data in the generalization
In this section, we investigate the impact of scaling training data on the generalization capabilities
of the agent. We evaluate three policy designs ( One-stage Diff ,Two-stage Diff , and Two-stage
Diff-res ). We train them using various proportions of the dataset, and evaluate their performance on
the test dataset (see Figure 5 Top). Note that One-stage Diff uses the same dataset as the low-level
policy of Two-stage Diff.
Results. We observe that both Two-stage Diff and Two-stage Diff-res show consistent performance
improvement with increasing used data. This trend implies that the two-stage policies have not yet
reached their performance saturation with the given data and could potentially continue to benefit
from additional training data in future works.
7
Figure 5: Precision and Recall for three different policy architectures trained with varying amount
of data volumes evaluated on the test dataset. Top: Models are trained with the same proportion of
high-level and low-level datasets. Bottom : Models are trained with different proportions of high-
level and low-level datasets. The x-axis represents the percentage of the low-level dataset utilized,
while HL % indicates the percentage of the high-level dataset used.
Evaluation on imbalance training datasets. We further employ different combinations of the high-
level and low-level policies of Two-stage Diff trained with different proportions of the dataset and
assess their performance. In addition, we introduce an oracle high-level policy, which outputs the
ground-truth fingertip position from human demonstration videos. The results (see Figure 5 Bottom)
demonstrate that the overall performance of policy is significantly influenced by the quality of the
high-level policy. Low-level policies paired with Oracle high-level policies consistently outperform
the ones paired with other high-level policies. Besides, we observe early performance convergence
with increasing training data when paired with a low-quality high-level policy. Specifically, with the
HL1%policy and HL 50%, performance almost converged with around 10% and50% low-level
data, respectively.
4.4 Limitations
Inference Speed One of the limitations is the inference speed. The models operate with an infer-
ence frequency of approximately 15Hz on an RTX 4090 machine, which is lower than the standard
real-time demand on hardware. Future works can employ faster diffusion models, e.g., DDIM [29],
to speed up the inference.
Out-of-distribution Data Most of the songs in our collected dataset are of modern style. When
evaluating the model on the dataset from [11], which mainly contains classical songs, the perfor-
mance degrades. This discrepancy implies the model’s limited generalization across songs of differ-
ent styles. Future work can collect more diverse training data to improve this aspect.
Acoustic Experience Although the policy achieves up to 56% F1-score on unseen songs, we found
that higher accuracy is still necessary to make the song acoustically appealing and recognizable.
Future work should focus on improving this accuracy to enhance the overall acoustic experience.
5 Conclusion
In this work, we present PianoMime, a framework for training a generalist robotic pianist using in-
ternet video sources. We start by training song-specific policies with residual RL, enabling the robot
to master individual songs by mimicking human pianists. Subsequently, we train a single behavioral
cloning policy that mimics these song-specific policies to play unseen songs. The policy leverages
three key techniques: goal representation learning, policy hierarchy, and expressive generative mod-
els. The resulting policy demonstrates an impressive generalization capability, achieving an average
F1-score of 70% on unseen songs. This also highlights that leveraging internet data can be highly
useful for training generalist robotic agents.
8
Acknowledgments
If a paper is accepted, the final camera-ready version will (and probably should) include acknowl-
edgments. All acknowledgments go at the end of the paper, including thanks to reviewers who gave
useful comments, to colleagues who contributed to the ideas, and to funding agencies and corporate
sponsors that provided financial support.
References
[1] M. V ¨olske, M. Potthast, S. Syed, and B. Stein. Tl; dr: Mining reddit to learn automatic
summarization. In Proceedings of the Workshop on New Frontiers in Summarization , pages
59–63, 2017.
[2] L. Fan, G. Wang, Y . Jiang, A. Mandlekar, Y . Yang, H. Zhu, A. Tang, D.-A. Huang, Y . Zhu,
and A. Anandkumar. Minedojo: Building open-ended embodied agents with internet-scale
knowledge. Advances in Neural Information Processing Systems , 35:18343–18362, 2022.
[3] K. Grauman, A. Westbury, E. Byrne, Z. Chavis, A. Furnari, R. Girdhar, J. Hamburger, H. Jiang,
M. Liu, X. Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In
Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition , pages
18995–19012, 2022.
[4] F. Torabi, G. Warnell, and P. Stone. Recent advances in imitation learning from observation.
arXiv preprint arXiv:1905.13566 , 2019.
[5] X. B. Peng, P. Abbeel, S. Levine, and M. Van de Panne. Deepmimic: Example-guided deep re-
inforcement learning of physics-based character skills. ACM Transactions On Graphics (TOG) ,
37(4):1–14, 2018.
[6] G. Garcia-Hernando, E. Johns, and T.-K. Kim. Physics-based dexterous manipulations with
estimated hand poses and residual reinforcement learning. In 2020 IEEE/RSJ International
Conference on Intelligent Robots and Systems (IROS) , pages 9561–9568. IEEE, 2020.
[7] X. B. Peng, E. Coumans, T. Zhang, T.-W. Lee, J. Tan, and S. Levine. Learning agile robotic
locomotion skills by imitating animals. Robotics: Science and Systems (RSS) , 2020.
[8] A. Nair, D. Chen, P. Agrawal, P. Isola, P. Abbeel, J. Malik, and S. Levine. Combining self-
supervised learning and imitation for vision-based rope manipulation. In 2017 IEEE interna-
tional conference on robotics and automation (ICRA) , pages 2146–2153. IEEE, 2017.
[9] L. Shao, T. Migimatsu, Q. Zhang, K. Yang, and J. Bohg. Concept2robot: Learning manip-
ulation concepts from instructions and human demonstrations. The International Journal of
Robotics Research , 40(12-14):1419–1434, 2021.
[10] Y . J. Ma, S. Sodhani, D. Jayaraman, O. Bastani, V . Kumar, and A. Zhang. Vip: Towards
universal visual reward and representation via value-implicit pre-training. arXiv preprint
arXiv:2210.00030 , 2022.
[11] K. Zakka, P. Wu, L. Smith, N. Gileadi, T. Howell, X. B. Peng, S. Singh, Y . Tassa, P. Florence,
A. Zeng, et al. Robopianist: Dexterous piano playing with deep reinforcement learning. In
Conference on Robot Learning , pages 2975–2994. PMLR, 2023.
[12] T. Silver, K. Allen, J. Tenenbaum, and L. Kaelbling. Residual policy learning. arXiv preprint
arXiv:1812.06298 , 2018.
[13] T. Johannink, S. Bahl, A. Nair, J. Luo, A. Kumar, M. Loskyll, J. A. Ojea, E. Solowjow, and
S. Levine. Residual reinforcement learning for robot control. In 2019 international conference
on robotics and automation (ICRA) , pages 6023–6029. IEEE, 2019.
9
[14] B. Scholz. Playing piano with a shadow dexterous hand. PhD thesis, Universitat Hamburg ,
2019.
[15] H. Xu, Y . Luo, S. Wang, T. Darrell, and R. Calandra. Towards learning to play piano with
dexterous hands and touch. In 2022 IEEE/RSJ International Conference on Intelligent Robots
and Systems (IROS) , pages 10410–10416. IEEE, 2022.
[16] T. Geijtenbeek, M. Van De Panne, and A. F. Van Der Stappen. Flexible muscle-based locomo-
tion for bipedal creatures. ACM Transactions on Graphics (TOG) , 32(6):1–11, 2013.
[17] N. Chentanez, M. M ¨uller, M. Macklin, V . Makoviychuk, and S. Jeschke. Physics-based mo-
tion capture imitation with deep reinforcement learning. In Proceedings of the 11th ACM
SIGGRAPH Conference on Motion, Interaction and Games , pages 1–10, 2018.
[18] L. Liu and J. Hodgins. Learning basketball dribbling skills using trajectory optimization and
deep reinforcement learning. ACM Transactions on Graphics (TOG) , 37(4):1–14, 2018.
[19] X. B. Peng, Z. Ma, P. Abbeel, S. Levine, and A. Kanazawa. Amp: Adversarial motion priors
for stylized physics-based character control. ACM Transactions on Graphics (ToG) , 40(4):
1–20, 2021.
[20] C. Lugaresi, J. Tang, H. Nash, C. McClanahan, E. Uboweja, M. Hays, F. Zhang, C.-L. Chang,
M. G. Yong, J. Lee, et al. Mediapipe: A framework for building perception pipelines. arXiv
preprint arXiv:1906.08172 , 2019.
[21] S. Caron, Y . De Mont-Marin, R. Budhiraja, and S. H. Bang. Pink: Python inverse kinematics
based on Pinocchio, 2024. URL https://github.com/stephane-caron/pink .
[22] C. Chi, S. Feng, Y . Du, Z. Xu, E. Cousineau, B. Burchfiel, and S. Song. Diffusion policy:
Visuomotor policy learning via action diffusion. arXiv preprint arXiv:2303.04137 , 2023.
[23] N. M. Shafiullah, Z. Cui, A. A. Altanzaya, and L. Pinto. Behavior transformers: Cloning k
modes with one stone. Advances in neural information processing systems , 35:22955–22968,
2022.
[24] P. Florence, C. Lynch, A. Zeng, O. A. Ramirez, A. Wahid, L. Downs, A. Wong, J. Lee, I. Mor-
datch, and J. Tompson. Implicit behavioral cloning. In Conference on Robot Learning , pages
158–168. PMLR, 2022.
[25] T. Z. Zhao, V . Kumar, S. Levine, and C. Finn. Learning fine-grained bimanual manipulation
with low-cost hardware. arXiv preprint arXiv:2304.13705 , 2023.
[26] E. Todorov, T. Erez, and Y . Tassa. Mujoco: A physics engine for model-based control. In
2012 IEEE/RSJ International Conference on Intelligent Robots and Systems , pages 5026–
5033, 2012. doi:10.1109/IROS.2012.6386109.
[27] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization
algorithms. arXiv preprint arXiv:1707.06347 , 2017.
[28] J. Ho, A. Jain, and P. Abbeel. Denoising diffusion probabilistic models. Advances in neural
information processing systems , 33:6840–6851, 2020.
[29] J. Song, C. Meng, and S. Ermon. Denoising diffusion implicit models. arXiv preprint
arXiv:2010.02502 , 2020.
[30] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
10
[31] D. Hendrycks and K. Gimpel. Gaussian error linear units (gelus). arXiv preprint
arXiv:1606.08415 , 2016.
[32] E. Perez, F. Strub, H. De Vries, V . Dumoulin, and A. Courville. Film: Visual reasoning with
a general conditioning layer. In Proceedings of the AAAI conference on artificial intelligence ,
volume 32, 2018.
[33] T. Haarnoja, A. Zhou, P. Abbeel, and S. Levine. Soft actor-critic: Off-policy maximum entropy
deep reinforcement learning with a stochastic actor. In International conference on machine
learning , pages 1861–1870. PMLR, 2018.
11
𝐻3×3Youtube MujocoFigure 6: Compute homography matrix given 8 correspondence feature points.
A Retargeting: From human hand to robot hand
To retarget from the human hand to robot hand, we follow a structured process.
Step 1: Homography Matrix Computation Given a top-view piano demonstration video, we
firstly choose ndifferent feature points on the piano. These points could be center points of specific
keys, edges, or other identifiable parts of the keys that are easily recognizable (See Figure 6).
Due to the uniform design of pianos, these points represent the same physical positions in both
the video and Mujoco. Given the chosen points, we follow the Eight-point Algorithm to compute
the Homography Matrix Hthat transforms the pixel coordinate in videos to the x-y coordinate in
Mujoco (z-axis is the vertical axis).
Step 2: Transformation of Fingertip Trajectory We then obtain the human fingertip tra-
jectory with MediaPipe [20]. We collect the fingertips positions every 0.05 seconds. Then we
transform the human fingertip trajectory within pixel coordinate into the Mujoco x-y 2D coordinate
using the computed homography matrix H.
Step 3: Heuristic Adjustment for Physical Alignment We found that the transformed fin-
gertip trajectory might not physically align with the notes, which means there might be no detected
fingertip that physically locates at the keys to be pressed or the detected fingertip might locate at the
border of the key (normally human presses the middle point of the horizontal axis of the key). This
misalignment could be due to the inaccuracy of the hand-tracking algorithm and the homography
matrix. Therefore, we perform a simple heuristic adjustment on the trajectory to improve the
physical alignment. Specifically, at each timestep of the video, we check whether there is any
fingertip that physically locates at the key to be pressed. If there is, we adjust its y-axis value to
the middle point of the corresponding key. Otherwise, we search within a small range, specifically
the neighboring two keys, to find the nearest fingertip. If no fingertip is found in the range or
the found fingertip has been assigned to another key to be pressed, we then leave it. Otherwise,
we adjust its y-axis value to the center of the corresponding key to ensure proper physical alignment.
Step 4: Z-axis Value Assignment Lastly, we assign the z-axis value for the fingertips. For
the fingertips that press keys, we set their z-axis values to 0. For other fingertips, we set their z-axis
value to 2¨hkey, where hkeyis the height of the keys in Mujoco.
B Implementation of Inverse Kinematics Solver
The implementation of the IK solver is based on the approach of [21]. The solver addresses multiple
tasks simultaneously by formulating an optimization problem and find the optimal joint velocities
that minimize the objective function. The optimization problem is given by:
min
9qÿ
iwi}Ji9q´Kivi}2, (1)
12
where wiis the weight of each task, Kiis the proportional gain and viis the velocity residual. We
define a set of 10 tasks, each specifying the desired position of one of the robot fingertips. We do not
specify the desired quaternions. All the weights wiare set to be equal. We use quadprog2to solve
the optimization problem with quadratic programming. The other parameters are listed in Table 2.
Table 2: The parameters of IK solver
Parameter Value
Gain 1.0
Limit Gain 0.05
Damping 1e-6
Levenberg-Marquardt Damping 1e-6
C Detailed MDP Formulation of Song-specific Policy
Table 3: The detailed reward function to train the song-specific policy. The Key Press reward is the
same as in [11], where ksandkgrepresent the current and the goal states of the key respectively,
and g is a function that transforms the distances to rewards in the [0, 1] range. pd fandprfrepresent
the fingertip positions of human demonstrator and robot respectively.
Reward Formula Weight Explanation
Key Press 0.5¨gp}ks´kg}2q`0.5¨p1´1false positiveq2/3 Press the right keys and
only the right keys
Mimic gp}pd f´prf}2q 1/3 Mimic the demonstrator’s
fingertip trajectory
Table 4: The observation space of song-specific agent.
Observation Unit Size
Hand and Forearm Joint Positions Rad 52
Hand and forearm Joint Velocities Rad/s 52
Piano Key Joint Positions Rad 88
Piano key Goal State Discrete 88
Demonstrator Forearm and Fingertips Cartesian Positions m 36
Prior control input ˜u(solved by IK) Rad 52
Sustain Pedal state Discrete 1
D Training Details of Song-specific Policy
We use PPO [27] (implemented by StableBaseline 3 [30]) to train the song-specific policy with resid-
ual RL(See Algorithm 1). All of the experiments are conducted using the same network architecture
and tested using 3 different seeds. Both actor and critic networks are of the same architecture, con-
taining 2 MLP hidden layers with 1024 and 256 nodes, respectively, and GELU [31] as activation
functions. The detailed hyperparameters of the networks are listed in Table 7.
2https://github.com/quadprog/quadprog
13
Table 5: The action space of song-specific agent.
Action Unit Size
Target Joint Positions Rad 46
Sustain Pedal Discrete 1
Table 6: The Hyperparameters of PPO
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Exponential Decay
Decay Rate 0.999
Actor Hidden Units 1024, 256
Actor Activation GELU
Critic Hidden Units 1024, 256
Critic Activation GELU
Discount Factor 0.99
Steps per Update 8192
GAE Lambda 0.95
Entropy Coefficient 0.0
Maximum Gradient Norm 0.5
Batch Size 1024
Number of Epochs per Iteration 10
Clip Range 0.2
Number of Iterations 2000
Optimizer Adam
E Representation Learning of Goal
We train an autoencoder to learn a geometrically continuous representation of the goal (See Figure
7 and Algorithm 2). During the training phase, the encoder E, encodes the original 88-dimensional
binary representation of a goal piano state ˇ “(tinto a 16-dimensional latent code z. The positional
encoding of a randomly sampled 3D query coordinate xis then concatenated with the latent code z
and passed through the decoder D. We use positional encoding here to represent the query coordinate
more expressively. The decoder is trained to predict the SDF fpx, ˇ “(tq. We define the SDF value of
xwith respect to ˇ “(tas the Euclidean distance between the xand the nearest key that is supposed to
be pressed in ˇ “(t, mathematically expressed as:
SDFpx, ˇ “(tq“ min
pPtpi| ˇ “(t,i“1u}x´p}, (2)
where pirepresents the position of the i-th key on the piano. The encoder and decoder are jointly
optimized to minimize the reconstruction loss:
Lpx, , ˇ “(tq“p SDFpx, ˇ “(tq´DpEpv, xqqq2. (3)
We pre-train the autoencoder using the GiantMIDI dataset3, which contains 10K piano MIDI files
of 2,786 composers. The pre-trained encoder maps the ˇ “(tinto the 16-dimensional latent code,
which serves as the latent goal for behavioral cloning. The encoder network is composed of four
3https://github.com/bytedance/GiantMIDI-Piano
14
Algorithm 1: Training of the song-specific policy with residual RL
1:Initialize actor network πθ
2:Initialize critic network vϕ
3:fori“1 :Niteration do
4: # Collect trajectories
5: fort“1 :Tdo
6: Get human demonstrator fingertip position xtand observation ot
7: Compute the prior control signal that tracks xtwith the IK controller ˜ut“ikpxt, otq
8: Run policy to get the residual term rt“πθpotq
9: Compute the adapted control signal ut“˜ut`rt
10: Execute utin environment and collect st, ut, rt, st`1
11: end for
12: # Update networks
13: forn“1 :Ndo
14: Sample a batch of transitions tpsj, uj, rj, sj`1qufrom the collected trajectories
15: Update the actor and critic network with PPO
16: end for
17:end for
Query
Coordinate
Positional
Embedding
SDF Encoder
...1
0
10
188-dimensional
binary vector
Latent
Code+
Figure 7: 1) Encoding: The encoder compresses the binary representation of the goal into latent
code. 2) Decoding: A 3D query coordinate xis randomly sampled. A neural network predicts the
SDF value given the positional encoding of xand the latent code.
1D-convolutional layers, followed by a linear layer. Each successive 1D-convolutional layer has an
increasing number of filters, specifically 2, 4, 8, and 16 filters, respectively. All convolutional layers
utilize a kernel size of 3. The linear layer transforms the flattened output from the convolutional
layers into a 16-dimensional latent code. The decoder network is a MLP with 2 hidden layers, each
with 16 neurons. We train the autoencoder for 100 epochs with a learning rate of 1e´3.
F Training Details of Diffusion Model
All the diffusion models utilized in this work, including One-stage Diff, the high-level and
low-level policies of Two-stage Diff, Two-stage Diff-res and Two-stage Diff w/o SDF, share
15
Algorithm 2: Training of the goal autoencoder
1:Initialize encoder Eϕ
2:Initialize decoder Dψ
3:fori“1 :Nepoch do
4: forj“1 :Nbatch do
5: foreach goal vin batch do
6: Compute the latent code z“Eψp ˇ “(tq
7: Sample a 3D coordinate as query x“Sample3DCoordinate()
8: Compute the positional encoding of query pe“PositionalEncoding( xq
9: Compute the output of the decoder conditioned by the query Dϕpz, peq
10: Compute the SDF value of query SDF px, ˇ “(tq
11: Compute the reconstruction loss L
12: end for
13: Compute the sum of the loss
14: Compute the gradient
15: Update network parameter ϕ, ψ
16: end for
17:end for
the same network architecture. The network architecture are the same as the U-net diffusion
policy in [22] and optimized with DDPM [28], except that we use temporal convolutional net-
works (TCNs) as the observation encoder, taking the concatenated goals (high-level policy) or
fingertip positions (low-level policy) of several timesteps as input to extract the features on tem-
poral dimension. Each level of U-net is then conditioned by the outputs of TCNs through FiLM [32].
High-level policies take the goals over 10 timesteps and the current fingertip position as in-
put and predict the human fingertip positions. In addition, we add a standard gaussian noise on the
current fingertip position during training to facilitate generalization. We further adjust the y-axis
value of the fingertips pressing the keys in the predicted high-level trajectories to the midpoint
of the keys. This adjustment ensures closer alignment with the data distribution of the training
dataset. Low-level policies take the predicted fingertip positions and the goals over 4 timesteps, the
proprioception state as input predict the robot actions. The proprioception state includes the robot
joint positions and velocities, as well as the piano joint positions. We use 100 diffusion steps during
training. To achieve high-quality results during inference, we find that at least 80 diffusion steps are
required for high-level policies and 50 steps for low-level policies.
Table 7: The Hyperparameters of DDPM
Hyperparameter Value
Initial Learning Rate 1e-4
Learning Rate Scheduler Cosine
U-Net Filters Number 256, 512, 1024
U-Net Kernel Size 5
TCN Filters Number 32, 64
TCN Kernel Size 3
Diffusion Steps Number 100
Batch Size 256
Number of Iterations 800
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
16
G Policy Distillation Experiment
Two-stage Diff w/o SDF We directly use the binary representation of goal instead of the SDF
embedding representation to condition the high-level and low-level policies.
Two-stage Diff-res We employ an IK solver to compute the target joints given the fingertip
positions predicted by the high-level policy. The low-level policy predicts the residual terms of IK
solver instead of the robot actions.
Two-stage BeT We train both high-level and low-level policies with Behavior Transformer
[23] instead of DDPM. The hyperparameter of Bet is listed in Table 8.
One-stage Diff We train a single diffusion model to predict the robot actions given the SDF
embedding representation of goals and the proprioception state.
Multi-task RL We create a multi-task environment where for each episode a random song is
sampled from the dataset. Consequently, we use Soft-Actor-Critic (SAC) [33] to train a single agent
within the environment. Both the actor and critic networks are MLPs, each with 3 hidden layers,
and each hidden layer contains 256 neurons. The reward function is the same as that in [11].
BC-MSE We train a feedforward network to predict the robot action of next timestep con-
ditioned on the binary representation of goal and proprioception state with MSE loss. The
feedforward network is a MLP with 3 hidden layers, each with 1024 neurons.
Table 8: The Hyperparameters of Behavior Transformer
Hyperparameter Value
Initial Learning Rate 3e-4
Learning Rate Scheduler Cosine
Number of Discretization Bins 64
Number of Transformer Heads 8
Number of Transformer Layers 8
Embedding Dimension 120
Batch Size 256
Number of Iterations 1200
Optimizer AdamW
EMA Exponential Factor 0.75
EMA Inverse Multiplicative Factor 1
H F1 Score of All Trained Song-Specific Policies
Figure 8 shows the F1 score of all song-specific policies we trained.
I Detailed Results on Test Dataset
In Table 9 and Table 10, we show the Precision, Recall and F1 score of each song in our collected
test dataset and the Etude-12 dataset from [11], achieved by Two-stage Diff and Two-stage Diff-res,
respectively. We observe an obvious performance degradation when testing on Etude-12 dataset.
We suspect that the reason is due to out-of-distribution data, as the songs in the Etude-12 dataset are
all classical, whereas our training and test dataset primarily consists of modern songs.
17
Table 9: Quantitative results of each song in the our collected test dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
Forester 0.81 0.70 0.68 0.79 0.71 0.67
Wednesday 0.66 0.57 0.58 0.67 0.54 0.55
Alone 0.80 0.62 0.66 0.83 0.65 0.67
Somewhere Only We Know 0.63 0.53 0.58 0.67 0.57 0.59
Eyes Closed 0.60 0.52 0.53 0.61 0.45 0.50
Pedro 0.70 0.58 0.60 0.67 0.56 0.47
Ohne Dich 0.73 0.55 0.58 0.75 0.56 0.62
Paradise 0.66 0.42 0.43 0.68 0.45 0.47
Hope 0.74 0.55 0.57 0.76 0.58 0.62
No Time To Die 0.77 0.53 0.55 0.79 0.57 0.60
The Spectre 0.64 0.52 0.54 0.67 0.50 0.52
Numb 0.55 0.44 0.45 0.57 0.47 0.48
Mean 0.69 0.54 0.56 0.71 0.55 0.57
Table 10: Quantitative results of each song in the Etude-12 dataset
Song NameTwo-stage Diff Two-stage Diff-res
Precision Recall F1 Precision Recall F1
FrenchSuiteNo1Allemande 0.45 0.31 0.34 0.39 0.27 0.30
FrenchSuiteNo5Sarabande 0.29 0.23 0.24 0.24 0.18 0.19
PianoSonataD8451StMov 0.58 0.52 0.52 0.60 0.50 0.51
PartitaNo26 0.35 0.22 0.24 0.40 0.24 0.26
WaltzOp64No1 0.44 0.31 0.33 0.43 0.28 0.31
BagatelleOp3No4 0.45 0.30 0.33 0.45 0.28 0.32
KreislerianaOp16No8 0.43 0.34 0.36 0.49 0.34 0.36
FrenchSuiteNo5Gavotte 0.34 0.29 0.33 0.41 0.31 0.33
PianoSonataNo232NdMov 0.35 0.24 0.25 0.29 0.19 0.21
GolliwoggsCakewalk 0.60 0.43 0.45 0.57 0.40 0.42
PianoSonataNo21StMov 0.32 0.22 0.25 0.36 0.23 0.25
PianoSonataK279InCMajor1StMov 0.43 0.35 0.35 0.53 0.38 0.39
Mean 0.42 0.31 0.33 0.43 0.30 0.32
18
Figure 8: F1 score of all 184 trained song-specific policies (descending order)
19 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18078v1 | http://arxiv.org/pdf/2407.18078v1 | PEFT-U: Parameter-Efficient Fine-Tuning for User Personalization | Christopher Clarke, Yuzhao Heng, Lingjia Tang, Jason Mars | 2024-07-25 | Abstract
The recent emergence of Large Language Mod-
els (LLMs) has heralded a new era of human-AI
interaction. These sophisticated models, exem-
plified by Chat-GPT and its successors, have
exhibited remarkable capabilities in language
understanding. However, as these LLMs have
undergone exponential growth, a crucial dimen-
sion that remains understudied is the person-
alization of these models. Large foundation
models such as GPT-3 etc. focus on creating
a universal model that serves a broad range
of tasks and users. This approach emphasizes
the model’s generalization capabilities, treating
users as a collective rather than as distinct indi-
viduals. While practical for many common ap-
plications, this one-size-fits-all approach often
fails to address the rich tapestry of human diver-
sity and individual needs. To explore this issue
we introduce the PEFT-U Benchmark : a new
dataset for building and evaluating NLP mod-
els for user personalization. PEFT-U consists
of a series of user-centered tasks containing di-
verse and individualized expressions where the
preferences of users can potentially differ for
the same input. Using PEFT-U, we explore the
challenge of efficiently personalizing LLMs to
accommodate user-specific preferences in the
context of diverse user-centered tasks.
1 | Introduction
Large Language Models (LLMs) have shown
tremendous capability in performing complex tasks
such as reasoning, summarization, creative writing,
etc. Through the scaling of these models, both
in size ( >1B parameters) and data ( >1 Trillion
tokens) these models have achieved remarkable
performance on a wide range of natural language
understanding and generation tasks (Touvron et al.,
2023; Henighan et al., 2020). However, even as
the generalization capability of LLMs has grown,
one crucial dimension that has been understudied is
the personalization of these models (Salemi et al.,
2023; Kazienko et al., 2023).At its core, personalization is about tailoring AI-
driven interactions to the individual preferences,
needs, and idiosyncrasies of each user (Salemi
et al., 2023; Welch et al., 2022; Clarke et al., 2023;
Kang et al., 2022). In many real-world scenar-
ios, users have unique preferences, contexts, and
expectations, which are currently incapable of be-
ing effectively accommodated by the generalized
LLMs available today. These traditional LLMs
have predominantly adhered to a "one-size-fits-
all" approach (Touvron et al., 2023; Clarke et al.,
2022; OpenAI, 2023; Bubeck et al., 2023), offer-
ing a single, uniform model capable of serving all
users and tasks alike. While this approach is un-
doubtedly valuable in many scenarios, it falls short
when it comes to accommodating the rich tapestry
of human diversity where people are not uniform,
and their linguistic and communicative preferences
vary widely (Li et al., 2023; Zhang et al., 2018).
Existing works in NLP have highlighted the need
for user perspective in language modeling partic-
ularly when dealing with intrinsically subjective
applications such as Hate Speech Detection and
Sentiment Analysis where differing perspectives
are common (Mostafazadeh Davani et al., 2022;
Sang and Stanton, 2021; Geva et al., 2019; Kan-
clerz et al., 2022; Welch et al., 2022). Research
has shown that accounting for user perspective
and personalization is essential for building robust
and effective models (Mostafazadeh Davani et al.,
2022; Sang and Stanton, 2021; Geva et al., 2019;
Kanclerz et al., 2022; Welch et al., 2022). How-
ever, despite this glaring need, existing resources
fail to model and cater to these differing perspec-
tives. When curated, NLP resources tend to have
an intrinsic bias towards the majority perspective
due to their reliance on voting for ground truth.
As such they fail to adequately represent diverse
user preferences and individualized expressions,
further contributing to a lack of personalization
(Mostafazadeh Davani et al., 2022; Sang and Stan-arXiv:2407.18078v1 [cs.CL] 25 Jul 2024
ton, 2021; Geva et al., 2019; Kanclerz et al., 2022).
To combat these challenges we introduce the
PEFT-U Benchmark . PEFT-U consists of over
13+ personalized tasks and 15k+ users across do-
mains such as Hate Speech, Sentiment/Emotion,
and Humor. In contrast to other resources, the
PEFT-U benchmark uniquely tests complex scenar-
ios where LLMs are faced with differing user per-
spectives even when facing the same input. To the
best of our knowledge, this benchmark is the first
of its kind to focus on modeling user preferences
in NLP with an emphasis on identical inputs that
require different model outputs depending upon
the user. Using PEFT-U we explore a range of
strategies for efficiently compartmentalizing user
perspectives. In particular, we implement and em-
pirically analyze a series of personalized prompting
approaches (non-parametric) vs tuning and com-
partmentalizing user-level knowledge (parametric)
for personalized tasks showing that personalized
models are crucial to providing users with more
accurate results representative of their actual per-
spectives. We publicly release our code, models,
and benchmark1.
2 PEFT-U Benchmark
The PEFT-U benchmark aims to assess the effi-
cacy of language models in producing personalized
outputs based on user-specific information.
Data Collection To generate high-quality data
samples representative of differing user perspec-
tives we focus on curating subjective problems
where the model is forced to respect the user’s
points of view e.g. Hate Speech Detection. Typi-
cally NLP resources for these problem areas em-
ploy an annotation process where correctness is
determined via majority vote and outliers are dis-
carded. This often results in the overlooking of
the subtleties of the user’s perspective, ultimately
leading to potential group biases and inaccuracies
in the data. In contrast, we reconstruct these data
sources framing individual annotators as distinct
users to capture these important nuances. To avoid
the possible influence of noisy/bad annotators we
take into account their contribution level to the an-
notation process and discard low-quality users. Ad-
ditionally, we discard users with less than n= 10
samples in their training and test sets respectively.
1https://github.com/ChrisIsKing/
Parameter-Efficient-PersonalizationAs shown in table 1 PEFT-U consists of 13+ person-
alized tasks and 15k+ users with each task gaining
a maximum Krippendorff’s alpha ( α) of 0.5 (Krip-
pendorff, 2011) across the domains of Hate/Abuse,
Humor, and Emotion/Sentiment as shown in ta-
ble 1. For each dataset, we construct a unique
instruction-style prompt to guide the LLM to gen-
erate the desired output. More details on each of
the specific datasets, our reconstruction process,
and their prompts are provided in Appendix A.
User Disagreement As shown in table 1, we
enforce that all personalized tasks must obtain a
Krippendorff’s alpha score of (α≤0.5). This re-
quirement is created to assess the ability to capture
differing user perspectives even when facing the
same input. Krippendorff’s alpha (α)is a reliabil-
ity coefficient developed to measure the agreement
among annotators. When used in data curation,
data is usually considered reliable when (α≥0.8).
By enforcing all datasets to have low agreement
scores, we force the model to rely on respective
user information to generate its output.
3 Modularity + Personalization
When exploring the problem of personalization,
one possible solution would be the allocation of a
dedicated LLM for each user. However, deploy-
ing a separate personalized model for each user
would incur significant compute costs in produc-
tion. In addition, the balance between embedding
generalized and personalized knowledge in these
models remains unclear. Thus providing such a
solution is prohibitive in this era of large language
models. Recent works in Modular Deep Learning
(Liu et al., 2022a; Pfeiffer et al., 2023; Hu et al.,
2021; Houlsby et al., 2019), seek to optimize and
further tune these LLMs without having to update
all the model parameters. These methods typically
introduce a small number of additional parame-
ters and update these parameters in a model while
freezing the remaining weights, thus limiting the
computational resources required. This is often
done to enable multi-task learning or to introduce
new updates in the training data without the need
for training from scratch.
In our experiment setting, we shift this paradigm
from multi-task learning to multi-user learning fo-
cusing on the research question of "How to ef-
ficiently personalize large language models for
subjective tasks?" . As such, we empirically an-
alyze personalized prompting approaches (non-
Dataset
# UsersAvg # examples
per userAvg # users
per textKrippendorff’s
AlphaDomain Name
Hate+AbuseHateXplain (Mathew et al., 2022) 253 238.9 3.0 0.46
GabHate (Kennedy et al., 2018) 18 4807.16 3.12 0.24
MeasuringHateSpeech (Sachdeva et al., 2022) 7912 17.13 3.42 0.47
TweetEval (Röttger et al., 2022) 20 200.0 200.0 0.14
UnhealthyConversations (Price et al., 2020) 588 386.77 4.64 0.28
WikiDetox Aggression (Wulczyn et al., 2017) 4053 336.84 11.78 0.43
SentimentGoEmotion (Demszky et al., 2020) 82 1859.95 2.83 0.44
StudEmo (Ngo et al., 2022) 25 296.44 1.43 0.18
Subjective Discourse (Ferracane et al., 2021)∗68 9.26 6.20 0.50/0.01/0.01
HumorCockamamie (Gultchin et al., 2019) 1878 489.33 7.65 0.08
EPIC (Frenda et al., 2023) 74 191.51 4.72 0.19
Table 1: PEFT-U Benchmark: We design a large-scale benchmark for personalized model training and evaluation
consisting of 13+ personalized tasks across 15k+ users with each task obtaining a Krippendorff’s alpha ( α)<0.5
per task.∗Subjective Discourse consists of 3 different sentiment tasks.
parametric) vs efficiently tuning and compartmen-
talizing user-level knowledge (parametric) for per-
sonalized tasks.
4 Benchmark Evaluation
To quantify the challenge the PEFT-U benchmark
presents, we evaluate the performance of a range of
parameter-efficient methods compared to zero/few-
shot prompting approaches.
Methods We implement and evaluate 7 differ-
ent parameter-efficient methods for personalizing
LLMs using Flan-T5 (Chung et al., 2022). These
methods consist of:
1)Zero-shot/Few-shot Prompting : Using k=
3random samples of user data we construct an
instruction-style prompt for inference.
2)LoRa (Hu et al., 2021): injects trainable
rank decomposition matrices into each layer of the
Transformer architecture.
3)Adapters (Houlsby et al., 2019) add a train-
able bottleneck layer after the feedforward network
in each Transformer layer.
4)Prompt Tuning (Lester et al., 2021) intro-
duces an additional ktunable tokens per down-
stream task prepended to the input text and trained
end-to-end.
5)Prefix-Tuning (Li and Liang, 2021) prepends
task-specific trainable vectors to the input of multi-
head attention in each Transformer layer that is
attended to as virtual tokens.
6)P-Tuning (Liu et al., 2022b) employs train-
able continuous prompt embeddings in concatena-
tion with discrete prompts.
7)IAˆ3 (Liu et al., 2022a) introduces trainablevectors lwinto different components of the trans-
former which perform element-wise rescaling of
inner model activations.
Training We train all models with AdamW
(Loshchilov and Hutter, 2019) and a weight de-
cay of 0.01 on NVIDIA RTX 3090 24GB GPUs.
We use a learning rate of 2e-5, batch size of 16,
and a linear learning rate warmup over the first
10% steps with a cosine schedule for 8 epochs over
multiple runs with varied random seeds.
5 Results
Evaluation Metrics We consider two perfor-
mance metrics: (1) average per-user accuracy per
task and (2) average accuracy for all tasks.
5.1 Few/Zero-shot vs PEFT
Table 2 shows our results analyzing existing PEFT
methods in comparison to few/zero-shot prompting
techniques. From these results, we show that per-
sonalizing models is crucial to providing users with
more accurate results representative of their actual
perspectives. Notably, zero/few-shot prompting
falls short of adequately representing user view-
points compared to its trained counterparts being
outperformed on average by all methods except
for Prompt Tuning. Across all methods, results
show that Adapters performs the best outperform-
ing on 12 out of the 13 PEFT-U tasks and achieving
an overall accuracy score of 64.4% compared to
59.5% of LoRa in 2nd. The presented results un-
derscore the complexity of the PEFT-U benchmark,
revealing the challenges inherent in achieving con-
sistently high performance across diverse tasks and
Method Size #ParamsDataset
AverageHate+Abuse Sentiment Humor Sentiment
Hate
XplainGab
HateMHSTweet
EvalUHCWiki
DetoxGo
EmotionStud
EmoCockamamie EPIC SD(D) SD(QS) SD(RS)
Zero/Few-Shot (k=3) - 0 47.4 81.9 26.1 61.5 55.2 61.4 53.3 27.2 97.1 63.3 16.0 20.5 11.3 47.9
LoRA 3.8M 880K 54.9 88.6 27.4 69.5 73.4 81.0 66.3 67.7 97.2 67.9 29.4 30.7 18.9 59.5
Prefix Tuning 1.5M 370K 48.8 85.4 45.5 61.8 66.0 72.7 60.1 32.9 97.1 66.7 7.7 11.7 8.1 51.1
P-Tuning 128K 1.8M 48.7 81.9 29.2 61.3 56.8 62.3 53.8 27.6 97.0 62.8 16.6 19.6 11.1 48.4
Prompt Tuning 128K 31K 49.3 82.8 28.7 59.5 56.3 63.3 52.1 27.6 97.1 61.1 10.5 20.5 9.9 47.6
Adapters 14M 3.5M 59.0 89.1 38.9 70.5 77.5 84.0 68.4 83.7 97.2 68.5 35.3 39.0 25.6 64.4
IA^3 450K 111K 48.6 86.7 26.5 62.3 61.6 70.0 58.9 27.6 97.1 64.3 19.0 24.1 13.5 50.8
Table 2: Results of PEFT Methods on the PEFT-U Benchmark: This table shows the macro accuracy of each PEFT
method in comparison to Zero/Few-shot prompting on Flan-T5 (Chung et al., 2022).
MethodOriginal
ParamsAdjusted
ParamsOriginal
AccAcc
w/ Reduced Params
LoRA 880K 111K 69.5 66.2
Prefix Tuning 370K 111K 61.8 61.5
P-Tuning 1.6M 111K 61.7 61.7
Prompt Tuning 15K 111K 59.8 50.0
Adapters 3.5M 111K 70.5 64.2
IA^3 111K - 62.3 -
Table 3: Results on TweetEval task for PEFT-U with
equal number of trainable parameters.
datasets. While personalized fine-tuning methods
exhibit superior accuracy compared to traditional
few/zero-shot prompting techniques, the variations
in performance among different PEFT methods as
well as the performance on datasets such as Subjec-
tive Discourse and MeasuringHateSpeech indicate
that the benchmark presents a multifaceted chal-
lenge. The nuances of user personalization, model
size, and parameter tuning significantly impact the
effectiveness of these methods. This observed di-
versity in performance across methods suggests
that there is no one-size-fits-all solution, and fur-
ther investigation is imperative.
5.2 Impact of Number of Parameters
Given the performance of Adapters, we sought to
understand whether its performance was due to
the number of trainable parameters. As such, we
systematically varied the parameter count across
each method on the TweetEval Task. Notably, we
observed nuanced patterns across different PEFT
methods. As shown in table 3, with reduced pa-
rameters all methods except for P-tuning suffered
a decrease in overall performance. However, LoRa
with equal trainable parameters was able to outper-
form Adapters.
6 | Section not found | Related Works
Prior works have highlighted the need for user per-
spective particularly when dealing with intrinsi-
cally subjective applications where differing per-spectives are common (Mostafazadeh Davani et al.,
2022; Sang and Stanton, 2021; Geva et al., 2019;
Kanclerz et al., 2022; Welch et al., 2022). Re-
search has shown that accounting for user perspec-
tive and personalization is essential for building
robust and effective models (Mostafazadeh Davani
et al., 2022; Sang and Stanton, 2021; Geva et al.,
2019; Kanclerz et al., 2022; Welch et al., 2022).
However, despite this glaring need, existing re-
sources fail to model and cater to these differing
perspectives. When curated, NLP resources tend
to have an intrinsic bias towards the majority per-
spective due to their reliance on voting for ground
truth. As such they fail to adequately represent
diverse user preferences and individualized expres-
sions, further contributing to a lack of personaliza-
tion (Mostafazadeh Davani et al., 2022; Sang and
Stanton, 2021; Geva et al., 2019; Kanclerz et al.,
2022). Other benchmarks such as Salemi et al.
(2023) highlight the importance of personalization
LLMs, however, PEFT-U uniquely factors cases of
conflicting user perspectives when exploring per-
sonalization in addition to considering the compute
constraints.
7 Conclusion
This work addresses a critical gap in NLP concern-
ing the personalization of LLMs. While LLMs
have achieved remarkable performance in various
tasks, their generalization capabilities have pre-
dominantly followed a "one-size-fits-all" paradigm.
This approach falls short of meeting the diverse
linguistic and communicative preferences of indi-
vidual users. The PEFT-U Benchmark introduced
in this paper serves as an effort to evaluate the
personalization capabilities of LLMs across a spec-
trum of tasks. PEFT-U, presents a unique challenge
by emphasizing scenarios where identical inputs
necessitate diverse model outputs. The reported re-
sults showcase the inherent challenges posed by the
PEFT-U benchmark and advocate for the continued
exploration of effective personalization strategies.
8 Limitations
The PEFT-U Benchmark while designed to capture
diverse user perspectives, may not fully represent
the intricacies of all real-world communication sce-
narios. The dataset’s construction involved a care-
ful curation process, but the authors acknowledge
that the complexities of individual preferences and
linguistic nuances are vast and varied. In this work,
user perspective is modeled solely based on the
user’s output preferences. Factors such as age, gen-
der, and other potentially important demographics
are not considered.
In addition, the personalization methodologies
explored in this study may not encompass the entire
spectrum of potential approaches. The field of NLP
is dynamic, and emerging techniques could offer
alternative solutions to the challenges presented.
Personalization in LLMs is an evolving research
area, as such there may be relevant strategies re-
leased recently that were not covered in this work.
References
Sébastien Bubeck, Varun Chandrasekaran, Ronen El-
dan, Johannes Gehrke, Eric Horvitz, Ece Kamar, Pe-
ter Lee, Yin Tat Lee, Yuanzhi Li, Scott Lundberg,
Harsha Nori, Hamid Palangi, Marco Tulio Ribeiro,
and Yi Zhang. 2023. Sparks of artificial general in-
telligence: Early experiments with gpt-4.
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang,
Mostafa Dehghani, Siddhartha Brahma, Albert Web-
son, Shixiang Shane Gu, Zhuyun Dai, Mirac Suz-
gun, Xinyun Chen, Aakanksha Chowdhery, Sharan
Narang, Gaurav Mishra, Adams Yu, Vincent Zhao,
Yanping Huang, Andrew Dai, Hongkun Yu, Slav
Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam
Roberts, Denny Zhou, Quoc V . Le, and Jason Wei.
2022. Scaling instruction-finetuned language mod-
els.
Christopher Clarke, Matthew Hall, Gaurav Mittal,
Ye Yu, Sandra Sajeev, Jason Mars, and Mei Chen.
2023. Rule by example: Harnessing logical rules for
explainable hate speech detection. In Proceedings
of the 61st Annual Meeting of the Association for
Computational Linguistics (Volume 1: Long Papers) ,
pages 364–376, Toronto, Canada. Association for
Computational Linguistics.
Christopher Clarke, Joseph Peper, Karthik Krishna-
murthy, Walter Talamonti, Kevin Leach, Walter
Lasecki, Yiping Kang, Lingjia Tang, and Jason Mars.2022. One agent to rule them all: Towards multi-
agent conversational AI. In Findings of the Asso-
ciation for Computational Linguistics: ACL 2022 ,
pages 3258–3267, Dublin, Ireland. Association for
Computational Linguistics.
Dorottya Demszky, Dana Movshovitz-Attias, Jeongwoo
Ko, Alan Cowen, Gaurav Nemade, and Sujith Ravi.
2020. Goemotions: A dataset of fine-grained emo-
tions.
Elisa Ferracane, Greg Durrett, Junyi Jessy Li, and Ka-
trin Erk. 2021. Did they answer? subjective acts and
intents in conversational discourse. In Proceedings
of the 2021 Conference of the North American Chap-
ter of the Association for Computational Linguistics:
Human Language Technologies , pages 1626–1644,
Online. Association for Computational Linguistics.
Simona Frenda, Alessandro Pedrani, Valerio Basile,
Soda Marem Lo, Alessandra Teresa Cignarella, Raf-
faella Panizzon, Cristina Marco, Bianca Scarlini, Vi-
viana Patti, Cristina Bosco, and Davide Bernardi.
2023. EPIC: Multi-perspective annotation of a cor-
pus of irony. In Proceedings of the 61st Annual Meet-
ing of the Association for Computational Linguis-
tics (Volume 1: Long Papers) , pages 13844–13857,
Toronto, Canada. Association for Computational Lin-
guistics.
Mor Geva, Yoav Goldberg, and Jonathan Berant. 2019.
Are we modeling the task or the annotator? an inves-
tigation of annotator bias in natural language under-
standing datasets. In Proceedings of the 2019 Confer-
ence on Empirical | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | methods typically
introduce a small number of additional parame-
ters and update these parameters in a model while
freezing the remaining weights, thus limiting the
computational resources required. This is often
done to enable multi-task learning or to introduce
new updates in the training data without the need
for training from scratch.
In our experiment setting, we shift this paradigm
from multi-task learning to multi-user learning fo-
cusing on the research question of "How to ef-
ficiently personalize large language models for
subjective tasks?" . As such, we empirically an-
alyze personalized prompting approaches (non-
Dataset
# UsersAvg # examples
per userAvg # users
per textKrippendorff’s
AlphaDomain Name
Hate+AbuseHateXplain (Mathew et al., 2022) 253 238.9 3.0 0.46
GabHate (Kennedy et al., 2018) 18 4807.16 3.12 0.24
MeasuringHateSpeech (Sachdeva et al., 2022) 7912 17.13 3.42 0.47
TweetEval (Röttger et al., 2022) 20 200.0 200.0 0.14
UnhealthyConversations (Price et al., 2020) 588 386.77 4.64 0.28
WikiDetox Aggression (Wulczyn et al., 2017) 4053 336.84 11.78 0.43
SentimentGoEmotion (Demszky et al., 2020) 82 1859.95 2.83 0.44
StudEmo (Ngo et al., 2022) 25 296.44 1.43 0.18
Subjective Discourse (Ferracane et al., 2021)∗68 9.26 6.20 0.50/0.01/0.01
HumorCockamamie (Gultchin et al., 2019) 1878 489.33 7.65 0.08
EPIC (Frenda et al., 2023) 74 191.51 4.72 0.19
Table 1: PEFT-U Benchmark: We design a large-scale benchmark for personalized model training and evaluation
consisting of 13+ personalized tasks across 15k+ users with each task obtaining a Krippendorff’s alpha ( α)<0.5
per task.∗Subjective Discourse consists of 3 different sentiment tasks.
parametric) vs efficiently tuning and compartmen-
talizing user-level knowledge (parametric) for per-
sonalized tasks.
4 Benchmark Evaluation
To quantify the challenge the PEFT-U benchmark
presents, we evaluate the performance of a range of
parameter-efficient methods compared to zero/few-
shot prompting approaches.
Methods We implement and evaluate 7 differ-
ent parameter-efficient methods for personalizing
LLMs using Flan-T5 (Chung et al., 2022). These
methods consist of:
1)Zero-shot/Few-shot Prompting : Using k=
3random samples of user data we construct an
instruction-style prompt for inference.
2)LoRa (Hu et al., 2021): injects trainable
rank decomposition matrices into each layer of the
Transformer architecture.
3)Adapters (Houlsby et al., 2019) add a train-
able bottleneck layer after the feedforward network
in each Transformer layer.
4)Prompt Tuning (Lester et al., 2021) intro-
duces an additional ktunable tokens per down-
stream task prepended to the input text and trained
end-to-end.
5)Prefix-Tuning (Li and Liang, 2021) prepends
task-specific trainable vectors to the input of multi-
head attention in each Transformer layer that is
attended to as virtual tokens.
6)P-Tuning (Liu et al., 2022b) employs train-
able continuous prompt embeddings in concatena-
tion with discrete prompts.
7)IAˆ3 (Liu et al., 2022a) introduces trainablevectors lwinto different components of the trans-
former which perform element-wise rescaling of
inner model activations.
Training We train all models with AdamW
(Loshchilov and Hutter, 2019) and a weight de-
cay of 0.01 on NVIDIA RTX 3090 24GB GPUs.
We use a learning rate of 2e-5, batch size of 16,
and a linear learning rate warmup over the first
10% steps with a cosine schedule for 8 epochs over
multiple runs with varied random seeds.
5 | Section not found | Data Collection To generate high-quality data
samples representative of differing user perspec-
tives we focus on curating subjective problems
where the model is forced to respect the user’s
points of view e.g. Hate Speech Detection. Typi-
cally NLP resources for these problem areas em-
ploy an annotation process where correctness is
determined via majority vote and outliers are dis-
carded. This often | Section not found | results representative of their actual per-
spectives. We publicly release our code, models,
and benchmark1.
2 PEFT-U Benchmark
The PEFT-U benchmark aims to assess the effi-
cacy of language models in producing personalized
outputs based on user-specific information.
Data Collection To generate high-quality data
samples representative of differing user perspec-
tives we focus on curating subjective problems
where the model is forced to respect the user’s
points of view e.g. Hate Speech Detection. Typi-
cally NLP resources for these problem areas em-
ploy an annotation process where correctness is
determined via majority vote and outliers are dis-
carded. This often results in the overlooking of
the subtleties of the user’s perspective, ultimately
leading to potential group biases and inaccuracies
in the data. In contrast, we reconstruct these data
sources framing individual annotators as distinct
users to capture these important nuances. To avoid
the possible influence of noisy/bad annotators we
take into account their contribution level to the an-
notation process and discard low-quality users. Ad-
ditionally, we discard users with less than n= 10
samples in their training and test sets respectively.
1https://github.com/ChrisIsKing/
Parameter-Efficient-PersonalizationAs shown in table 1 PEFT-U consists of 13+ person-
alized tasks and 15k+ users with each task gaining
a maximum Krippendorff’s alpha ( α) of 0.5 (Krip-
pendorff, 2011) across the domains of Hate/Abuse,
Humor, and Emotion/Sentiment as shown in ta-
ble 1. For each dataset, we construct a unique
instruction-style prompt to guide the LLM to gen-
erate the desired output. More details on each of
the specific datasets, our reconstruction process,
and their prompts are provided in Appendix A.
User Disagreement As shown in table 1, we
enforce that all personalized tasks must obtain a
Krippendorff’s alpha score of (α≤0.5). This re-
quirement is created to assess the ability to capture
differing user perspectives even when facing the
same input. Krippendorff’s alpha (α)is a reliabil-
ity coefficient developed to measure the agreement
among annotators. When used in data curation,
data is usually considered reliable when (α≥0.8).
By enforcing all datasets to have low agreement
scores, we force the model to rely on respective
user information to generate its output.
3 Modularity + Personalization
When exploring the problem of personalization,
one possible solution would be the allocation of a
dedicated LLM for each user. However, deploy-
ing a separate personalized model for each user
would incur significant compute costs in produc-
tion. In addition, the balance between embedding
generalized and personalized knowledge in these
models remains unclear. Thus providing such a
solution is prohibitive in this era of large language
models. Recent works in Modular Deep Learning
(Liu et al., 2022a; Pfeiffer et al., 2023; Hu et al.,
2021; Houlsby et al., 2019), seek to optimize and
further tune these LLMs without having to update
all the model parameters. These methods typically
introduce a small number of additional parame-
ters and update these parameters in a model while
freezing the remaining weights, thus limiting the
computational resources required. This is often
done to enable multi-task learning or to introduce
new updates in the training data without the need
for training from scratch.
In our experiment setting, we shift this paradigm
from multi-task learning to multi-user learning fo-
cusing on the research question of "How to ef-
ficiently personalize large language models for
subjective tasks?" . As such, we empirically an-
alyze personalized prompting approaches (non-
Dataset
# UsersAvg # examples
per userAvg # users
per textKrippendorff’s
AlphaDomain Name
Hate+AbuseHateXplain (Mathew et al., 2022) 253 238.9 3.0 0.46
GabHate (Kennedy et al., 2018) 18 4807.16 3.12 0.24
MeasuringHateSpeech (Sachdeva et al., 2022) 7912 17.13 3.42 0.47
TweetEval (Röttger et al., 2022) 20 200.0 200.0 0.14
UnhealthyConversations (Price et al., 2020) 588 386.77 4.64 0.28
WikiDetox Aggression (Wulczyn et al., 2017) 4053 336.84 11.78 0.43
SentimentGoEmotion (Demszky et al., 2020) 82 1859.95 2.83 0.44
StudEmo (Ngo et al., 2022) 25 296.44 1.43 0.18
Subjective Discourse (Ferracane et al., 2021)∗68 9.26 6.20 0.50/0.01/0.01
HumorCockamamie (Gultchin et al., 2019) 1878 489.33 7.65 0.08
EPIC (Frenda et al., 2023) 74 191.51 4.72 0.19
Table 1: PEFT-U Benchmark: We design a large-scale benchmark for personalized model training and evaluation
consisting of 13+ personalized tasks across 15k+ users with each task obtaining a Krippendorff’s alpha ( α)<0.5
per task.∗Subjective Discourse consists of 3 different sentiment tasks.
parametric) vs efficiently tuning and compartmen-
talizing user-level knowledge (parametric) for per-
sonalized tasks.
4 Benchmark Evaluation
To quantify the challenge the PEFT-U benchmark
presents, we evaluate the performance of a range of
parameter-efficient methods compared to zero/few-
shot prompting approaches.
Methods We implement and evaluate 7 differ-
ent parameter-efficient methods for personalizing
LLMs using Flan-T5 (Chung et al., 2022). These
methods consist of:
1)Zero-shot/Few-shot Prompting : Using k=
3random samples of user data we construct an
instruction-style prompt for inference.
2)LoRa (Hu et al., 2021): injects trainable
rank decomposition matrices into each layer of the
Transformer architecture.
3)Adapters (Houlsby et al., 2019) add a train-
able bottleneck layer after the feedforward network
in each Transformer layer.
4)Prompt Tuning (Lester et al., 2021) intro-
duces an additional ktunable tokens per down-
stream task prepended to the input text and trained
end-to-end.
5)Prefix-Tuning (Li and Liang, 2021) prepends
task-specific trainable vectors to the input of multi-
head attention in each Transformer layer that is
attended to as virtual tokens.
6)P-Tuning (Liu et al., 2022b) employs train-
able continuous prompt embeddings in concatena-
tion with discrete prompts.
7)IAˆ3 (Liu et al., 2022a) introduces trainablevectors lwinto different components of the trans-
former which perform element-wise rescaling of
inner model activations.
Training We train all models with AdamW
(Loshchilov and Hutter, 2019) and a weight de-
cay of 0.01 on NVIDIA RTX 3090 24GB GPUs.
We use a learning rate of 2e-5, batch size of 16,
and a linear learning rate warmup over the first
10% steps with a cosine schedule for 8 epochs over
multiple runs with varied random seeds.
5 Results
Evaluation Metrics We consider two perfor-
mance metrics: (1) average per-user accuracy per
task and (2) average accuracy for all tasks.
5.1 Few/Zero-shot vs PEFT
Table 2 shows our results analyzing existing PEFT
methods in comparison to few/zero-shot prompting
techniques. From these results, we show that per-
sonalizing models is crucial to providing users with
more accurate results representative of their actual
perspectives. Notably, zero/few-shot prompting
falls short of adequately representing user view-
points compared to its trained counterparts being
outperformed on average by all methods except
for Prompt Tuning. Across all methods, results
show that Adapters performs the best outperform-
ing on 12 out of the 13 PEFT-U tasks and achieving
an overall accuracy score of 64.4% compared to
59.5% of LoRa in 2nd. The presented results un-
derscore the complexity of the PEFT-U benchmark,
revealing the challenges inherent in achieving con-
sistently high performance across diverse tasks and
Method Size #ParamsDataset
AverageHate+Abuse Sentiment Humor Sentiment
Hate
XplainGab
HateMHSTweet
EvalUHCWiki
DetoxGo
EmotionStud
EmoCockamamie EPIC SD(D) SD(QS) SD(RS)
Zero/Few-Shot (k=3) - 0 47.4 81.9 26.1 61.5 55.2 61.4 53.3 27.2 97.1 63.3 16.0 20.5 11.3 47.9
LoRA 3.8M 880K 54.9 88.6 27.4 69.5 73.4 81.0 66.3 67.7 97.2 67.9 29.4 30.7 18.9 59.5
Prefix Tuning 1.5M 370K 48.8 85.4 45.5 61.8 66.0 72.7 60.1 32.9 97.1 66.7 7.7 11.7 8.1 51.1
P-Tuning 128K 1.8M 48.7 81.9 29.2 61.3 56.8 62.3 53.8 27.6 97.0 62.8 16.6 19.6 11.1 48.4
Prompt Tuning 128K 31K 49.3 82.8 28.7 59.5 56.3 63.3 52.1 27.6 97.1 61.1 10.5 20.5 9.9 47.6
Adapters 14M 3.5M 59.0 89.1 38.9 70.5 77.5 84.0 68.4 83.7 97.2 68.5 35.3 39.0 25.6 64.4
IA^3 450K 111K 48.6 86.7 26.5 62.3 61.6 70.0 58.9 27.6 97.1 64.3 19.0 24.1 13.5 50.8
Table 2: Results of PEFT Methods on the PEFT-U Benchmark: This table shows the macro accuracy of each PEFT
method in comparison to Zero/Few-shot prompting on Flan-T5 (Chung et al., 2022).
MethodOriginal
ParamsAdjusted
ParamsOriginal
AccAcc
w/ Reduced Params
LoRA 880K 111K 69.5 66.2
Prefix Tuning 370K 111K 61.8 61.5
P-Tuning 1.6M 111K 61.7 61.7
Prompt Tuning 15K 111K 59.8 50.0
Adapters 3.5M 111K 70.5 64.2
IA^3 111K - 62.3 -
Table 3: Results on TweetEval task for PEFT-U with
equal number of trainable parameters.
datasets. While personalized fine-tuning methods
exhibit superior accuracy compared to traditional
few/zero-shot prompting techniques, the variations
in performance among different PEFT methods as
well as the performance on datasets such as Subjec-
tive Discourse and MeasuringHateSpeech indicate
that the benchmark presents a multifaceted chal-
lenge. The nuances of user personalization, model
size, and parameter tuning significantly impact the
effectiveness of these methods. This observed di-
versity in performance across methods suggests
that there is no one-size-fits-all solution, and fur-
ther investigation is imperative.
5.2 Impact of Number of Parameters
Given the performance of Adapters, we sought to
understand whether its performance was due to
the number of trainable parameters. As such, we
systematically varied the parameter count across
each method on the TweetEval Task. Notably, we
observed nuanced patterns across different PEFT
methods. As shown in table 3, with reduced pa-
rameters all methods except for P-tuning suffered
a decrease in overall performance. However, LoRa
with equal trainable parameters was able to outper-
form Adapters.
6 Related Works
Prior works have highlighted the need for user per-
spective particularly when dealing with intrinsi-
cally subjective applications where differing per-spectives are common (Mostafazadeh Davani et al.,
2022; Sang and Stanton, 2021; Geva et al., 2019;
Kanclerz et al., 2022; Welch et al., 2022). Re-
search has shown that accounting for user perspec-
tive and personalization is essential for building
robust and effective models (Mostafazadeh Davani
et al., 2022; Sang and Stanton, 2021; Geva et al.,
2019; Kanclerz et al., 2022; Welch et al., 2022).
However, despite this glaring need, existing re-
sources fail to model and cater to these differing
perspectives. When curated, NLP resources tend
to have an intrinsic bias towards the majority per-
spective due to their reliance on voting for ground
truth. As such they fail to adequately represent
diverse user preferences and individualized expres-
sions, further contributing to a lack of personaliza-
tion (Mostafazadeh Davani et al., 2022; Sang and
Stanton, 2021; Geva et al., 2019; Kanclerz et al.,
2022). Other benchmarks such as Salemi et al.
(2023) highlight the importance of personalization
LLMs, however, PEFT-U uniquely factors cases of
conflicting user perspectives when exploring per-
sonalization in addition to considering the compute
constraints.
7 Conclusion
This work addresses a critical gap in NLP concern-
ing the personalization of LLMs. While LLMs
have achieved remarkable performance in various
tasks, their generalization capabilities have pre-
dominantly followed a "one-size-fits-all" paradigm.
This approach falls short of meeting the diverse
linguistic and communicative preferences of indi-
vidual users. The PEFT-U Benchmark introduced
in this paper serves as an effort to evaluate the
personalization capabilities of LLMs across a spec-
trum of tasks. PEFT-U, presents a unique challenge
by emphasizing scenarios where identical inputs
necessitate diverse model outputs. The reported re-
sults showcase the inherent challenges posed by the
PEFT-U benchmark and advocate for the continued
exploration of effective personalization strategies.
8 Limitations
The PEFT-U Benchmark while designed to capture
diverse user perspectives, may not fully represent
the intricacies of all real-world communication sce-
narios. The dataset’s construction involved a care-
ful curation process, but the authors acknowledge
that the complexities of individual preferences and
linguistic nuances are vast and varied. In this work,
user perspective is modeled solely based on the
user’s output preferences. Factors such as age, gen-
der, and other potentially important demographics
are not considered.
In addition, the personalization methodologies
explored in this study may not encompass the entire
spectrum of potential approaches. The field of NLP
is dynamic, and emerging techniques could offer
alternative solutions to the challenges presented.
Personalization in LLMs is an evolving research
area, as such there may be relevant strategies re-
leased recently that were not covered in this work.
References
Sébastien Bubeck, Varun Chandrasekaran, Ronen El-
dan, Johannes Gehrke, Eric Horvitz, Ece Kamar, Pe-
ter Lee, Yin Tat Lee, Yuanzhi Li, Scott Lundberg,
Harsha Nori, Hamid Palangi, Marco Tulio Ribeiro,
and Yi Zhang. 2023. Sparks of artificial general in-
telligence: Early experiments with gpt-4.
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang,
Mostafa Dehghani, Siddhartha Brahma, Albert Web-
son, Shixiang Shane Gu, Zhuyun Dai, Mirac Suz-
gun, Xinyun Chen, Aakanksha Chowdhery, Sharan
Narang, Gaurav Mishra, Adams Yu, Vincent Zhao,
Yanping Huang, Andrew Dai, Hongkun Yu, Slav
Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam
Roberts, Denny Zhou, Quoc V . Le, and Jason Wei.
2022. Scaling instruction-finetuned language mod-
els.
Christopher Clarke, Matthew Hall, Gaurav Mittal,
Ye Yu, Sandra Sajeev, Jason Mars, and Mei Chen.
2023. Rule by example: Harnessing logical rules for
explainable hate speech detection. In Proceedings
of the 61st Annual Meeting of the Association for
Computational Linguistics (Volume 1: Long Papers) ,
pages 364–376, Toronto, Canada. Association for
Computational Linguistics.
Christopher Clarke, Joseph Peper, Karthik Krishna-
murthy, Walter Talamonti, Kevin Leach, Walter
Lasecki, Yiping Kang, Lingjia Tang, and Jason Mars.2022. One agent to rule them all: Towards multi-
agent conversational AI. In | Findings of the Asso-
ciation for Computational Linguistics: ACL 2022 ,
pages 3258–3267, Dublin, Ireland. Association for
Computational Linguistics.
Dorottya Demszky, Dana Movshovitz-Attias, Jeongwoo
Ko, Alan Cowen, Gaurav Nemade, and Sujith Ravi.
2020. Goemotions: A dataset of fine-grained emo-
tions.
Elisa Ferracane, Greg Durrett, Junyi Jessy Li, and Ka-
trin Erk. 2021. Did they answer? subjective acts and
intents in conversational discourse. In Proceedings
of the 2021 Conference of the North American Chap-
ter of the Association for Computational Linguistics:
Human Language Technologies , pages 1626–1644,
Online. Association for Computational Linguistics.
Simona Frenda, Alessandro Pedrani, Valerio Basile,
Soda Marem Lo, Alessandra Teresa Cignarella, Raf-
faella Panizzon, Cristina Marco, Bianca Scarlini, Vi-
viana Patti, Cristina Bosco, and Davide Bernardi.
2023. EPIC: Multi-perspective annotation of a cor-
pus of irony. In Proceedings of the 61st Annual Meet-
ing of the Association for Computational Linguis-
tics (Volume 1: Long Papers) , pages 13844–13857,
Toronto, Canada. Association for Computational Lin-
guistics.
Mor Geva, Yoav Goldberg, and Jonathan Berant. 2019.
Are we modeling the task or the annotator? an inves-
tigation of annotator bias in natural language under-
standing datasets. In Proceedings of the 2019 Confer-
ence on Empirical Methods in Natural Language Pro-
cessing and the 9th International Joint Conference
on Natural Language Processing (EMNLP-IJCNLP) ,
pages 1161–1166, Hong Kong, China. Association
for Computational Linguistics.
Limor Gultchin, Genevieve Patterson, Nancy Baym,
Nathaniel Swinger, and Adam Kalai. 2019. Humor
in word embeddings: Cockamamie gobbledegook for
nincompoops. In Proceedings of the 36th Interna-
tional Conference on Machine Learning , volume 97
ofProceedings of Machine Learning Research , pages
2474–2483. PMLR.
Tom Henighan, Jared Kaplan, Mor Katz, Mark Chen,
Christopher Hesse, Jacob Jackson, Heewoo Jun,
Tom B. Brown, Prafulla Dhariwal, Scott Gray, Chris
Hallacy, Benjamin Mann, Alec Radford, Aditya
Ramesh, Nick Ryder, Daniel M. Ziegler, John Schul-
man, Dario Amodei, and Sam McCandlish. 2020.
Scaling laws for autoregressive generative modeling.
Neil Houlsby, Andrei Giurgiu, Stanislaw Jastrzebski,
Bruna Morrone, Quentin de Laroussilhe, Andrea Ges-
mundo, Mona Attariyan, and Sylvain Gelly. 2019.
Parameter-efficient transfer learning for nlp.
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and
Weizhu Chen. 2021. Lora: Low-rank adaptation of
large language models.
Kamil Kanclerz, Marcin Gruza, Konrad Karanowski,
Julita Bielaniewicz, Piotr Milkowski, Jan Kocon, and
Przemyslaw Kazienko. 2022. What if ground truth
is subjective? personalized deep neural hate speech
detection. In Proceedings of the 1st Workshop on Per-
spectivist Approaches to NLP @LREC2022 , pages
37–45, Marseille, France. European Language Re-
sources Association.
Yiping Kang, Ashish Mahendra, Christopher Clarke,
Lingjia Tang, and Jason Mars. 2022. Towards per-
sonalized intelligence at scale.
Przemysław Kazienko, Julita Bielaniewicz, Marcin
Gruza, Kamil Kanclerz, Konrad Karanowski, Piotr
Miłkowski, and Jan Koco ´n. 2023. Human-centered
neural reasoning for subjective content processing:
Hate speech, emotions, and humor. Information Fu-
sion, 94:43–65.
Brendan Kennedy, Mohammad Atari,
Aida Mostafazadeh Davani, Leigh Yeh, Ali
Omrani, Y . Kim, Kris Coombs, Shreya Havaldar,
Gwenyth Portillo-Wightman, Elaine Gonzalez, Joe
Hoover, Aida Azatian, Aadila Hussain, A. Lara,
O G., Asmaa Al Omary, C. G. Park, C. Wang,
X Wang, Y . Zhang, and Morteza Dehghani. 2018.
The gab hate corpus: A collection of 27k posts
annotated for hate speech.
Klaus Krippendorff. 2011. Computing krippendorff’s
alpha-reliability.
Brian Lester, Rami Al-Rfou, and Noah Constant. 2021.
The power of scale for parameter-efficient prompt
tuning.
Cheng Li, Mingyang Zhang, Qiaozhu Mei, Yaqing
Wang, Spurthi Amba Hombaiah, Yi Liang, and
Michael Bendersky. 2023. Teach llms to personalize
– an approach inspired by writing education.
Xiang Lisa Li and Percy Liang. 2021. Prefix-tuning:
Optimizing continuous prompts for generation. In
Proceedings of the 59th Annual Meeting of the Asso-
ciation for Computational Linguistics and the 11th
International Joint Conference on Natural Language
Processing (Volume 1: Long Papers) , pages 4582–
4597, Online. Association for Computational Lin-
guistics.
Haokun Liu, Derek Tam, Mohammed Muqeeth, Jay Mo-
hta, Tenghao Huang, Mohit Bansal, and Colin Raffel.
2022a. Few-shot parameter-efficient fine-tuning is
better and cheaper than in-context learning.
Xiao Liu, Kaixuan Ji, Yicheng Fu, Weng Tam, Zhengx-
iao Du, Zhilin Yang, and Jie Tang. 2022b. P-tuning:
Prompt tuning can be comparable to fine-tuning
across scales and tasks. In Proceedings of the 60th
Annual Meeting of the Association for Computational
Linguistics (Volume 2: Short Papers) , pages 61–68,
Dublin, Ireland. Association for Computational Lin-
guistics.Ilya Loshchilov and Frank Hutter. 2019. Decoupled
weight decay regularization. In International Confer-
ence on Learning Representations .
Binny Mathew, Punyajoy Saha, Seid Muhie Yimam,
Chris Biemann, Pawan Goyal, and Animesh Mukher-
jee. 2022. Hatexplain: A benchmark dataset for ex-
plainable hate speech detection.
Aida Mostafazadeh Davani, Mark Díaz, and Vinodku-
mar Prabhakaran. 2022. Dealing with disagreements:
Looking beyond the majority vote in subjective an-
notations. Transactions of the Association for Com-
putational Linguistics , 10:92–110.
Anh Ngo, Agri Candri, Teddy Ferdinan, Jan Kocon,
and Wojciech Korczynski. 2022. StudEmo: A non-
aggregated review dataset for personalized emotion
recognition. In Proceedings of the 1st Workshop
on Perspectivist Approaches to NLP @LREC2022 ,
pages 46–55, Marseille, France. European Language
Resources Association.
OpenAI. 2023. Gpt-4 technical report.
Jonas Pfeiffer, Sebastian Ruder, Ivan Vuli ´c, and
Edoardo Maria Ponti. 2023. Modular deep learning.
Ilan Price, Jordan Gifford-Moore, Jory Flemming, Saul
Musker, Maayan Roichman, Guillaume Sylvain,
Nithum Thain, Lucas Dixon, and Jeffrey Sorensen.
2020. Six attributes of unhealthy conversations. In
Proceedings of the Fourth Workshop on Online Abuse
and Harms , pages 114–124, Online. Association for
Computational Linguistics.
Paul Röttger, Bertie Vidgen, Dirk Hovy, and Janet B.
Pierrehumbert. 2022. Two contrasting data annota-
tion paradigms for subjective nlp tasks.
Pratik Sachdeva, Renata Barreto, Geoff Bacon, Alexan-
der Sahn, Claudia von Vacano, and Chris Kennedy.
2022. The measuring hate speech corpus: Leverag-
ing rasch measurement theory for data perspectivism.
InProceedings of the 1st Workshop on Perspectivist
Approaches to NLP @LREC2022 , pages 83–94, Mar-
seille, France. European Language Resources Asso-
ciation.
Alireza Salemi, Sheshera Mysore, Michael Bendersky,
and Hamed Zamani. 2023. Lamp: When large lan-
guage models meet personalization.
Yisi Sang and Jeffrey Stanton. 2021. The origin and
value of disagreement among data labelers: A case
study of the individual difference in hate speech an-
notation.
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton
Ferrer, Moya Chen, Guillem Cucurull, David Esiobu,
Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller,
Cynthia Gao, Vedanuj Goswami, Naman Goyal, An-
thony Hartshorn, Saghar Hosseini, Rui Hou, Hakan
Inan, Marcin Kardas, Viktor Kerkez, Madian Khabsa,
Isabel Kloumann, Artem Korenev, Punit Singh Koura,
Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Di-
ana Liskovich, Yinghai Lu, Yuning Mao, Xavier Mar-
tinet, Todor Mihaylov, Pushkar Mishra, Igor Moly-
bog, Yixin Nie, Andrew Poulton, Jeremy Reizen-
stein, Rashi Rungta, Kalyan Saladi, Alan Schelten,
Ruan Silva, Eric Michael Smith, Ranjan Subrama-
nian, Xiaoqing Ellen Tan, Binh Tang, Ross Tay-
lor, Adina Williams, Jian Xiang Kuan, Puxin Xu,
Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan,
Melanie Kambadur, Sharan Narang, Aurelien Ro-
driguez, Robert Stojnic, Sergey Edunov, and Thomas
Scialom. 2023. Llama 2: Open foundation and fine-
tuned chat models.
Charles Welch, Chenxi Gu, Jonathan K. Kummerfeld,
Veronica Perez-Rosas, and Rada Mihalcea. 2022.
Leveraging similar users for personalized language
modeling with limited data. In Proceedings of the
60th Annual Meeting of the Association for Compu-
tational Linguistics (Volume 1: Long Papers) , pages
1742–1752, Dublin, Ireland. Association for Compu-
tational Linguistics.
Ellery Wulczyn, Nithum Thain, and Lucas Dixon. 2017.
Ex machina: Personal attacks seen at scale.
Saizheng Zhang, Emily Dinan, Jack Urbanek, Arthur
Szlam, Douwe Kiela, and Jason Weston. 2018. Per-
sonalizing dialogue agents: I have a dog, do you
have pets too? In Proceedings of the 56th Annual
Meeting of the Association for Computational Lin-
guistics (Volume 1: Long Papers) , pages 2204–2213,
Melbourne, Australia. Association for Computational
Linguistics.
A Additional Dataset Details
In this section, we detail the datasets in our PEFT-U
benchmark, including dataset construction, repre-
sentative samples, and task instructions.
A.1 Dataset Details & Construction
We include datasets in various domains, including:
•HateXplain (Mathew et al., 2022) contains
posts on social media. Each post is classified
into 3 classes: hate, offensive, or normal. The
dataset additionally contained annotations for
the hate speech target community and the ra-
tionales. We consider the post texts and the
classification labels only.
•GabHate (Kennedy et al., 2018) has 28K
posts from the social media platform Gab.
Each post is annotated using a hierarchical
coding typology of hate-based rhetoric, with
hierarchical labels indicating dehumanizing
and violent speech, vulgarity and offensivelanguage, and targeted groups. We only con-
sider the top-level binary classification on hate
speech.
•MeasuringHateSpeech (Sachdeva et al.,
2022) contains 50K social media comments
from various platforms. They are labeled
by a large number (11K) of Crowdsource
workers on Amazon Mechanical Turk2. Each
comment is annotated with 10 ordinal la-
bels: sentiment, disrespect, insult, attack-
ing/defending, humiliation, inferior/superior
status, dehumanization, violence, genocide,
and a 3-valued hate speech benchmark label.
This dataset adjusts for annotators’ perspec-
tives by aggregating the labels via faceted
Rasch measurement theory (RMT). We use
the comment text and the 3-valued hate speech
label only.
•TweetEval (Röttger et al., 2022) comprises
200 Twitter posts, each annotated by 20 an-
notator groups of 3. Annotators were given
a short definition of hate speech only, which
encourages the subjectivity of annotators. The
labels are binary classifications of hatefulness.
•UnhealthyConversations (Price et al., 2020)
consists of 44K comments labeled by crowd-
source workers as either “healthy” or “un-
healthy”. It also contains six potentially un-
healthy sub-attributes: (1) hostile; (2) antag-
onistic, insulting, provocative, or trolling; (3)
dismissive; (4) condescending or patronizing;
(5) sarcastic; and/or (6) an unfair generaliza-
tion. We only consider the top-level binary
classification of healthy conversations.
•WikiDetox Aggression (Wulczyn et al., 2017)
is a large collection of 100K online comments
to English Wikipedia where crowd-source an-
notators label whether each comment is a per-
sonal attack.
•GoEmotion (Demszky et al., 2020) is a large
annotated dataset of 58k English Reddit com-
ments, labeled for 27 emotion categories or
Neutral. We reduce the emotion categories
into 6 coarse categories with Ekman-style
grouping. Each comment can have multiple
emotion labels. We drop texts with no labels
annotated and texts labeled as ‘neutral’.
•StudEmo (Ngo et al., 2022) comprises 5K
2https://www.mturk.com
Dataset # Unique
TextsLabels
Domain Name
Hate+AbuseHateXplain 20K [hateful, offensive, normal]
GabHate 28K [Hateful, Non-hateful]
Measuring
HateSpeech50K Hate speech scale: [0, 1, 2]
TweetEval 200 [Hateful, Non-hateful]
Unhealthy
Conversations44K [healthy, unhealthy]
WikiDetox
Aggression100K [Aggressive, Normal]
SentimentGoEmotion 58K [anger, disgust, fear, joy, sadness, surprise]
StudEmo 5K[joy, trust, anticipation, surprise, fear, sadness, anger,
disgust, valence, arousal]
Subjective Discourse
(response)
1K[answer+direct, answer+over-answer, shift+correct,
shift+dodge, can’t answer+honest, can’t answer+lying]
Subjective Discourse
(question sentiment)[very-negative, negative, somewhat-negative, neutral,
somewhat-positive, positive, very-positive]
Subjective Discourse
(response sentiment)[very-negative, negative, somewhat-negative, neutral,
somewhat-positive, positive, very-positive]
HumorCockamamie 120K [humorous, not-humorous]
EPIC 3K [Ironic, Non-ironic]
Table 4: Additional details on the PEFT-U Benchmark.
customer reviews annotated by 25 people for
10 emotion dimensions: eight emotion dimen-
sions from Plutchik’s model plus valence and
arousal. Valence has an intensity range of
[−3,+3] whereas each remaining category
has a range of [0,3]. We treat the problem
as multi-class classification where we keep
categories with intensity value ≥1as positive
labels.
•Subjective Discourse (Ferracane et al., 2021)
consists of 1,000 question-response pairs from
20 witness testimonials in U.S. congressional
hearings. The study collects subjective in-
terpretations from the crowdsource workers
about the conversations on three aspects: the
question, the response, and an explanation.
In particular, the annotator provides subjec-
tive assessments of the conversation acts and
communicative intents of the responses, form-
ing 6 response labels. Each annotator also
rates their sentiment toward the politicians
and the witness on a 7-point scale. We lever-
age the response labels, and the sentiments
toward the politicians and witnesses to form
3 dataset versions. To construct the text part,
we join (question speaker detail, question text,response speaker detail, response text) by new-
lines.
•Cockamamie (Gultchin et al., 2019) includes
120K words and phrases from GNEWS. The
words and phrases are annotated by crowd
workers fluent in English on whether they are
humorous. 1,500 words are further annotated
on six binary humor features. We leverage
the words and the initial binary “humorous”
labels only.
•EPIC (Frenda et al., 2023) is made of 3K
short social media (post, reply) pairs collected
from Twitter and Reddit across five regional
varieties of English. Annotators from five dif-
ferent counties were asked to provide a binary
label (either Irony ornot-Irony ) for the Re-
plytext given the context provided by Post.
We template the (Post, Reply) pairs by adding
“message” and “reply” prefixes.
We summarize additional details for each dataset
in Table 4. We split each user’s data into
train/dev/test sets by 80/10/10 splits.
A.2 Representative Samples
In this section, we show representative samples
for each dataset where different user perspectives
result in different labels for the same text input.
Warning: Offensive content is inevitable for
datasets in the Hate+Abuse domain.
A.2.1 Representative Sample for HateXplain
Text. right definitely not going back to the fag
hag thing it was fun for a bit in my <number> but
outrageously gay people are just too high strung
for me it back to that reason i can not be a lesbian
Labels .
- normal
- hatespeech
- offensive
A.2.2 Representative Sample for
MeasuringHateSpeech
Text. @L1LTR4P fucking losers wetbacks #Sor-
ryNotSorry
Labels .
- 0
- 1
- 2
A.2.3 Representative Sample for GabHate
Text. #Breaking: Claiming bias against conserva-
tives, @FreedomWatchUSA has filed a class action
lawsuit against Google, Facebook, Instagram, Twit-
ter, and Apple.
Labels .
- Non-hateful
- Hateful
A.2.4 Representative Sample for TweetEval
Text. [USER] fuck Brett Farve redneck ass, he
stuckup he don’t give a damn lol he be on campus
acting like he the shit
Labels .
- Hateful
- Non-hateful
A.2.5 Representative Sample for Unhealthy
Conversations
Text. They are poor because they are reliant on the
drug trade and reliant on the drug trade because
they are then poor. That cycle can be broken.
Labels .
- healthy
- unhealthyA.2.6 Representative Sample for WikiDetox
Aggression
Text. == Dougbiznatch again! ==
Hey I’m back. Gonna vandalize all day and no one
can stop me! As you can tell I can’t be stopped by
banning. I’ll be seeing alo tof you and the rest of
the blacklisted admins for the next couple of weeks
=P
Dougbiznatch
Labels .
- Aggressive
- Normal
A.2.7 Representative Sample for GoEmotion
Text. Is he dead now from a tragic drowning acci-
dent? Asking for a friend.
Labels .
- [sadness]
- [surprise]
A.2.8 Representative Sample for StudEmo
Text. We got to the Cycle On Hostel by chance
in the middle of the night. There wasn’t a single
place available in other places. . . ...and it’s very
good that we didn’t get to another place! First of
all, great service: people who are open to others,
nice and smiling, who help us with every time of
day and night. Spacious hostel, rooms and bath-
rooms are clean. And besides all that - the location
- nothing to add, nothing to take away. Literally 5
minutes away from Neptune and at the same time
the building is situated in such a place that at night
it is quiet despite such a short distance from the
busiest street where it is full of tourists and chil-
dren. If we will still have a chance to spend the
night in Gdansk, we will surely come to Cycle On
again. With a clear conscience I recommend
Labels .
- [trust, anticipation, valence, arousal]
- [joy, trust, valence, arousal]
A.2.9 Representative Sample for Subjective
Discourse (response)
Text. politician: JIM JORDAN, Ohio
Okay. Well, this is put out by the Exempt Orga-
nizations Division, same division where all these
problems took place over the last three years. It
came out, again, just five days after the comment
period on the proposed rule ended at the end of
February, and I want to just highlight a few of the
questions that are asked. So there is a category that
says what if the IRS needs more information about
your (c)(4) application? New sample questions. So
if we could put them up side-by-side. Now, the
first slide are the targeted questions that TIGTA
said were inappropriate and that you agree are inap-
propriate, Judith Kendall agreed are inappropriate.
Those are those questions. And now, just five days
after the proposed rule comment period ends, you
issue a newsletter from the Exempt Organizations
Division highlighting the new questions you are
going to ask, and I just want to look how similar
the two questions are. Let’s just take the second cat-
egory, whether an officer or director, etcetera, has
run or will run for public office. The new question
says this: Do you support a candidate for public of-
fice who is one of your founders, officers, or board
members? It is basically the same. This reminds
me of when I was in grade school and the teachers
told us you shouldn’t plagiarize, so you change
a few words and basically plagiarize. This is the
same thing. So here is what I don’t understand. If
you are trying to comply with the TIGTA report, if
the new (c)(4) rule is a way to deal with what the
audit said and not as what I believe is a continua-
tion of the project Lois Lerner started, why are you
asking the same darn questions?
witness: The Hon. John Koskinen, Commissioner,
Internal Revenue Service
As I noted, I haven’t seen that and can’t read it on
the chart. I would be delighted to sit down and
go over all of those questions with you and with
the exempt organizations. All of the TIGTA report
didn’t blanket say you should never ask questions
about this. Thank you for the chart.
Labels .
- can’t answer+lying
- can’t answer+honest
- shift+dodge
A.2.10 Representative Sample for Subjective
Discourse (question sentiment)
Text. politician: RANDY NEUGEBAUER, Texas
And, as you’re aware, Section 972 of Dodd-Frank
requires an issuer of securities to disclose the an-
nual proxy statement, the reason why the issuer
has chosen to allow the same person to serve as
the board chairman and the CEO. This year, Wells
states that your dual role is a result of your ex-tensive experience and knowledge regarding the
company and provides the most efficient leadership
of the board and the company. Mr. Stumpf, do you
think it’s a good idea for the same person to serve
as both chairman of the board and CEO?
witness: Stumpf, John G., Chairman and Chief
Executive Officer, Wells Fargo and Company
Thank you, Congressman, for that question. In
our company, we have 14 outside directors. We
have a lead director. All directors are New York
Stock Exchange-independent, by their standards.
I am not a member of any standing committee of
that board. The independent directors and the lead
director help set the agenda for the boards. They
always have meetings that are in executive session
without me. And as you probably read about what
happened this weekend–because we filed an 8-K
yesterday about actions that they took as an inde-
pendent board, and I was not part of that. So the
board acts quite independently.
Labels .
- negative
- neutral
- somewhat-negative
- somewhat-positive
A.2.11 Representative Sample for Subjective
Discourse (response sentiment)
Text. politician: JERROLD NADLER, New York,
Chairman
It is our understanding that at least one briefing
occurred between December–between your deci-
sion not to recuse yourself on December 19th and
6 days later, Christmas day. Is that correct? Simple
enough question, yes or no.
witness: Matthew G. Whitaker, Acting Attorney
General, U.S. Department of Justice Oral Testi-
mony
Mr. Chairman, I, again, what is the basis for
your question? You are saying that it is your
understanding—-
Labels .
- negative
- neutral
- somewhat-negative
- somewhat-positive
A.2.12 Representative Sample for
Cockamamie
Text. judokas
Labels .
- humorous
- not-humorous
A.2.13 Representative Sample for EPIC
Text. message: “Because the last generation was
Gen. Z and there’s no where to go past that, so we
gotta start from the beginning.”
reply: “but we should have just named the first
generation “Alpha” instead of doing it now”
Labels .
- Ironic
- Non-ironic
A.3 Task Instructions
In this section, we show the task instructions
prepended to prompts in training and inference for
each dataset.
A.3.1 Instruction for HateXplain
Please review the following text and indicate if it
has the presence of hate speech or is offensive in
nature. Respond ‘hatespeech’ if the text contains
hate speech, ‘offensive’ if the text does not contain
hate speech but is offensive and ‘normal’ if the text
is neither offensive nor contains hate speech.
A.3.2 Instruction for MeasuringHateSpeech
On a scale of 0-2 rate the level of hatespeech con-
tained in the following text. Respond with ‘0’ if
the text does not contain hate speech, ‘1’ if the
text contains some hate speech, and ‘2’ if the text
contains a lot of hate speech.
A.3.3 Instruction for GabHate
Please review the following text and indicate if it
has the presence of hate speech. Respond ‘Hateful’
if the text contains hate speech and ‘Non-hateful’
if the text does not contain hate speech.
A.3.4 Instruction for TweetEval
Please review the following text and indicate if it
has the presence of hate speech. Respond ‘Hateful’
if the text contains hate speech and ‘Non-hateful’
if the text does not contain hate speech.
A.3.5 Instruction for Unhealthy
Conversations
Please review the following text and indicated if it
is ‘healthy’ or ‘unhealthy’. Respond ‘healthy’ ifthe text is healthy and ‘unhealthy’ if the text can
be considered hostile, antagonistic, condescending,
dismissive or an unfair generalization.
A.3.6 Instruction for WikiDetox Aggression
Please review the following text and indicate if it
has the presence of malicious remark to a person
or group. Respond ‘Aggressive’ if the text contains
a personal attack and ‘Normal’ if the text does not
contain a personal attack.
A.3.7 Instruction for GoEmotion
Please analyze the following text and assign one
or more appropriate emotion labels. Emotion la-
bels include happiness, sadness, anger, surprise,
joy, fear, disgust. You can select one or multiple
emotion labels that best capture the emotional con-
tent of the text. Respond with the emotion labels
separated by a comma.
A.3.8 Instruction for StudEmo
Please analyze the following text and assign one
or more appropriate emotion labels. Emotion la-
bels include joy, trust, anticipation, surprise, fear,
sadness, disgust, anger, valence, and arousal. You
can select one or multiple emotion labels that best
capture the emotional content of the text. Respond
with the emotion labels separated by a comma.
A.3.9 Instruction for Subjective Discourse
(response)
Please analyze the following text and indicate how
the witness responded to the question. Respond
with ‘answer’ if they answered the question reason-
ably, ‘cant-answer-lying’ if they could not answer
and are lying, ‘cant-answer-sincere’ if they could
not answer but are honest about it, ‘shift-dodge’ if
they shifted the topic with the intent of dodging the
question, ‘answer_overans-sway’ if they over an-
swered the question with the intention of swaying
or ‘shift-correct’ if they shifted the topic with the
intention of clarifying the question.
A.3.10 Instruction for Subjective Discourse
(question sentiment)
Please analyze the following text and rate your
sentiment towards the questioners. Sentiment la-
bels include ‘somewhat-positive’, ‘positive’, ‘very-
positive’, ‘somewhat-negative’, ‘very-negative’,
‘neutral’ and ‘negative’. Respond with the sen-
timent label that best captures your sentiment to-
wards the questioners.
A.3.11 Instruction for Subjective Discourse
(response sentiment)
Please analyze the following text and rate your
sentiment towards the witness. Sentiment la-
bels include ‘somewhat-positive’, ‘positive’, ‘very-
positive’, ‘somewhat-negative’, ‘very-negative’,
‘neutral’ and ‘negative’. Respond with the sen-
timent label that best captures your sentiment to-
wards the witness.
A.3.12 Instruction for Cockamamie
Please rate whether the following text is funny or
not funny. Respond ‘yes’ if you think the text is
funny and ‘no’ if you think the text is not funny.
A.3.13 Instruction for EPIC
Irony is a figurative language device that conveys
that opposite of literal meaning, profiling inten-
tionally a secondary or extended meaning. Please
review the following message and reply and indi-
cate if it has the presence of irony. Respond ‘Ironic’
if the reply if you think the reply is ironic and ‘Non-
ironic’ if you think the reply is not ironic. | Section not found | Section not found | Section not found | Limitations
The PEFT-U Benchmark while designed to capture
diverse user perspectives, may not fully represent
the intricacies of all real-world communication sce-
narios. The dataset’s construction involved a care-
ful curation process, but the authors acknowledge
that the complexities of individual p | Section not found | Conclusion
This work addresses a critical gap in NLP concern-
ing the personalization of LLMs. While LLMs
have achieved remarkable performance in various
tasks, their generalization capabilities have pre-
dominantly followed a "one-size-fits-all" paradigm.
This approach falls short of meeting the diverse
linguistic and communicative p | Section not found | Section not found | references of users can potentially differ for
the same input. Using PEFT-U, we explore the
challenge of efficiently personalizing LLMs to
accommodate user-specific preferences in the
context of diverse user-centered tasks.
1 Introduction
Large Language Models (LLMs) have shown
tremendous capability in performing complex tasks
such as reasoning, summarization, creative writing,
etc. Through the scaling of these models, both
in size ( >1B parameters) and data ( >1 Trillion
tokens) these models have achieved remarkable
performance on a wide range of natural language
understanding and generation tasks (Touvron et al.,
2023; Henighan et al., 2020). However, even as
the generalization capability of LLMs has grown,
one crucial dimension that has been understudied is
the personalization of these models (Salemi et al.,
2023; Kazienko et al., 2023).At its core, personalization is about tailoring AI-
driven interactions to the individual preferences,
needs, and idiosyncrasies of each user (Salemi
et al., 2023; Welch et al., 2022; Clarke et al., 2023;
Kang et al., 2022). In many real-world scenar-
ios, users have unique preferences, contexts, and
expectations, which are currently incapable of be-
ing effectively accommodated by the generalized
LLMs available today. These traditional LLMs
have predominantly adhered to a "one-size-fits-
all" approach (Touvron et al., 2023; Clarke et al.,
2022; OpenAI, 2023; Bubeck et al., 2023), offer-
ing a single, uniform model capable of serving all
users and tasks alike. While this approach is un-
doubtedly valuable in many scenarios, it falls short
when it comes to accommodating the rich tapestry
of human diversity where people are not uniform,
and their linguistic and communicative preferences
vary widely (Li et al., 2023; Zhang et al., 2018).
Existing works in NLP have highlighted the need
for user perspective in language modeling partic-
ularly when dealing with intrinsically subjective
applications such as Hate Speech Detection and
Sentiment Analysis where differing perspectives
are common (Mostafazadeh Davani et al., 2022;
Sang and Stanton, 2021; Geva et al., 2019; Kan-
clerz et al., 2022; Welch et al., 2022). Research
has shown that accounting for user perspective
and personalization is essential for building robust
and effective models (Mostafazadeh Davani et al.,
2022; Sang and Stanton, 2021; Geva et al., 2019;
Kanclerz et al., 2022; Welch et al., 2022). How-
ever, despite this glaring need, existing resources
fail to model and cater to these differing perspec-
tives. When curated, NLP resources tend to have
an intrinsic bias towards the majority perspective
due to their reliance on voting for ground truth.
As such they fail to adequately represent diverse
user preferences and individualized expressions,
further contributing to a lack of personalization
(Mostafazadeh Davani et al., 2022; Sang and Stan-arXiv:2407.18078v1 [cs.CL] 25 Jul 2024
ton, 2021; Geva et al., 2019; Kanclerz et al., 2022).
To combat these challenges we introduce the
PEFT-U Benchmark . PEFT-U consists of over
13+ personalized tasks and 15k+ users across do-
mains such as Hate Speech, Sentiment/Emotion,
and Humor. In contrast to other resources, the
PEFT-U benchmark uniquely tests complex scenar-
ios where LLMs are faced with differing user per-
spectives even when facing the same input. To the
best of our knowledge, this benchmark is the first
of its kind to focus on modeling user preferences
in NLP with an emphasis on identical inputs that
require different model outputs depending upon
the user. Using PEFT-U we explore a range of
strategies for efficiently compartmentalizing user
perspectives. In particular, we implement and em-
pirically analyze a series of personalized prompting
approaches (non-parametric) vs tuning and com-
partmentalizing user-level knowledge (parametric)
for personalized tasks showing that personalized
models are crucial to providing users with more
accurate results representative of their actual per-
spectives. We publicly release our code, models,
and benchmark1.
2 PEFT-U Benchmark
The PEFT-U benchmark aims to assess the effi-
cacy of language models in producing personalized
outputs based on user-specific information.
Data Collection To generate high-quality data
samples representative of differing user perspec-
tives we focus on curating subjective problems
where the model is forced to respect the user’s
points of view e.g. Hate Speech Detection. Typi-
cally NLP resources for these problem areas em-
ploy an annotation process where correctness is
determined via majority vote and outliers are dis-
carded. This often results in the overlooking of
the subtleties of the user’s perspective, ultimately
leading to potential group biases and inaccuracies
in the data. In contrast, we reconstruct these data
sources framing individual annotators as distinct
users to capture these important nuances. To avoid
the possible influence of noisy/bad annotators we
take into account their contribution level to the an-
notation process and discard low-quality users. Ad-
ditionally, we discard users with less than n= 10
samples in their training and test sets respectively.
1https://github.com/ChrisIsKing/
Parameter-Efficient-PersonalizationAs shown in table 1 PEFT-U consists of 13+ person-
alized tasks and 15k+ users with each task gaining
a maximum Krippendorff’s alpha ( α) of 0.5 (Krip-
pendorff, 2011) across the domains of Hate/Abuse,
Humor, and Emotion/Sentiment as shown in ta-
ble 1. For each dataset, we construct a unique
instruction-style prompt to guide the LLM to gen-
erate the desired output. More details on each of
the specific datasets, our reconstruction process,
and their prompts are provided in | Appendix A.
User Disagreement As shown in table 1, we
enforce that all personalized tasks must obtain a
Krippendorff’s alpha score of (α≤0.5). This re-
quirement is created to assess the ability to capture
differing user perspectives even when facing the
same input. Krippendorff’s alpha (α)is a reliabil-
ity coefficient developed to measure the agreement
among annotators. When used in data curation,
data is usually considered reliable when (α≥0.8).
By enforcing all datasets to have low agreement
scores, we force the model to rely on respective
user information to generate its output.
3 Modularity + Personalization
When exploring the problem of personalization,
one possible solution would be the allocation of a
dedicated LLM for each user. However, deploy-
ing a separate personalized model for each user
would incur significant compute costs in produc-
tion. In addition, the balance between embedding
generalized and personalized knowledge in these
models remains unclear. Thus providing such a
solution is prohibitive in this era of large language
models. Recent works in Modular Deep Learning
(Liu et al., 2022a; Pfeiffer et al., 2023; Hu et al.,
2021; Houlsby et al., 2019), seek to optimize and
further tune these LLMs without having to update
all the model parameters. These methods typically
introduce a small number of additional parame-
ters and update these parameters in a model while
freezing the remaining weights, thus limiting the
computational resources required. This is often
done to enable multi-task learning or to introduce
new updates in the training data without the need
for training from scratch.
In our experiment setting, we shift this paradigm
from multi-task learning to multi-user learning fo-
cusing on the research question of "How to ef-
ficiently personalize large language models for
subjective tasks?" . As such, we empirically an-
alyze personalized prompting approaches (non-
Dataset
# UsersAvg # examples
per userAvg # users
per textKrippendorff’s
AlphaDomain Name
Hate+AbuseHateXplain (Mathew et al., 2022) 253 238.9 3.0 0.46
GabHate (Kennedy et al., 2018) 18 4807.16 3.12 0.24
MeasuringHateSpeech (Sachdeva et al., 2022) 7912 17.13 3.42 0.47
TweetEval (Röttger et al., 2022) 20 200.0 200.0 0.14
UnhealthyConversations (Price et al., 2020) 588 386.77 4.64 0.28
WikiDetox Aggression (Wulczyn et al., 2017) 4053 336.84 11.78 0.43
SentimentGoEmotion (Demszky et al., 2020) 82 1859.95 2.83 0.44
StudEmo (Ngo et al., 2022) 25 296.44 1.43 0.18
Subjective Discourse (Ferracane et al., 2021)∗68 9.26 6.20 0.50/0.01/0.01
HumorCockamamie (Gultchin et al., 2019) 1878 489.33 7.65 0.08
EPIC (Frenda et al., 2023) 74 191.51 4.72 0.19
Table 1: PEFT-U Benchmark: We design a large-scale benchmark for personalized model training and evaluation
consisting of 13+ personalized tasks across 15k+ users with each task obtaining a Krippendorff’s alpha ( α)<0.5
per task.∗Subjective Discourse consists of 3 different sentiment tasks.
parametric) vs efficiently tuning and compartmen-
talizing user-level knowledge (parametric) for per-
sonalized tasks.
4 Benchmark Evaluation
To quantify the challenge the PEFT-U benchmark
presents, we evaluate the performance of a range of
parameter-efficient methods compared to zero/few-
shot prompting approaches.
Methods We implement and evaluate 7 differ-
ent parameter-efficient methods for personalizing
LLMs using Flan-T5 (Chung et al., 2022). These
methods consist of:
1)Zero-shot/Few-shot Prompting : Using k=
3random samples of user data we construct an
instruction-style prompt for inference.
2)LoRa (Hu et al., 2021): injects trainable
rank decomposition matrices into each layer of the
Transformer architecture.
3)Adapters (Houlsby et al., 2019) add a train-
able bottleneck layer after the feedforward network
in each Transformer layer.
4)Prompt Tuning (Lester et al., 2021) intro-
duces an additional ktunable tokens per down-
stream task prepended to the input text and trained
end-to-end.
5)Prefix-Tuning (Li and Liang, 2021) prepends
task-specific trainable vectors to the input of multi-
head attention in each Transformer layer that is
attended to as virtual tokens.
6)P-Tuning (Liu et al., 2022b) employs train-
able continuous prompt embeddings in concatena-
tion with discrete prompts.
7)IAˆ3 (Liu et al., 2022a) introduces trainablevectors lwinto different components of the trans-
former which perform element-wise rescaling of
inner model activations.
Training We train all models with AdamW
(Loshchilov and Hutter, 2019) and a weight de-
cay of 0.01 on NVIDIA RTX 3090 24GB GPUs.
We use a learning rate of 2e-5, batch size of 16,
and a linear learning rate warmup over the first
10% steps with a cosine schedule for 8 epochs over
multiple runs with varied random seeds.
5 Results
Evaluation Metrics We consider two perfor-
mance metrics: (1) average per-user accuracy per
task and (2) average accuracy for all tasks.
5.1 Few/Zero-shot vs PEFT
Table 2 shows our results analyzing existing PEFT
methods in comparison to few/zero-shot prompting
techniques. From these results, we show that per-
sonalizing models is crucial to providing users with
more accurate results representative of their actual
perspectives. Notably, zero/few-shot prompting
falls short of adequately representing user view-
points compared to its trained counterparts being
outperformed on average by all methods except
for Prompt Tuning. Across all methods, results
show that Adapters performs the best outperform-
ing on 12 out of the 13 PEFT-U tasks and achieving
an overall accuracy score of 64.4% compared to
59.5% of LoRa in 2nd. The presented results un-
derscore the complexity of the PEFT-U benchmark,
revealing the challenges inherent in achieving con-
sistently high performance across diverse tasks and
Method Size #ParamsDataset
AverageHate+Abuse Sentiment Humor Sentiment
Hate
XplainGab
HateMHSTweet
EvalUHCWiki
DetoxGo
EmotionStud
EmoCockamamie EPIC SD(D) SD(QS) SD(RS)
Zero/Few-Shot (k=3) - 0 47.4 81.9 26.1 61.5 55.2 61.4 53.3 27.2 97.1 63.3 16.0 20.5 11.3 47.9
LoRA 3.8M 880K 54.9 88.6 27.4 69.5 73.4 81.0 66.3 67.7 97.2 67.9 29.4 30.7 18.9 59.5
Prefix Tuning 1.5M 370K 48.8 85.4 45.5 61.8 66.0 72.7 60.1 32.9 97.1 66.7 7.7 11.7 8.1 51.1
P-Tuning 128K 1.8M 48.7 81.9 29.2 61.3 56.8 62.3 53.8 27.6 97.0 62.8 16.6 19.6 11.1 48.4
Prompt Tuning 128K 31K 49.3 82.8 28.7 59.5 56.3 63.3 52.1 27.6 97.1 61.1 10.5 20.5 9.9 47.6
Adapters 14M 3.5M 59.0 89.1 38.9 70.5 77.5 84.0 68.4 83.7 97.2 68.5 35.3 39.0 25.6 64.4
IA^3 450K 111K 48.6 86.7 26.5 62.3 61.6 70.0 58.9 27.6 97.1 64.3 19.0 24.1 13.5 50.8
Table 2: Results of PEFT Methods on the PEFT-U Benchmark: This table shows the macro accuracy of each PEFT
method in comparison to Zero/Few-shot prompting on Flan-T5 (Chung et al., 2022).
MethodOriginal
ParamsAdjusted
ParamsOriginal
AccAcc
w/ Reduced Params
LoRA 880K 111K 69.5 66.2
Prefix Tuning 370K 111K 61.8 61.5
P-Tuning 1.6M 111K 61.7 61.7
Prompt Tuning 15K 111K 59.8 50.0
Adapters 3.5M 111K 70.5 64.2
IA^3 111K - 62.3 -
Table 3: Results on TweetEval task for PEFT-U with
equal number of trainable parameters.
datasets. While personalized fine-tuning methods
exhibit superior accuracy compared to traditional
few/zero-shot prompting techniques, the variations
in performance among different PEFT methods as
well as the performance on datasets such as Subjec-
tive Discourse and MeasuringHateSpeech indicate
that the benchmark presents a multifaceted chal-
lenge. The nuances of user personalization, model
size, and parameter tuning significantly impact the
effectiveness of these methods. This observed di-
versity in performance across methods suggests
that there is no one-size-fits-all solution, and fur-
ther investigation is imperative.
5.2 Impact of Number of Parameters
Given the performance of Adapters, we sought to
understand whether its performance was due to
the number of trainable parameters. As such, we
systematically varied the parameter count across
each method on the TweetEval Task. Notably, we
observed nuanced patterns across different PEFT
methods. As shown in table 3, with reduced pa-
rameters all methods except for P-tuning suffered
a decrease in overall performance. However, LoRa
with equal trainable parameters was able to outper-
form Adapters.
6 Related Works
Prior works have highlighted the need for user per-
spective particularly when dealing with intrinsi-
cally subjective applications where differing per-spectives are common (Mostafazadeh Davani et al.,
2022; Sang and Stanton, 2021; Geva et al., 2019;
Kanclerz et al., 2022; Welch et al., 2022). Re-
search has shown that accounting for user perspec-
tive and personalization is essential for building
robust and effective models (Mostafazadeh Davani
et al., 2022; Sang and Stanton, 2021; Geva et al.,
2019; Kanclerz et al., 2022; Welch et al., 2022).
However, despite this glaring need, existing re-
sources fail to model and cater to these differing
perspectives. When curated, NLP resources tend
to have an intrinsic bias towards the majority per-
spective due to their reliance on voting for ground
truth. As such they fail to adequately represent
diverse user preferences and individualized expres-
sions, further contributing to a lack of personaliza-
tion (Mostafazadeh Davani et al., 2022; Sang and
Stanton, 2021; Geva et al., 2019; Kanclerz et al.,
2022). Other benchmarks such as Salemi et al.
(2023) highlight the importance of personalization
LLMs, however, PEFT-U uniquely factors cases of
conflicting user perspectives when exploring per-
sonalization in addition to considering the compute
constraints.
7 Conclusion
This work addresses a critical gap in NLP concern-
ing the personalization of LLMs. While LLMs
have achieved remarkable performance in various
tasks, their generalization capabilities have pre-
dominantly followed a "one-size-fits-all" paradigm.
This approach falls short of meeting the diverse
linguistic and communicative preferences of indi-
vidual users. The PEFT-U Benchmark introduced
in this paper serves as an effort to evaluate the
personalization capabilities of LLMs across a spec-
trum of tasks. PEFT-U, presents a unique challenge
by emphasizing scenarios where identical inputs
necessitate diverse model outputs. The reported re-
sults showcase the inherent challenges posed by the
PEFT-U benchmark and advocate for the continued
exploration of effective personalization strategies.
8 Limitations
The PEFT-U Benchmark while designed to capture
diverse user perspectives, may not fully represent
the intricacies of all real-world communication sce-
narios. The dataset’s construction involved a care-
ful curation process, but the authors acknowledge
that the complexities of individual preferences and
linguistic nuances are vast and varied. In this work,
user perspective is modeled solely based on the
user’s output preferences. Factors such as age, gen-
der, and other potentially important demographics
are not considered.
In addition, the personalization methodologies
explored in this study may not encompass the entire
spectrum of potential approaches. The field of NLP
is dynamic, and emerging techniques could offer
alternative solutions to the challenges presented.
Personalization in LLMs is an evolving research
area, as such there may be relevant strategies re-
leased recently that were not covered in this work.
References
Sébastien Bubeck, Varun Chandrasekaran, Ronen El-
dan, Johannes Gehrke, Eric Horvitz, Ece Kamar, Pe-
ter Lee, Yin Tat Lee, Yuanzhi Li, Scott Lundberg,
Harsha Nori, Hamid Palangi, Marco Tulio Ribeiro,
and Yi Zhang. 2023. Sparks of artificial general in-
telligence: Early experiments with gpt-4.
Hyung Won Chung, Le Hou, Shayne Longpre, Barret
Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang,
Mostafa Dehghani, Siddhartha Brahma, Albert Web-
son, Shixiang Shane Gu, Zhuyun Dai, Mirac Suz-
gun, Xinyun Chen, Aakanksha Chowdhery, Sharan
Narang, Gaurav Mishra, Adams Yu, Vincent Zhao,
Yanping Huang, Andrew Dai, Hongkun Yu, Slav
Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam
Roberts, Denny Zhou, Quoc V . Le, and Jason Wei.
2022. Scaling instruction-finetuned language mod-
els.
Christopher Clarke, Matthew Hall, Gaurav Mittal,
Ye Yu, Sandra Sajeev, Jason Mars, and Mei Chen.
2023. Rule by example: Harnessing logical rules for
explainable hate speech detection. In Proceedings
of the 61st Annual Meeting of the Association for
Computational Linguistics (Volume 1: Long Papers) ,
pages 364–376, Toronto, Canada. Association for
Computational Linguistics.
Christopher Clarke, Joseph Peper, Karthik Krishna-
murthy, Walter Talamonti, Kevin Leach, Walter
Lasecki, Yiping Kang, Lingjia Tang, and Jason Mars.2022. One agent to rule them all: Towards multi-
agent conversational AI. In Findings of the Asso-
ciation for Computational Linguistics: ACL 2022 ,
pages 3258–3267, Dublin, Ireland. Association for
Computational Linguistics.
Dorottya Demszky, Dana Movshovitz-Attias, Jeongwoo
Ko, Alan Cowen, Gaurav Nemade, and Sujith Ravi.
2020. Goemotions: A dataset of fine-grained emo-
tions.
Elisa Ferracane, Greg Durrett, Junyi Jessy Li, and Ka-
trin Erk. 2021. Did they answer? subjective acts and
intents in conversational discourse. In Proceedings
of the 2021 Conference of the North American Chap-
ter of the Association for Computational Linguistics:
Human Language Technologies , pages 1626–1644,
Online. Association for Computational Linguistics.
Simona Frenda, Alessandro Pedrani, Valerio Basile,
Soda Marem Lo, Alessandra Teresa Cignarella, Raf-
faella Panizzon, Cristina Marco, Bianca Scarlini, Vi-
viana Patti, Cristina Bosco, and Davide Bernardi.
2023. EPIC: Multi-perspective annotation of a cor-
pus of irony. In Proceedings of the 61st Annual Meet-
ing of the Association for Computational Linguis-
tics (Volume 1: Long Papers) , pages 13844–13857,
Toronto, Canada. Association for Computational Lin-
guistics.
Mor Geva, Yoav Goldberg, and Jonathan Berant. 2019.
Are we modeling the task or the annotator? an inves-
tigation of annotator bias in natural language under-
standing datasets. In Proceedings of the 2019 Confer-
ence on Empirical Methods in Natural Language Pro-
cessing and the 9th International Joint Conference
on Natural Language Processing (EMNLP-IJCNLP) ,
pages 1161–1166, Hong Kong, China. Association
for Computational Linguistics.
Limor Gultchin, Genevieve Patterson, Nancy Baym,
Nathaniel Swinger, and Adam Kalai. 2019. Humor
in word embeddings: Cockamamie gobbledegook for
nincompoops. In Proceedings of the 36th Interna-
tional Conference on Machine Learning , volume 97
ofProceedings of Machine Learning Research , pages
2474–2483. PMLR.
Tom Henighan, Jared Kaplan, Mor Katz, Mark Chen,
Christopher Hesse, Jacob Jackson, Heewoo Jun,
Tom B. Brown, Prafulla Dhariwal, Scott Gray, Chris
Hallacy, Benjamin Mann, Alec Radford, Aditya
Ramesh, Nick Ryder, Daniel M. Ziegler, John Schul-
man, Dario Amodei, and Sam McCandlish. 2020.
Scaling laws for autoregressive generative modeling.
Neil Houlsby, Andrei Giurgiu, Stanislaw Jastrzebski,
Bruna Morrone, Quentin de Laroussilhe, Andrea Ges-
mundo, Mona Attariyan, and Sylvain Gelly. 2019.
Parameter-efficient transfer learning for nlp.
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and
Weizhu Chen. 2021. Lora: Low-rank adaptation of
large language models.
Kamil Kanclerz, Marcin Gruza, Konrad Karanowski,
Julita Bielaniewicz, Piotr Milkowski, Jan Kocon, and
Przemyslaw Kazienko. 2022. What if ground truth
is subjective? personalized deep neural hate speech
detection. In Proceedings of the 1st Workshop on Per-
spectivist Approaches to NLP @LREC2022 , pages
37–45, Marseille, France. European Language Re-
sources Association.
Yiping Kang, Ashish Mahendra, Christopher Clarke,
Lingjia Tang, and Jason Mars. 2022. Towards per-
sonalized intelligence at scale.
Przemysław Kazienko, Julita Bielaniewicz, Marcin
Gruza, Kamil Kanclerz, Konrad Karanowski, Piotr
Miłkowski, and Jan Koco ´n. 2023. Human-centered
neural reasoning for subjective content processing:
Hate speech, emotions, and humor. Information Fu-
sion, 94:43–65.
Brendan Kennedy, Mohammad Atari,
Aida Mostafazadeh Davani, Leigh Yeh, Ali
Omrani, Y . Kim, Kris Coombs, Shreya Havaldar,
Gwenyth Portillo-Wightman, Elaine Gonzalez, Joe
Hoover, Aida Azatian, Aadila Hussain, A. Lara,
O G., Asmaa Al Omary, C. G. Park, C. Wang,
X Wang, Y . Zhang, and Morteza Dehghani. 2018.
The gab hate corpus: A collection of 27k posts
annotated for hate speech.
Klaus Krippendorff. 2011. Computing krippendorff’s
alpha-reliability.
Brian Lester, Rami Al-Rfou, and Noah Constant. 2021.
The power of scale for parameter-efficient prompt
tuning.
Cheng Li, Mingyang Zhang, Qiaozhu Mei, Yaqing
Wang, Spurthi Amba Hombaiah, Yi Liang, and
Michael Bendersky. 2023. Teach llms to personalize
– an approach inspired by writing education.
Xiang Lisa Li and Percy Liang. 2021. Prefix-tuning:
Optimizing continuous prompts for generation. In
Proceedings of the 59th Annual Meeting of the Asso-
ciation for Computational Linguistics and the 11th
International Joint Conference on Natural Language
Processing (Volume 1: Long Papers) , pages 4582–
4597, Online. Association for Computational Lin-
guistics.
Haokun Liu, Derek Tam, Mohammed Muqeeth, Jay Mo-
hta, Tenghao Huang, Mohit Bansal, and Colin Raffel.
2022a. Few-shot parameter-efficient fine-tuning is
better and cheaper than in-context learning.
Xiao Liu, Kaixuan Ji, Yicheng Fu, Weng Tam, Zhengx-
iao Du, Zhilin Yang, and Jie Tang. 2022b. P-tuning:
Prompt tuning can be comparable to fine-tuning
across scales and tasks. In Proceedings of the 60th
Annual Meeting of the Association for Computational
Linguistics (Volume 2: Short Papers) , pages 61–68,
Dublin, Ireland. Association for Computational Lin-
guistics.Ilya Loshchilov and Frank Hutter. 2019. Decoupled
weight decay regularization. In International Confer-
ence on Learning Representations .
Binny Mathew, Punyajoy Saha, Seid Muhie Yimam,
Chris Biemann, Pawan Goyal, and Animesh Mukher-
jee. 2022. Hatexplain: A benchmark dataset for ex-
plainable hate speech detection.
Aida Mostafazadeh Davani, Mark Díaz, and Vinodku-
mar Prabhakaran. 2022. Dealing with disagreements:
Looking beyond the majority vote in subjective an-
notations. Transactions of the Association for Com-
putational Linguistics , 10:92–110.
Anh Ngo, Agri Candri, Teddy Ferdinan, Jan Kocon,
and Wojciech Korczynski. 2022. StudEmo: A non-
aggregated review dataset for personalized emotion
recognition. In Proceedings of the 1st Workshop
on Perspectivist Approaches to NLP @LREC2022 ,
pages 46–55, Marseille, France. European Language
Resources Association.
OpenAI. 2023. Gpt-4 technical report.
Jonas Pfeiffer, Sebastian Ruder, Ivan Vuli ´c, and
Edoardo Maria Ponti. 2023. Modular deep learning.
Ilan Price, Jordan Gifford-Moore, Jory Flemming, Saul
Musker, Maayan Roichman, Guillaume Sylvain,
Nithum Thain, Lucas Dixon, and Jeffrey Sorensen.
2020. Six attributes of unhealthy conversations. In
Proceedings of the Fourth Workshop on Online Abuse
and Harms , pages 114–124, Online. Association for
Computational Linguistics.
Paul Röttger, Bertie Vidgen, Dirk Hovy, and Janet B.
Pierrehumbert. 2022. Two contrasting data annota-
tion paradigms for subjective nlp tasks.
Pratik Sachdeva, Renata Barreto, Geoff Bacon, Alexan-
der Sahn, Claudia von Vacano, and Chris Kennedy.
2022. The measuring hate speech corpus: Leverag-
ing rasch measurement theory for data perspectivism.
InProceedings of the 1st Workshop on Perspectivist
Approaches to NLP @LREC2022 , pages 83–94, Mar-
seille, France. European Language Resources Asso-
ciation.
Alireza Salemi, Sheshera Mysore, Michael Bendersky,
and Hamed Zamani. 2023. Lamp: When large lan-
guage models meet personalization.
Yisi Sang and Jeffrey Stanton. 2021. The origin and
value of disagreement among data labelers: A case
study of the individual difference in hate speech an-
notation.
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton
Ferrer, Moya Chen, Guillem Cucurull, David Esiobu,
Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller,
Cynthia Gao, Vedanuj Goswami, Naman Goyal, An-
thony Hartshorn, Saghar Hosseini, Rui Hou, Hakan
Inan, Marcin Kardas, Viktor Kerkez, Madian Khabsa,
Isabel Kloumann, Artem Korenev, Punit Singh Koura,
Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Di-
ana Liskovich, Yinghai Lu, Yuning Mao, Xavier Mar-
tinet, Todor Mihaylov, Pushkar Mishra, Igor Moly-
bog, Yixin Nie, Andrew Poulton, Jeremy Reizen-
stein, Rashi Rungta, Kalyan Saladi, Alan Schelten,
Ruan Silva, Eric Michael Smith, Ranjan Subrama-
nian, Xiaoqing Ellen Tan, Binh Tang, Ross Tay-
lor, Adina Williams, Jian Xiang Kuan, Puxin Xu,
Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan,
Melanie Kambadur, Sharan Narang, Aurelien Ro-
driguez, Robert Stojnic, Sergey Edunov, and Thomas
Scialom. 2023. Llama 2: Open foundation and fine-
tuned chat models.
Charles Welch, Chenxi Gu, Jonathan K. Kummerfeld,
Veronica Perez-Rosas, and Rada Mihalcea. 2022.
Leveraging similar users for personalized language
modeling with limited data. In Proceedings of the
60th Annual Meeting of the Association for Compu-
tational Linguistics (Volume 1: Long Papers) , pages
1742–1752, Dublin, Ireland. Association for Compu-
tational Linguistics.
Ellery Wulczyn, Nithum Thain, and Lucas Dixon. 2017.
Ex machina: Personal attacks seen at scale.
Saizheng Zhang, Emily Dinan, Jack Urbanek, Arthur
Szlam, Douwe Kiela, and Jason Weston. 2018. Per-
sonalizing dialogue agents: I have a dog, do you
have pets too? In Proceedings of the 56th Annual
Meeting of the Association for Computational Lin-
guistics (Volume 1: Long Papers) , pages 2204–2213,
Melbourne, Australia. Association for Computational
Linguistics.
A Additional Dataset Details
In this section, we detail the datasets in our PEFT-U
benchmark, including dataset construction, repre-
sentative samples, and task instructions.
A.1 Dataset Details & Construction
We include datasets in various domains, including:
•HateXplain (Mathew et al., 2022) contains
posts on social media. Each post is classified
into 3 classes: hate, offensive, or normal. The
dataset additionally contained annotations for
the hate speech target community and the ra-
tionales. We consider the post texts and the
classification labels only.
•GabHate (Kennedy et al., 2018) has 28K
posts from the social media platform Gab.
Each post is annotated using a hierarchical
coding typology of hate-based rhetoric, with
hierarchical labels indicating dehumanizing
and violent speech, vulgarity and offensivelanguage, and targeted groups. We only con-
sider the top-level binary classification on hate
speech.
•MeasuringHateSpeech (Sachdeva et al.,
2022) contains 50K social media comments
from various platforms. They are labeled
by a large number (11K) of Crowdsource
workers on Amazon Mechanical Turk2. Each
comment is annotated with 10 ordinal la-
bels: sentiment, disrespect, insult, attack-
ing/defending, humiliation, inferior/superior
status, dehumanization, violence, genocide,
and a 3-valued hate speech benchmark label.
This dataset adjusts for annotators’ perspec-
tives by aggregating the labels via faceted
Rasch measurement theory (RMT). We use
the comment text and the 3-valued hate speech
label only.
•TweetEval (Röttger et al., 2022) comprises
200 Twitter posts, each annotated by 20 an-
notator groups of 3. Annotators were given
a short definition of hate speech only, which
encourages the subjectivity of annotators. The
labels are binary classifications of hatefulness.
•UnhealthyConversations (Price et al., 2020)
consists of 44K comments labeled by crowd-
source workers as either “healthy” or “un-
healthy”. It also contains six potentially un-
healthy sub-attributes: (1) hostile; (2) antag-
onistic, insulting, provocative, or trolling; (3)
dismissive; (4) condescending or patronizing;
(5) sarcastic; and/or (6) an unfair generaliza-
tion. We only consider the top-level binary
classification of healthy conversations.
•WikiDetox Aggression (Wulczyn et al., 2017)
is a large collection of 100K online comments
to English Wikipedia where crowd-source an-
notators label whether each comment is a per-
sonal attack.
•GoEmotion (Demszky et al., 2020) is a large
annotated dataset of 58k English Reddit com-
ments, labeled for 27 emotion categories or
Neutral. We reduce the emotion categories
into 6 coarse categories with Ekman-style
grouping. Each comment can have multiple
emotion labels. We drop texts with no labels
annotated and texts labeled as ‘neutral’.
•StudEmo (Ngo et al., 2022) comprises 5K
2https://www.mturk.com
Dataset # Unique
TextsLabels
Domain Name
Hate+AbuseHateXplain 20K [hateful, offensive, normal]
GabHate 28K [Hateful, Non-hateful]
Measuring
HateSpeech50K Hate speech scale: [0, 1, 2]
TweetEval 200 [Hateful, Non-hateful]
Unhealthy
Conversations44K [healthy, unhealthy]
WikiDetox
Aggression100K [Aggressive, Normal]
SentimentGoEmotion 58K [anger, disgust, fear, joy, sadness, surprise]
StudEmo 5K[joy, trust, anticipation, surprise, fear, sadness, anger,
disgust, valence, arousal]
Subjective Discourse
(response)
1K[answer+direct, answer+over-answer, shift+correct,
shift+dodge, can’t answer+honest, can’t answer+lying]
Subjective Discourse
(question sentiment)[very-negative, negative, somewhat-negative, neutral,
somewhat-positive, positive, very-positive]
Subjective Discourse
(response sentiment)[very-negative, negative, somewhat-negative, neutral,
somewhat-positive, positive, very-positive]
HumorCockamamie 120K [humorous, not-humorous]
EPIC 3K [Ironic, Non-ironic]
Table 4: Additional details on the PEFT-U Benchmark.
customer reviews annotated by 25 people for
10 emotion dimensions: eight emotion dimen-
sions from Plutchik’s model plus valence and
arousal. Valence has an intensity range of
[−3,+3] whereas each remaining category
has a range of [0,3]. We treat the problem
as multi-class classification where we keep
categories with intensity value ≥1as positive
labels.
•Subjective Discourse (Ferracane et al., 2021)
consists of 1,000 question-response pairs from
20 witness testimonials in U.S. congressional
hearings. The study collects subjective in-
terpretations from the crowdsource workers
about the conversations on three aspects: the
question, the response, and an explanation.
In particular, the annotator provides subjec-
tive assessments of the conversation acts and
communicative intents of the responses, form-
ing 6 response labels. Each annotator also
rates their sentiment toward the politicians
and the witness on a 7-point scale. We lever-
age the response labels, and the sentiments
toward the politicians and witnesses to form
3 dataset versions. To construct the text part,
we join (question speaker detail, question text,response speaker detail, response text) by new-
lines.
•Cockamamie (Gultchin et al., 2019) includes
120K words and phrases from GNEWS. The
words and phrases are annotated by crowd
workers fluent in English on whether they are
humorous. 1,500 words are further annotated
on six binary humor features. We leverage
the words and the initial binary “humorous”
labels only.
•EPIC (Frenda et al., 2023) is made of 3K
short social media (post, reply) pairs collected
from Twitter and Reddit across five regional
varieties of English. Annotators from five dif-
ferent counties were asked to provide a binary
label (either Irony ornot-Irony ) for the Re-
plytext given the context provided by Post.
We template the (Post, Reply) pairs by adding
“message” and “reply” prefixes.
We summarize additional details for each dataset
in Table 4. We split each user’s data into
train/dev/test sets by 80/10/10 splits.
A.2 Representative Samples
In this section, we show representative samples
for each dataset where different user perspectives
result in different labels for the same text input.
Warning: Offensive content is inevitable for
datasets in the Hate+Abuse domain.
A.2.1 Representative Sample for HateXplain
Text. right definitely not going back to the fag
hag thing it was fun for a bit in my <number> but
outrageously gay people are just too high strung
for me it back to that reason i can not be a lesbian
Labels .
- normal
- hatespeech
- offensive
A.2.2 Representative Sample for
MeasuringHateSpeech
Text. @L1LTR4P fucking losers wetbacks #Sor-
ryNotSorry
Labels .
- 0
- 1
- 2
A.2.3 Representative Sample for GabHate
Text. #Breaking: Claiming bias against conserva-
tives, @FreedomWatchUSA has filed a class action
lawsuit against Google, Facebook, Instagram, Twit-
ter, and Apple.
Labels .
- Non-hateful
- Hateful
A.2.4 Representative Sample for TweetEval
Text. [USER] fuck Brett Farve redneck ass, he
stuckup he don’t give a damn lol he be on campus
acting like he the shit
Labels .
- Hateful
- Non-hateful
A.2.5 Representative Sample for Unhealthy
Conversations
Text. They are poor because they are reliant on the
drug trade and reliant on the drug trade because
they are then poor. That cycle can be broken.
Labels .
- healthy
- unhealthyA.2.6 Representative Sample for WikiDetox
Aggression
Text. == Dougbiznatch again! ==
Hey I’m back. Gonna vandalize all day and no one
can stop me! As you can tell I can’t be stopped by
banning. I’ll be seeing alo tof you and the rest of
the blacklisted admins for the next couple of weeks
=P
Dougbiznatch
Labels .
- Aggressive
- Normal
A.2.7 Representative Sample for GoEmotion
Text. Is he dead now from a tragic drowning acci-
dent? Asking for a friend.
Labels .
- [sadness]
- [surprise]
A.2.8 Representative Sample for StudEmo
Text. We got to the Cycle On Hostel by chance
in the middle of the night. There wasn’t a single
place available in other places. . . ...and it’s very
good that we didn’t get to another place! First of
all, great service: people who are open to others,
nice and smiling, who help us with every time of
day and night. Spacious hostel, rooms and bath-
rooms are clean. And besides all that - the location
- nothing to add, nothing to take away. Literally 5
minutes away from Neptune and at the same time
the building is situated in such a place that at night
it is quiet despite such a short distance from the
busiest street where it is full of tourists and chil-
dren. If we will still have a chance to spend the
night in Gdansk, we will surely come to Cycle On
again. With a clear conscience I recommend
Labels .
- [trust, anticipation, valence, arousal]
- [joy, trust, valence, arousal]
A.2.9 Representative Sample for Subjective
Discourse (response)
Text. politician: JIM JORDAN, Ohio
Okay. Well, this is put out by the Exempt Orga-
nizations Division, same division where all these
problems took place over the last three years. It
came out, again, just five days after the comment
period on the proposed rule ended at the end of
February, and I want to just highlight a few of the
questions that are asked. So there is a category that
says what if the IRS needs more information about
your (c)(4) application? New sample questions. So
if we could put them up side-by-side. Now, the
first slide are the targeted questions that TIGTA
said were inappropriate and that you agree are inap-
propriate, Judith Kendall agreed are inappropriate.
Those are those questions. And now, just five days
after the proposed rule comment period ends, you
issue a newsletter from the Exempt Organizations
Division highlighting the new questions you are
going to ask, and I just want to look how similar
the two questions are. Let’s just take the second cat-
egory, whether an officer or director, etcetera, has
run or will run for public office. The new question
says this: Do you support a candidate for public of-
fice who is one of your founders, officers, or board
members? It is basically the same. This reminds
me of when I was in grade school and the teachers
told us you shouldn’t plagiarize, so you change
a few words and basically plagiarize. This is the
same thing. So here is what I don’t understand. If
you are trying to comply with the TIGTA report, if
the new (c)(4) rule is a way to deal with what the
audit said and not as what I believe is a continua-
tion of the project Lois Lerner started, why are you
asking the same darn questions?
witness: The Hon. John Koskinen, Commissioner,
Internal Revenue Service
As I noted, I haven’t seen that and can’t read it on
the chart. I would be delighted to sit down and
go over all of those questions with you and with
the exempt organizations. All of the TIGTA report
didn’t blanket say you should never ask questions
about this. Thank you for the chart.
Labels .
- can’t answer+lying
- can’t answer+honest
- shift+dodge
A.2.10 Representative Sample for Subjective
Discourse (question sentiment)
Text. politician: RANDY NEUGEBAUER, Texas
And, as you’re aware, Section 972 of Dodd-Frank
requires an issuer of securities to disclose the an-
nual proxy statement, the reason why the issuer
has chosen to allow the same person to serve as
the board chairman and the CEO. This year, Wells
states that your dual role is a result of your ex-tensive experience and knowledge regarding the
company and provides the most efficient leadership
of the board and the company. Mr. Stumpf, do you
think it’s a good idea for the same person to serve
as both chairman of the board and CEO?
witness: Stumpf, John G., Chairman and Chief
Executive Officer, Wells Fargo and Company
Thank you, Congressman, for that question. In
our company, we have 14 outside directors. We
have a lead director. All directors are New York
Stock Exchange-independent, by their standards.
I am not a member of any standing committee of
that board. The independent directors and the lead
director help set the agenda for the boards. They
always have meetings that are in executive session
without me. And as you probably read about what
happened this weekend–because we filed an 8-K
yesterday about actions that they took as an inde-
pendent board, and I was not part of that. So the
board acts quite independently.
Labels .
- negative
- neutral
- somewhat-negative
- somewhat-positive
A.2.11 Representative Sample for Subjective
Discourse (response sentiment)
Text. politician: JERROLD NADLER, New York,
Chairman
It is our understanding that at least one briefing
occurred between December–between your deci-
sion not to recuse yourself on December 19th and
6 days later, Christmas day. Is that correct? Simple
enough question, yes or no.
witness: Matthew G. Whitaker, Acting Attorney
General, U.S. Department of Justice Oral Testi-
mony
Mr. Chairman, I, again, what is the basis for
your question? You are saying that it is your
understanding—-
Labels .
- negative
- neutral
- somewhat-negative
- somewhat-positive
A.2.12 Representative Sample for
Cockamamie
Text. judokas
Labels .
- humorous
- not-humorous
A.2.13 Representative Sample for EPIC
Text. message: “Because the last generation was
Gen. Z and there’s no where to go past that, so we
gotta start from the beginning.”
reply: “but we should have just named the first
generation “Alpha” instead of doing it now”
Labels .
- Ironic
- Non-ironic
A.3 Task Instructions
In this section, we show the task instructions
prepended to prompts in training and inference for
each dataset.
A.3.1 Instruction for HateXplain
Please review the following text and indicate if it
has the presence of hate speech or is offensive in
nature. Respond ‘hatespeech’ if the text contains
hate speech, ‘offensive’ if the text does not contain
hate speech but is offensive and ‘normal’ if the text
is neither offensive nor contains hate speech.
A.3.2 Instruction for MeasuringHateSpeech
On a scale of 0-2 rate the level of hatespeech con-
tained in the following text. Respond with ‘0’ if
the text does not contain hate speech, ‘1’ if the
text contains some hate speech, and ‘2’ if the text
contains a lot of hate speech.
A.3.3 Instruction for GabHate
Please review the following text and indicate if it
has the presence of hate speech. Respond ‘Hateful’
if the text contains hate speech and ‘Non-hateful’
if the text does not contain hate speech.
A.3.4 Instruction for TweetEval
Please review the following text and indicate if it
has the presence of hate speech. Respond ‘Hateful’
if the text contains hate speech and ‘Non-hateful’
if the text does not contain hate speech.
A.3.5 Instruction for Unhealthy
Conversations
Please review the following text and indicated if it
is ‘healthy’ or ‘unhealthy’. Respond ‘healthy’ ifthe text is healthy and ‘unhealthy’ if the text can
be considered hostile, antagonistic, condescending,
dismissive or an unfair generalization.
A.3.6 Instruction for WikiDetox Aggression
Please review the following text and indicate if it
has the presence of malicious remark to a person
or group. Respond ‘Aggressive’ if the text contains
a personal attack and ‘Normal’ if the text does not
contain a personal attack.
A.3.7 Instruction for GoEmotion
Please analyze the following text and assign one
or more appropriate emotion labels. Emotion la-
bels include happiness, sadness, anger, surprise,
joy, fear, disgust. You can select one or multiple
emotion labels that best capture the emotional con-
tent of the text. Respond with the emotion labels
separated by a comma.
A.3.8 Instruction for StudEmo
Please analyze the following text and assign one
or more appropriate emotion labels. Emotion la-
bels include joy, trust, anticipation, surprise, fear,
sadness, disgust, anger, valence, and arousal. You
can select one or multiple emotion labels that best
capture the emotional content of the text. Respond
with the emotion labels separated by a comma.
A.3.9 Instruction for Subjective Discourse
(response)
Please analyze the following text and indicate how
the witness responded to the question. Respond
with ‘answer’ if they answered the question reason-
ably, ‘cant-answer-lying’ if they could not answer
and are lying, ‘cant-answer-sincere’ if they could
not answer but are honest about it, ‘shift-dodge’ if
they shifted the topic with the intent of dodging the
question, ‘answer_overans-sway’ if they over an-
swered the question with the intention of swaying
or ‘shift-correct’ if they shifted the topic with the
intention of clarifying the question.
A.3.10 Instruction for Subjective Discourse
(question sentiment)
Please analyze the following text and rate your
sentiment towards the questioners. Sentiment la-
bels include ‘somewhat-positive’, ‘positive’, ‘very-
positive’, ‘somewhat-negative’, ‘very-negative’,
‘neutral’ and ‘negative’. Respond with the sen-
timent label that best captures your sentiment to-
wards the questioners.
A.3.11 Instruction for Subjective Discourse
(response sentiment)
Please analyze the following text and rate your
sentiment towards the witness. Sentiment la-
bels include ‘somewhat-positive’, ‘positive’, ‘very-
positive’, ‘somewhat-negative’, ‘very-negative’,
‘neutral’ and ‘negative’. Respond with the sen-
timent label that best captures your sentiment to-
wards the witness.
A.3.12 Instruction for Cockamamie
Please rate whether the following text is funny or
not funny. Respond ‘yes’ if you think the text is
funny and ‘no’ if you think the text is not funny.
A.3.13 Instruction for EPIC
Irony is a figurative language device that conveys
that opposite of literal meaning, profiling inten-
tionally a secondary or extended meaning. Please
review the following message and reply and indi-
cate if it has the presence of irony. Respond ‘Ironic’
if the reply if you think the reply is ironic and ‘Non-
ironic’ if you think the reply is not ironic. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18119v1 | http://arxiv.org/pdf/2407.18119v1 | Tracking linguistic information in transformer-based sentence embeddings through targeted sparsification | Vivi Nastase, Paola Merlo | 2024-07-25 | Abstract
Analyses of transformer-based models have
shown that they encode a variety of linguis-
tic information from their textual input. While
these analyses have shed a light on the rela-
tion between linguistic information on one side,
and internal architecture and parameters on the
other, a question remains unanswered: how is
this linguistic information reflected in sentence
embeddings? Using datasets consisting of sen-
tences with known structure, we test to what
degree information about chunks (in particular
noun, verb or prepositional phrases), such as
grammatical number, or semantic role, can be
localized in sentence embeddings. Our results
show that such information is not distributed
over the entire sentence embedding, but rather
it is encoded in specific regions. Understand-
ing how the information from an input text is
compressed into sentence embeddings helps un-
derstand current transformer models and help
build future explainable neural models.
1 | Introduction
In the quest for understanding transformer-based
models, much work has been dedicated to uncover
what kind of information is encoded in the model’s
various layers and parameters. These analyses have
provided several enlightening insights: (i) differ-
ent types of linguistic information – e.g. parts of
speech, syntactic structure, named entities – are
selectively more evident at different layers of the
model (Tenney et al., 2019a; Rogers et al., 2020),
(ii) subnetworks can be identified that seem to en-
code particular linguistic functionalities (Csordás
et al., 2021), and (iii) fine-tuning for specific tasks
can be focused on very small subsets of parameters,
on different parts of a model’s layers (Panigrahi
et al., 2023). While these analyses and probes have
focused on the insides of the models, mostly their
parameters and layers, testing their impact is usu-
ally done by using the output of the model, namelytoken or sentence embeddings, to solve specific
tasks. The link between the inside of the model and
its outputs is usually not explicitly investigated.
We ask several facets of this question here: how
are the internally-detected information types and
structures reflected in the model’s output? And how
are arbitrarily long and complex sentences encoded
systematically in a fixed-sized vector?
Understanding what kind of information the sen-
tence embeddings encode, and how, has multiple
benefits: (i) it connects internal changes in the
model parameters and structure with changes in
its outputs; (ii) it contributes to verifying the ro-
bustness of models and whether or not they rely on
shallow or accidental regularities in the data; (iii) it
narrows down the field of search when a language
model produces wrong outputs, and (iv) it helps
maximize the use of training data for developing
more robust models from smaller textual resources.
Transformer-based models usually use a token-
focused learning objective, and have a weaker su-
pervision signal at the sentence level – e.g. a next
sentence prediction (Devlin et al., 2018), or sen-
tence order information (Lan et al., 2019). Despite
this focus, high performance in a variety of tasks
(using raw or fine-tuned sentence embeddings) as
well as direct probing shows that sentence represen-
tations encode a variety of linguistic information
(Conneau et al., 2018). On the other hand, direct
exploration of BERT sentence embeddings has also
shown that they contain mostly shallow informa-
tion, related to sentence length and lexical variation,
and that many of their dimensions are correlated,
indicating that either information is redundantly
encoded, or that not all dimensions encode useful
information (Nikolaev and Padó, 2023). Some of
this preexisting work assumes that sentence embed-
dings encode information in an overt manner, for
example, each principal component dimension is
responsible for encoding some type of information.
We adopt the different view that information inarXiv:2407.18119v1 [cs.CL] 25 Jul 2024
sentence embeddings may be encoded in merged
layers, in a manner similar to audio signals being
composed of overlapping signals of different fre-
quencies. We hypothesize that each such layer may
encode different types of information. We aim to
test this hypothesis and check (i) whether we can
separate such layers, and (ii) investigate whether
information about specific chunks in a sentence
–noun,verb, or prepositional phrases– is encoded in
different layers and parts of a sentence embedding.
We perform our investigation in an environment
with data focused on specific grammatical phenom-
ena, while displaying lexical, structural and seman-
tic variation, and a previously developed system
that has been shown to detect the targeted phenom-
ena well (Nastase and Merlo, 2024). The system is
a variational encoder-decoder, with an encoder that
compresses the information in the input into a very
low-dimensional latent vector. Nastase and Merlo
(2024) have shown that the sentence embeddings,
and their compressed representations on the latent
layer, encode information about chunks – noun,
verb, prepositional phrases – and their linguistic
properties.
The current study investigates the general hy-
pothesis indicated above by specifically exploring
two new research questions in this setting:
1.Whether a targeted sparsification of the sys-
tem maintains a high performance on the task,
indicating that information about chunks in
the sentence is localizable.
2.Contingent on the answer to the first question,
we trace back the signal from the latent layer
to the input sentence embeddings, and analyze
how specific differences in chunk properties
– different number of chunks, or chunks that
differ from each other only on one property
(e.g. grammatical number) – are localized and
reflected in the sentence embeddings.
The code and data are available at
https://github.com/CLCL-Geneva/
BLM-SNFDisentangling .
2 | Section not found | Related work
Sentence embeddings Transformer models in-
duce contextual token embeddings by passing the
embedding vectors through successive layers us-
ing multi-head attention that allows for tokens to
influence each other’s representation at each suc-
cessive step (Vaswani et al., 2017). The modelfocuses on the token embeddings, as the tokens
expected on the output layer provide the training
signal. There are numerous variations on the BERT
(Devlin et al., 2018) transformer model1, that vary
in the way the models are trained (Liu et al., 2019),
how they combine (or not) the positional and to-
ken embeddings (He et al., 2020), how the input
is presented to the model (Liu et al., 2019; Clark
et al., 2020). With regards to the sentence-level
supervision signal, BERT (Devlin et al., 2018) uses
the next sentence prediction objective, ALBERT
(Lan et al., 2019), aiming to improve coherence,
uses sentence order prediction. It is more common
to further train or fine-tune a pre-trained model to
produce sentence embeddings fitting specific tasks,
such as story continuation (Ippolito et al., 2020) or
sentence similarity (Reimers and Gurevych, 2019).
Electra (Clark et al., 2020) does not have a
sentence-level objective, but it relies on replaced
token detection, which relies on the sentence con-
text to determine whether a (number of) token(s)
in the given sentence were replaced by a generator
sample. This leads to sentence embeddings that
perform well on tasks such as Question Answering,
or detecting verb classes (Yi et al., 2022).
Probing embeddings and models for linguistic
information Most work investigating the kind of
knowledge captured by transformer-based models
have focused on analysing the architecture of the
model (Tenney et al., 2019b; Rogers et al., 2020) to
determine the localization and flow of information
through the model’s layers. There is also much
work on analyzing the induced token embeddings
to determine what kind of linguistic information
they encode, such as sentence structure (Hewitt
and Manning, 2019), predicate argument structure
(Conia et al., 2022), subjecthood and objecthood
(Papadimitriou et al., 2021), among others. Testing
whether sentence representation contain specific
types of linguistic information has been done using
task (or information)-specific classifiers (Adi et al.,
2017; Conneau et al., 2018; Goldberg, 2019; Wil-
son et al., 2023). Opitz and Frank (2022) aim to
map subsets of dimensions of fine-tuned sentence
embeddings to semantic features.
Sparsification Deep learning models have bil-
lions of parameters. This makes them not only
incomprehensible, but also expensive to train. The
1https://huggingface.co/docs/transformers/en/
model_summary
lottery ticket | Section not found | Section not found | research questions in this setting:
1.Whether a targeted sparsification of the sys-
tem maintains a high performance on the task,
indicating that information about chunks in
the sentence is localizable.
2.Contingent on the answer to the first question,
we trace back the signal from the latent layer
to the input sentence embeddings, and analyze
how specific differences in chunk properties
– different number of chunks, or chunks that
differ from each other only on one property
(e.g. grammatical number) – are localized and
reflected in the sentence embeddings.
The code and data are available at
https://github.com/CLCL-Geneva/
BLM-SNFDisentangling .
2 Related work
Sentence embeddings Transformer models in-
duce contextual token embeddings by passing the
embedding vectors through successive layers us-
ing multi-head attention that allows for tokens to
influence each other’s representation at each suc-
cessive step (Vaswani et al., 2017). The modelfocuses on the token embeddings, as the tokens
expected on the output layer provide the training
signal. There are numerous variations on the BERT
(Devlin et al., 2018) transformer model1, that vary
in the way the models are trained (Liu et al., 2019),
how they combine (or not) the positional and to-
ken embeddings (He et al., 2020), how the input
is presented to the model (Liu et al., 2019; Clark
et al., 2020). With regards to the sentence-level
supervision signal, BERT (Devlin et al., 2018) uses
the next sentence prediction objective, ALBERT
(Lan et al., 2019), aiming to improve coherence,
uses sentence order prediction. It is more common
to further train or fine-tune a pre-trained model to
produce sentence embeddings fitting specific tasks,
such as story continuation (Ippolito et al., 2020) or
sentence similarity (Reimers and Gurevych, 2019).
Electra (Clark et al., 2020) does not have a
sentence-level objective, but it relies on replaced
token detection, which relies on the sentence con-
text to determine whether a (number of) token(s)
in the given sentence were replaced by a generator
sample. This leads to sentence embeddings that
perform well on tasks such as Question Answering,
or detecting verb classes (Yi et al., 2022).
Probing embeddings and models for linguistic
information Most work investigating the kind of
knowledge captured by transformer-based models
have focused on analysing the architecture of the
model (Tenney et al., 2019b; Rogers et al., 2020) to
determine the localization and flow of information
through the model’s layers. There is also much
work on analyzing the induced token embeddings
to determine what kind of linguistic information
they encode, such as sentence structure (Hewitt
and Manning, 2019), predicate argument structure
(Conia et al., 2022), subjecthood and objecthood
(Papadimitriou et al., 2021), among others. Testing
whether sentence representation contain specific
types of linguistic information has been done using
task (or information)-specific classifiers (Adi et al.,
2017; Conneau et al., 2018; Goldberg, 2019; Wil-
son et al., 2023). Opitz and Frank (2022) aim to
map subsets of dimensions of fine-tuned sentence
embeddings to semantic features.
Sparsification Deep learning models have bil-
lions of parameters. This makes them not only
incomprehensible, but also expensive to train. The
1https://huggingface.co/docs/transformers/en/
model_summary
lottery ticket | Section not found | hypothesis and check (i) whether we can
separate such layers, and (ii) investigate whether
information about specific chunks in a sentence
–noun,verb, or prepositional phrases– is encoded in
different layers and parts of a sentence embedding.
We perform our investigation in an environment
with data focused on specific grammatical phenom-
ena, while displaying lexical, structural and seman-
tic variation, and a previously developed system
that has been shown to detect the targeted phenom-
ena well (Nastase and Merlo, 2024). The system is
a variational encoder-decoder, with an encoder that
compresses the information in the input into a very
low-dimensional latent vector. Nastase and Merlo
(2024) have shown that the sentence embeddings,
and their compressed representations on the latent
layer, encode information about chunks – noun,
verb, prepositional phrases – and their linguistic
properties.
The current study investigates the general hy-
pothesis indicated above by specifically exploring
two new research questions in this setting:
1.Whether a targeted sparsification of the sys-
tem maintains a high performance on the task,
indicating that information about chunks in
the sentence is localizable.
2.Contingent on the answer to the first question,
we trace back the signal from the latent layer
to the input sentence embeddings, and analyze
how specific differences in chunk properties
– different number of chunks, or chunks that
differ from each other only on one property
(e.g. grammatical number) – are localized and
reflected in the sentence embeddings.
The code and data are available at
https://github.com/CLCL-Geneva/
BLM-SNFDisentangling .
2 Related work
Sentence embeddings Transformer models in-
duce contextual token embeddings by passing the
embedding vectors through successive layers us-
ing multi-head attention that allows for tokens to
influence each other’s representation at each suc-
cessive step (Vaswani et al., 2017). The modelfocuses on the token embeddings, as the tokens
expected on the output layer provide the training
signal. There are numerous variations on the BERT
(Devlin et al., 2018) transformer model1, that vary
in the way the models are trained (Liu et al., 2019),
how they combine (or not) the positional and to-
ken embeddings (He et al., 2020), how the input
is presented to the model (Liu et al., 2019; Clark
et al., 2020). With regards to the sentence-level
supervision signal, BERT (Devlin et al., 2018) uses
the next sentence prediction objective, ALBERT
(Lan et al., 2019), aiming to improve coherence,
uses sentence order prediction. It is more common
to further train or fine-tune a pre-trained model to
produce sentence embeddings fitting specific tasks,
such as story continuation (Ippolito et al., 2020) or
sentence similarity (Reimers and Gurevych, 2019).
Electra (Clark et al., 2020) does not have a
sentence-level objective, but it relies on replaced
token detection, which relies on the sentence con-
text to determine whether a (number of) token(s)
in the given sentence were replaced by a generator
sample. This leads to sentence embeddings that
perform well on tasks such as Question Answering,
or detecting verb classes (Yi et al., 2022).
Probing embeddings and models for linguistic
information Most work investigating the kind of
knowledge captured by transformer-based models
have focused on analysing the architecture of the
model (Tenney et al., 2019b; Rogers et al., 2020) to
determine the localization and flow of information
through the model’s layers. There is also much
work on analyzing the induced token embeddings
to determine what kind of linguistic information
they encode, such as sentence structure (Hewitt
and Manning, 2019), predicate argument structure
(Conia et al., 2022), subjecthood and objecthood
(Papadimitriou et al., 2021), among others. Testing
whether sentence representation contain specific
types of linguistic information has been done using
task (or information)-specific classifiers (Adi et al.,
2017; Conneau et al., 2018; Goldberg, 2019; Wil-
son et al., 2023). Opitz and Frank (2022) aim to
map subsets of dimensions of fine-tuned sentence
embeddings to semantic features.
Sparsification Deep learning models have bil-
lions of parameters. This makes them not only
incomprehensible, but also expensive to train. The
1https://huggingface.co/docs/transformers/en/
model_summary
lottery ticket hypothesis (Frankle and Carbin, 2018)
posits that large networks can be reduced to sub-
networks that encode efficiently the functionality
of the entire network. Detecting functional subnet-
works can be done a posteriori , over a pre-learned
network to investigate the functionality of detected
subnetworks (Csordás et al., 2021), the potential
compositionality of the learned model (Lepori et al.,
2023), or where task-specific skills are encoded in
a fine-tuned model (Panigrahi et al., 2023).
Instead of learning a sparse network over a pre-
learned model, Cao et al. (2021) use a pruning-
based approach to finding subnetworks in a pre-
trained model that performs some linguistic task.
Pruning can be done at several levels of granularity:
weights, neurons, layers. Their analyses confirm
previous investigations of the types of information
encoded in different layers of a transformer (Con-
neau et al., 2018). Conmy et al. (2023) introduce
the Automatic Circuit DisCovery (ACDC) algo-
rithm, which adapts subnetwork probing and head
importance score for pruning to discover circuits
that implement specific linguistic functions.
Sparsification can also be achieved using L0reg-
ularization, as the pruning would be done directly
during training by encouraging weights to become
exactly zero. Louizos et al. (2018); Savarese et al.
(2020), among others, implement solutions to the
issue that L0regularization is non-differentiable,
and test it on image classification.
The cited work focuses on the parameters of the
model, and sparsification approaches aiming to de-
tect the subnetworks to which specific skills or
linguistic information can be ascribed. Our focus,
instead, is the output of transformer-based mod-
els, in particular sentence embeddings, which we
investigate using targeted sparsification.
3 Approach overview
We investigate whether we can identify specific
sentence properties in sentence embeddings. Nas-
tase and Merlo (2024) have shown that using
an encoder-decoder architecture, sentence embed-
dings can be compressed into a latent representa-
tion that preserves information about chunks in a
sentence, and their properties necessary to solve a
specific linguistic task.
We first test whether we can sparsify this archi-
tecture in a targeted manner, such that each region
of the sentence embedding contributes a signal to
only one unit of the latent layer. This allows us toisolate different parts of the sentence embedding.
After establishing that sparsification does not
lead to a dramatic drop in performance, we trace
back the signal from the latent layer to the sentence
embeddings, and test whether we can localize in-
formation about how different numbers of chunks,
or chunks with different properties, are encoded.
In the final step, we use the sparse encoder-
decoder sentence compression system as the first
in a two-layer system used to solve language tasks –
called Blackbird Language Matrices (Merlo, 2023)
– that require chunk and chunk properties informa-
tion. The first layer will compress each sentence
into a very small latent vector, and this represen-
tation is then used on the second layer to solve a
pattern detection problem that relies on information
about chunks in a sentence and their pattern across
a sequence of sentences.
4 Data
We use two data types: (i) a dataset of sentences
with known chunk structure and chunk properties,
(ii) two datasets representing two multiple-choice
problems, whose solution requires understanding
the chunk structure and chunk properties of the
sentences in each instance.
4.1 A dataset of sentences
We start with an artificially-created set of sentences
built from noun, prepositional and verb phrases.
Each sentence has one of the following structures:
NP [PP 1[PP 2]] VP , where the parentheses sur-
round optional structure. Each chunk can have
singular or plural form, with agreement between
the first NP (the subject) and the VP. This leads to
14’336 sentences with one of 14 patterns.
The dataset consists of ordered pairs of one input
sentence and N(=7) output sentences, extracted
from the set described above. Only one of the out-
put sentences has the same chunk pattern as the
input sentence, and is considered as the correct
output. We select 4004 instances uniformly dis-
tributed over the 14 patterns, which are split into
train:dev:test – 2576:630:798.
4.2 Multiple Choice Problems: Blackbird
Language Matrices
Blackbird Language Matrices (BLMs) (Merlo,
2023) are language versions of the visual Raven
Progressive Matrices (RPMs). Like the RPMs, they
are multiple-choice problems. The input is a se-
quence of 7 sentences built using specific rules, and
BLM agreement problem
CONTEXT TEMPLATE
NP-sg PP1-sg VP-sg
NP-pl PP1-sg VP-pl
NP-sg PP1-pl VP-sg
NP-pl PP1-pl VP-pl
NP-sg PP1-sg PP2-sg VP-sg
NP-pl PP1-sg PP2-sg VP-pl
NP-sg PP1-pl PP2-sg VP-sg
ANSWER SET
NP-sg PP1-sg et NP2 VP-sg Coord
NP-pl PP1-pl NP2-sg VP-pl correct
NP-sg PP1-sg VP-sg WNA
NP-pl PP1-pl NP2-pl VP-sg AE_V
NP-pl PP1-sg NP2-pl VP-sg AE_N1
NP-pl PP1-pl NP2-sg VP-sg AE_N2
NP-pl PP1-sg PP1-sg VP-pl WN1
NP-pl PP1-pl PP2-pl VP-pl WN2BLM verb alternation problem
CONTEXT TEMPLATE
NP-Agent Verb NP-Loc PP-Theme
NP-Theme VerbPass PP-Agent
NP-Theme VerbPass PP-Loc PP-Agent
NP-Theme VerbPass PP-Loc
NP-Loc VerbPass PP-Agent
NP-Loc VerbPass PP-Theme PP-Agent
NP-Loc VerbPass PP-Theme
ANSWER SET
NP-Agent Verb NP-Theme PP-Loc CORRECT
NP-Agent *VerbPass NP-Theme PP-Loc A GENT ACT
NP-Agent Verb NP-Theme *NP-Loc A LT1
NP-Agent Verb *PP-Theme PP-Loc A LT2
NP-Agent Verb *[NP-Theme PP-Loc] N OEMB
NP-Agent Verb NP-Theme *PP-Loc L EXPREP
*NP-Theme Verb NP-Agent PP-Loc SSM1
*NP-Loc Verb NP-Agent PP-Theme SSM2
*NP-Theme Verb NP-Loc PP-Agent AASSM
Figure 1: Structure of two BLM problems, in terms of chunks in sentences and sequence structure.
the correct answer fits within the sequence defined
by these rules. The incorrect options are built by
corrupting some of the underlying generating rules
of the input sentence sequence. Solving the prob-
lem requires identifying the entities (the chunks),
their relevant attributes (their morphological or se-
mantic properties) and their connecting operators.
We use two BLM datasets: (i) BLM-AgrF – sub-
ject verb agreement in French (An et al., 2023),
and (ii) BLM-s/lE – the spray-load verb alterna-
tions in English2(Samo et al., 2023). The structure
of these datasets – in terms of the sentence chunks
and sequence structure – is shown in Figure 1.
Datasets statistics Table 1 shows the datasets
statistics. Each set is split 90:10 into train:test sub-
sets, and then we randomly sample 2000 instances
as train data. 20% of the train data is used for de-
velopment. Types I, II, III correspond to different
amounts of lexical variation within an instance.
Subj.-verb agr. Verb alternations
ALT-ATL ATL-ALT
Type I 2000:252 2000:375 2000:375
Type II 2000:4866 2000:1500 2000:1500
Type III 2000:4869 2000:1500 2000:1500
Table 1: Train:Test statistics for the two BLM problems.
To solve a BLM instance, the system processes
the input sentence sequence and outputs a sentence
representation that will be compared to the repre-
sentation of the sentences in the answer set. The
candidate answer closest to the generated sentence
representation will be considered the correct one.
2Agent-Location-Theme (ALT) – Agent-Theme-Location
(ATL)We run the experiments on the BLMs for agree-
ment and on the verb alternation BLMs. While the
information necessary to solve the agreement task
is more structural, solving the verb alternation task
requires not only structural information on chunks,
but also semantic information, as syntactically sim-
ilar chunks play different roles in a sentence.
5 Experiments
We present a progression of experiments.
1.Using the dataset of sentences with known
chunk structure, we test whether a sparse vari-
ational encoder-decoder system can distill in-
formation about the chunk structure of a sen-
tence from its embedding.
2.We analyze the sparse model, and trace the
information from the latent layer back to the
sentence embedding to understand where in
the sentence embeddings these differences are
encoded.
3.We combine the sparsified variational encoder-
decoder with another V AE-like layer to solve
the BLM tasks, and test whether the latent
layer sentence encodings maintain informa-
tion useful for the tasks.
All experiments use Electra (Clark et al., 2019)3.
We use as sentence representations the embedding
of the [CLS] token, reshaped as a two dimensional
array with shape 32x24.
3Electra pretrained model: google/electra-base-
discriminator
The experiments are analyzed through the out-
put of the system, in terms of average F1 score
over three runs. For the investigations of the sen-
tence embeddings, we also analyze the compressed
vectors on the latent layer, to determine whether
chunk patterns are encoded in these vectors. If
these vectors cluster by the chunk pattern of the
corresponding sentences it will indicate that sen-
tence chunk patterns were indeed detected and are
encoded differently in the latent layer.
5.1 Sparsification
Nastase and Merlo (2024) have shown that sentence
embeddings contain information about the chunk
structure and their properties using an encoder-
decoder architecture that compresses the relevant
information into a small latent layer. They build
on Nastase and Merlo (2023) who show that re-
shaping a sentence embedding from the commonly
used one-dimensional array to a two-dimensional
representation allows grammatical information to
become more readily accessible.
We adopt the system of (Nastase and Merlo,
2024), with the same architecture (including num-
ber of CNN channels and kernel size), and sparsify
it, to determine whether specific information can
be localized in sentence embeddings. The encoder
of the system consists of a CNN layer followed by
a FFNN, that compresses the information into a
latent layer, as illustrated in Figure 2.
input convolution
(40 channels)
CNN FFNNlinearized
output
of CNNlatentEncoder architecture
Figure 2: Details of the encoder architecture
The CNN layer in the encoder detects a different
pattern in the sentence representation on each of its
40 channels. The linear layer compresses the lin-
earized output of the CNN into a very small latent
layer (length 5). A vector is sampled from this, and
then decoded into a sentence representation using
a decoder which is a mirror of the encoder.
An instance consists of an input sentence s, and
7 output sentences, only one of which has the samechunk structure as the input and is considered the
correct one (section 4.1). The aim is to guide
the system to capture information about the chunk
structure of the sentences in the latent layer, by
using a max-margin loss function that assigns a
higher score to the correct option relative to the
others. Formally, if esis the embedding of the in-
put sentence s,ˆesis the embedding output by the
decoder, ecis the embedding of the correct option
andei, i= 1,6are the embeddings of the other
options, and mm is the maxmargin function, then:
loss(s) =mm(ˆes, ec,{ei|i= 1,6}) +KL(zs||N(0,1))
mm(ˆes, ec, ei)=
max(0,1−score (ˆes, ec) +P6
i=1score (ˆes, ei)/6)
We want to sparsify this network in a targeted
way: we enforce that each output unit from the
CNN layer will contribute to only one unit in the
latent layer. Figure 3 illustrates the process.
1
2
3
nA
B
X1
2
3
nA
B
Xlinearized
output
of CNNlatent latent linearized
output
of CNNFFNN sparsification
Figure 3: Separating linguistic signals by masking the
one-layer FFNN
To enforce this behaviour, we use an approach
inspired from sparsification (Savarese et al., 2020)
and subnetworking (Lepori et al., 2023). Instead
of considering the output of the CNN as the input
layer of a linear network, we make each CNN out-
put unit the input of a separate linear network, con-
nected to the latent layer. We apply a mask mto the
weights Wof this network, and compute a masked
weight matrix Wm=W×softmax (M/τ),
where τis a temperature parameter used to push
the softmax function towards a one-hot vector.
We use a kernel 15x154and equal stride (15x15)
to have a very clear separation of the information
flow from the sentence embedding to the latent
4We adopt the size of the kernel from previous work.
layer. This will ensure our sparsification desidera-
tum, and the learned network will have a particular
configuration: if NCNN is the set of output nodes
from the CNN, and NLare the nodes on the latent
layer, then the sets of CNN output nodes connected
to each of the latent units are disjunct:
∀nl∈NL, Sl
CNN ={nc∈NCNN|Wm(nl, nc)>0}
and if i̸=jthenSi
CNN∩Sj
CNN=∅
Sparsification results Despite the fact that this
type of sparsification is very harsh, and channels
the information from the sentence embedding into
very few paths on the way to the latent layer, the
results in terms of average F1-score/standard devi-
ation over three runs without 0.997 (0.0035) and
with sparsification 0.977 (0.0095) are close. While
this difference is rather small, we notice a big-
ger difference in the latent layer. Figure 5 shows
the TSNE projections of the latent layers. As
can be seen, while the full network shows a very
clear and crisp separation of latents that encode
different chunk patterns – with a 0.9928/0.0101
F1 macro-average/standard deviation – when spar-
sifying the information is slightly less crisp in
the 2D TSNE projection, but still high F1 macro-
average/standard deviation (0.9886/0.0038)
5.2 Localizing linguistic information in
sentence embeddings
We approach the isolation of linguistic information
with the following intuition: on each channel, the
CNN discovers different patterns in various regions
of the sentences. Some combination of these pat-
terns – i.e. some combinations of signals from the
CNN output – encode specific properties of the
sentences. These signals eventually reach the la-
tent layer. Previous experiments have shown that
this latent layer contains information about chunks
and their properties. Working backwards from the
latent layer to the sentence embedding – through
the CNN output layer, the different channels and
sentence embedding regions – helps us trace back
where the biggest changes are when the input sen-
tences have different properties.
To verify whether specific linguistic informa-
tion, like different number of chunks, or different
chunk properties, is encoded in different regions of
the sentence embeddings, we analyse the distribu-
tion of values in each network node in the encoder,
namely the CNN output nodes NCNN and the la-
tent nodes NL.
Figure 4: TSNE projection of the latent layer for
encoder-decoder with full network connections.
Figure 5: TSNE projection of the latent layer for sparsi-
fied encoder-decoder.
We denote Spthe set of input sentences that
share the same chunk pattern p(for instance, p=
"NP-s VP-s"). We pass their sentence embeddings
through the learned encoder, and gather the values
in each CNN output node:
Vp
CNN={Vp
CNN(nc)|nc∈NCNN}
Vp
CNN(nc) ={valnc(s)|s∈Sp}
andvalnc(s)is the value in the CNN output node
ncwhen the input is the embedding of sentence s.
To check for differences in how sentence with
different patterns are encoded, we will look at sets
of sentences Sp1andSp2where p1andp2are pat-
terns that differ minimally. We consider three such
minimal differences:
length one pattern has an extra (or one less) chunk
than the other but are otherwise identical ( np-s
vp-s vs.np-s pp1-s vp-s),
grammatical number the two patterns have the
same number of chunks, but one (and only
one) chunk has a different grammatical num-
ber than the other ( np-s pp1- svp-s vs.np-s
pp1-p vp-s),
subject-verb number alternation the two pat-
terns are identical except in the grammatical
number of the subject and verb ( np-spp1-s
vp-s vs.np-p pp1-s vp-p ).
To compare how chunk information is encoded
in sentences that have different patterns p1and
p2, we compare the sets of values in each CNN
output node nc:Vp1
CNN(nc)andVp2
CNN(nc). If
these value distributions are very different, this is
an indication that the area of a sentence embedding
where the signal to ncis coming from is involved
in encoding the type of information that is different
between p1andp2.
We perform this analysis in two steps: (i) a fil-
tering step that eliminates from the analysis the
CNN output nodes that do not encode differences
in behaviour between patterns, and (ii) a quantifi-
cation of the differences in the values in the node
for different patterns.
The filtering step is performed using a
two-sample Kolmogorov-Smirnov test (Hodges,
1958),5which provides information whether two
samples come from the same distribution. As we
are interested in the CNN output nodes where the
value distributions are different when the inputs are
sentences with different patterns, we will filter out
from the analysis the nodes ncwhere the sets of
values Vp
CNN(nc)come from the same distribution
for all patterns prepresented in the data.
For the remaining CNN output nodes, we
project the value distributions onto the same set
of bins, and then quantify the difference using
cosine distance. Specifically, we determine the
range of values for Vp
CNNfor all patterns p–
min VCNN, max VCNN, and split it into 100 bins.
For each CNN output node ncand pattern pwe
make a value distribution vector vp
ncfrom the
node’s set of values Vp
CNN(nc), w.r.t. the 100 bins.
We then compute a score for every pair of mini-
mally different patterns p1, p2for each node ncas
the cosine distance:
score nc(p1, p2) = 1−cos(vp1nc, vp2nc)
This score quantifies how different a region of
the sentence embedding is when encoding sen-
tences with different chunk patterns.
Localization results A first clue that informa-
tion related to chunk patterns in a sentence is lo-
calized is the fact that the filtering step using the
5We use the ks_2samp test in the scipy Python packagetwo-sample Kolmogorov-Smirnov test leads to the
removal of 83 out of 240 (34%) CNN output nodes.
For the remaining nodes where differences in
value distributions between different sentence pat-
terns exist, we compute the cosine distance be-
tween pairs of minimally different patterns with
respect to grammatical number, length and subject-
verb number alternations. Figure 6 shows the
differences in value distributions in each CNN
output nodes from each channel – channels are
reprezented on the y-axis, and the 5 latent units on
the x-axis in different colours. A stronger colour
indicates a stronger effect. More detailed plots are
included in Figure ??in the appendix.
These plots indicate that there
are few channel-sentence region
combinations that encode differ-
ences in chunk structure in the
input sentences. While in the
figure the sentence areas are il-
lustrated with equal sizes, the re-
gions are presented transposed
for space considerations, and
they have the shapes shown in the adjacent fig-
ure. The chunks and the chunk information seems
to be encoded in the bottom part of the sentence
embedding, and much of it in the bottom 2x24 area.
5.3 BLM tasks
To further test whether task specific information
is robust to sparsification, we use the two-level
variational encoder-decoder depicted in Figure 8.
An instance for a BLM task consists of a tuple,
comprising a sequence of sentences S={si|i=
1,7}as input, and an answer set with one correct
answer ac, and several incorrect answers aerr. The
sentence level of the 2-level encoder-decoder com-
presses the sentence embeddings of each of the
sentences in the input sequence into a small latent
vector. The sampled latent representations are then
used as the representations of the sentences in the
input sequence. This sequence representation is
passed as input to the BLM-level encoder-decoder,
it is compressed into a new latent layer, and the
sampled vector is then decoded into a sentence rep-
resentation that best matches the representation of
the correct answer.
BLM task results We evaluate the performance
of the sparsified 2-level V AE on the BLM tasks.
Only the first level of the V AE, the one process-
ing individual sentences, is sparsified as described
Figure 6: Average cosine distance between value distributions in each CNN output node (i.e. each node correspond-
ing to the application of the kernel from each channel on the sentence embeddings, according to the kernel size and
stride) for sets of sentences with minimally different patters: (left) patterns differ in only one grammatical number
attribute for one chunk, (middle) patterns differ only in length, (right) patterns differ only in the number of the
subject and verb. Each panel corresponds to one region of the sentence embedding the size of the kernel. The y-axis
represents the channels of the CNN. The x-axis represents the latent units in different colours (the stronger the color,
the higher the value, max = 1), and the pairs of compared patterns represented as adjacent rectangles.
Figure 7: Results in term of average F1 scores over 3 runs, for the BLM agreement (1) and verb alternations
ALT-ATL (2) and ATL-ALT (3)
Figure 8: A two-level variational encoder-decoder: the
top level compresses the sentence embeddings into a
latent layer, and the bottom level uses the compressed
sentence representations to solve the BLM tasks.
in section 5.1. Figure 7 shows the performance
of three system variations: (i) a one-level V AE
that processes the input sequence of sentences and
produces a sentence representation, (ii) the two-
level V AE described in more detail in (Nastase and
Merlo, 2024), (iii) the sparsified version of the sen-
tence level V AE in the two-level V AE. As in the
previous experiments, sparsification does not cause
harsh drops in performance for either of the two
BLM tasks. The reason for this is the same rea-
son we chose this particular data for experiments:
solving the task relies on the system having infor-
mation about the chunks in the sentence, and their
properties. As long as that type of information ispreserved, the tasks can be solved successfully.
We note two main changes however. In the agree-
ment task, the sparsified system registers a drop
in performance when trained on maximally lexi-
cally different data (type III). The two-level system
without sparsification also registers such a drop
in comparison with the baseline one-level encoder
decoder. Both these effects may be due to the am-
biguous supervision signal at the sentence level of
the system: while using type I and type II data with
little lexical variation, it is easier for the system
to focus on structural differences between the cor-
rect and incorrect output options. When using type
III data with much lexical variation, it is not clear
for the system what is the relevant dimension of
difference between the output options.
In the verb alternation task, previous results on
predicting the Agent-Theme-Location or the Agent-
Location-Theme alternation produced very similar
results. This is not the case here, but understanding
why this happens requires additional analysis.
6 Conclusions
Our aim was to understand how information is en-
coded in sentence embedding, given that previous
work has shown that various types of linguistic
information is encoded in a model’s layers and pa-
rameters. We investigated this question using a
dataset of sentences with specific chunk structure,
and two multiple-choice problems that require in-
formation about sentence chunks and their prop-
erties to be solved successfully. We have shown
that using a sparsified encoder-decoder system, the
sentence representations can be compressed into a
latent layer that encodes chunk structure properties.
We then traced back the signal from the latent layer
to the sentence embedding, to detect which areas
of the sentence embeddings change the most when
comparing sentences with different chunk patterns.
This analysis shows that such information is cap-
tured by a small number of channel-sentence area
combinations. Further experiments with the two
multiple-choice tasks have confirmed that chunk
information and their grammatical properties (for
the agreement BLM) and chunk information and
their semantic role properties (for the verb alterna-
tion BLM) are captured by the sparsified sentence
compression level. We envision further analyses to
see where the differences between chunk patterns
that have different semantic roles are encoded, and
get closer to decoding the sentence embeddings.
7 Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in future work.
Acknowledgments We gratefully acknowledge
the partial support of this work by the Swiss Na-
tional Science Foundation, through grant SNF Ad-
vanced grant TMAG-1_209426 to PM.
References
Yossi Adi, Einat Kermany, Yonatan Belinkov, Ofer Lavi,
and Yoav Goldberg. 2017. Fine-grained analysis
of sentence embeddings using auxiliary prediction
tasks. In 5th International Conference on Learning
Representations, ICLR 2017, Toulon, France, April24-26, 2017, Conference Track Proceedings . Open-
Review.net.
Aixiu An, Chunyang Jiang, Maria A. Rodriguez, Vivi
Nastase, and Paola Merlo. 2023. BLM-AgrF: A new
French benchmark to investigate generalization of
agreement in neural networks. In Proceedings of the
17th Conference of the European Chapter of the As-
sociation for Computational Linguistics , pages 1363–
1374, Dubrovnik, Croatia. Association for Computa-
tional Linguistics.
Steven Cao, Victor Sanh, and Alexander Rush. 2021.
Low-complexity probing via finding subnetworks. In
Proceedings of the 2021 Conference of the North
American Chapter of the Association for Computa-
tional Linguistics: Human Language Technologies ,
pages 960–966, Online. Association for Computa-
tional Linguistics.
Kevin Clark, Urvashi Khandelwal, Omer Levy, and
Christopher D. Manning. 2019. What does BERT
look at? an analysis of BERT’s attention. In Pro-
ceedings of the 2019 ACL Workshop BlackboxNLP:
Analyzing and Interpreting Neural Networks for NLP ,
pages 276–286, Florence, Italy. Association for Com-
putational Linguistics.
Kevin Clark, Minh-Thang Luong, Quoc V . Le, and
Christopher D. Manning. 2020. ELECTRA: Pre-
training text encoders as discriminators rather than
generators. In ICLR .
Simone Conia, Edoardo Barba, Alessandro Scirè, and
Roberto Navigli. 2022. Semantic role labeling meets
definition modeling: Using natural language to de-
scribe predicate-argument structures. In Findings
of the Association for Computational Linguistics:
EMNLP 2022 , pages 4253–4270, Abu Dhabi, United
Arab Emirates. Association for Computational Lin-
guistics.
Arthur Conmy, Augustine Mavor-Parker, Aengus Lynch,
Stefan Heimersheim, and Adrià Garriga-Alonso.
2023. Towards automated circuit discovery for mech-
anistic interpretability. In Advances in Neural Infor-
mation Processing Systems , volume 36, pages 16318–
16352. Curran Associates, Inc.
Alexis Conneau, German Kruszewski, Guillaume Lam-
ple, Loïc Barrault, and Marco Baroni. 2018. What
you can cram into a single $&!#* vector: Probing
sentence embeddings for linguistic properties. In
Proceedings of the 56th Annual Meeting of the As-
sociation for Computational Linguistics (Volume 1:
Long Papers) , pages 2126–2136, Melbourne, Aus-
tralia. Association for Computational Linguistics.
Róbert Csordás, Sjoerd van Steenkiste, and Jürgen
Schmidhuber. 2021. Are neural nets modular? in-
specting functional modularity through differentiable
weight masks. In Int. Conf. on Learning Representa-
tions (ICLR) , Virtual only.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. BERT: pre-training of
deep bidirectional transformers for language under-
standing. CoRR , abs/1810.04805.
Jonathan Frankle and Michael Carbin. 2018. The lottery
ticket hypothesis: Training pruned neural networks.
CoRR , abs/1803.03635.
Yoav Goldberg. 2019. Assessing bert’s syntactic abili-
ties. arXiv preprint arXiv:1901.05287 .
Pengcheng He, Xiaodong Liu, Jianfeng Gao, and
Weizhu Chen. 2020. Deberta: Decoding-
enhanced BERT with disentangled attention. CoRR ,
abs/2006.03654.
John Hewitt and Christopher D. Manning. 2019. A
structural probe for finding syntax in word represen-
tations. In Proceedings of the 2019 Conference of
the North American Chapter of the Association for
Computational Linguistics: Human Language Tech-
nologies, Volume 1 (Long and Short Papers) , pages
4129–4138, Minneapolis, Minnesota. Association for
Computational Linguistics.
Joseph L. Hodges. 1958. The significance probability
of the smirnov two-sample test. Arkiv für Matematik ,
3:469–486.
Daphne Ippolito, David Grangier, Douglas Eck, and
Chris Callison-Burch. 2020. Toward better storylines
with sentence-level language models. In Proceedings
of the 58th Annual Meeting of the Association for
Computational Linguistics , pages 7472–7478, Online.
Association for Computational Linguistics.
Zhenzhong Lan, Mingda Chen, Sebastian Goodman,
Kevin Gimpel, Piyush Sharma, and Radu Sori-
cut. 2019. ALBERT: A lite BERT for self-
supervised learning of language representations.
CoRR , abs/1909.11942.
Michael Lepori, Thomas Serre, and Ellie Pavlick. 2023.
Break it down: Evidence for structural composition-
ality in neural networks. Advances in Neural Infor-
mation Processing Systems , 36:42623–42660.
Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man-
dar Joshi, Danqi Chen, Omer Levy, Mike Lewis,
Luke Zettlemoyer, and Veselin Stoyanov. 2019.
Roberta: A robustly optimized bert pretraining ap-
proach. arXiv preprint arXiv:1907.11692 .
Christos Louizos, Max Welling, and Diederik P. Kingma.
2018. Learning sparse neural networks through l_0
regularization. In 6th International Conference on
Learning Representations, ICLR 2018, Vancouver,
BC, Canada, April 30 - May 3, 2018, Conference
Track Proceedings . OpenReview.net.
Paola Merlo. 2023. Blackbird language matrices
(BLM), a new task for rule-like generalization in neu-
ral networks: Motivations and formal specifications.
ArXiv , cs.CL 2306.11444.Vivi Nastase and Paola Merlo. 2023. Grammati-
cal information in BERT sentence embeddings as
two-dimensional arrays. In Proceedings of the
8th Workshop on Representation Learning for NLP
(RepL4NLP 2023) , pages 22–39, Toronto, Canada.
Association for Computational Linguistics.
Vivi Nastase and Paola Merlo. 2024. Are there iden-
tifiable structural parts in the sentence embedding
whole?
Dmitry Nikolaev and Sebastian Padó. 2023. The uni-
verse of utterances according to BERT. In Proceed-
ings of the 15th International Conference on Com-
putational Semantics , pages 99–105, Nancy, France.
Association for Computational Linguistics.
Juri Opitz and Anette Frank. 2022. SBERT studies
meaning representations: Decomposing sentence em-
beddings into explainable semantic features. In Pro-
ceedings of the 2nd Conference of the Asia-Pacific
Chapter of the Association for Computational Lin-
guistics and the 12th International Joint Conference
on Natural Language Processing (Volume 1: Long
Papers) , pages 625–638, Online only. Association for
Computational Linguistics.
Abhishek Panigrahi, Nikunj Saunshi, Haoyu Zhao, and
Sanjeev Arora. 2023. Task-specific skill localization
in fine-tuned language models. In International Con-
ference on Machine Learning , pages 27011–27033.
PMLR.
Isabel Papadimitriou, Ethan A. Chi, Richard Futrell, and
Kyle Mahowald. 2021. Deep subjecthood: Higher-
order grammatical features in multilingual BERT. In
Proceedings of the 16th Conference of the European
Chapter of the Association for Computational Lin-
guistics: Main Volume , pages 2522–2532, Online.
Association for Computational Linguistics.
Nils Reimers and Iryna Gurevych. 2019. Sentence-
BERT: Sentence embeddings using Siamese BERT-
networks. In Proceedings of the 2019 Conference on
Empirical | Section not found | Section not found | Methods in Natural Language Processing
and the 9th International Joint Conference on Natu-
ral Language Processing (EMNLP-IJCNLP) , pages
3982–3992, Hong Kong, China. Association for Com-
putational Linguistics.
Anna Rogers, Olga Kovaleva, and Anna Rumshisky.
2020. A primer in BERTology: What we know about
how BERT works. Transactions of the Association
for Computational Linguistics , 8:842–866.
Giuseppe Samo, Vivi Nastase, Chunyang Jiang, and
Paola Merlo. 2023. BLM-s/lE: A structured dataset
of English spray-load verb alternations for testing
generalization in LLMs. In | Section not found | Section not found | Section not found | results
show that such information is not distributed
over the entire sentence embedding, but rather
it is encoded in specific regions. Understand-
ing how the information from an input text is
compressed into sentence embeddings helps un-
derstand current transformer models and help
build future explainable neural models.
1 Introduction
In the quest for understanding transformer-based
models, much work has been dedicated to uncover
what kind of information is encoded in the model’s
various layers and parameters. These analyses have
provided several enlightening insights: (i) differ-
ent types of linguistic information – e.g. parts of
speech, syntactic structure, named entities – are
selectively more evident at different layers of the
model (Tenney et al., 2019a; Rogers et al., 2020),
(ii) subnetworks can be identified that seem to en-
code particular linguistic functionalities (Csordás
et al., 2021), and (iii) fine-tuning for specific tasks
can be focused on very small subsets of parameters,
on different parts of a model’s layers (Panigrahi
et al., 2023). While these analyses and probes have
focused on the insides of the models, mostly their
parameters and layers, testing their impact is usu-
ally done by using the output of the model, namelytoken or sentence embeddings, to solve specific
tasks. The link between the inside of the model and
its outputs is usually not explicitly investigated.
We ask several facets of this question here: how
are the internally-detected information types and
structures reflected in the model’s output? And how
are arbitrarily long and complex sentences encoded
systematically in a fixed-sized vector?
Understanding what kind of information the sen-
tence embeddings encode, and how, has multiple
benefits: (i) it connects internal changes in the
model parameters and structure with changes in
its outputs; (ii) it contributes to verifying the ro-
bustness of models and whether or not they rely on
shallow or accidental regularities in the data; (iii) it
narrows down the field of search when a language
model produces wrong outputs, and (iv) it helps
maximize the use of training data for developing
more robust models from smaller textual resources.
Transformer-based models usually use a token-
focused learning objective, and have a weaker su-
pervision signal at the sentence level – e.g. a next
sentence prediction (Devlin et al., 2018), or sen-
tence order information (Lan et al., 2019). Despite
this focus, high performance in a variety of tasks
(using raw or fine-tuned sentence embeddings) as
well as direct probing shows that sentence represen-
tations encode a variety of linguistic information
(Conneau et al., 2018). On the other hand, direct
exploration of BERT sentence embeddings has also
shown that they contain mostly shallow informa-
tion, related to sentence length and lexical variation,
and that many of their dimensions are correlated,
indicating that either information is redundantly
encoded, or that not all dimensions encode useful
information (Nikolaev and Padó, 2023). Some of
this preexisting work assumes that sentence embed-
dings encode information in an overt manner, for
example, each principal component dimension is
responsible for encoding some type of information.
We adopt the different view that information inarXiv:2407.18119v1 [cs.CL] 25 Jul 2024
sentence embeddings may be encoded in merged
layers, in a manner similar to audio signals being
composed of overlapping signals of different fre-
quencies. We hypothesize that each such layer may
encode different types of information. We aim to
test this hypothesis and check (i) whether we can
separate such layers, and (ii) investigate whether
information about specific chunks in a sentence
–noun,verb, or prepositional phrases– is encoded in
different layers and parts of a sentence embedding.
We perform our investigation in an environment
with data focused on specific grammatical phenom-
ena, while displaying lexical, structural and seman-
tic variation, and a previously developed system
that has been shown to detect the targeted phenom-
ena well (Nastase and Merlo, 2024). The system is
a variational encoder-decoder, with an encoder that
compresses the information in the input into a very
low-dimensional latent vector. Nastase and Merlo
(2024) have shown that the sentence embeddings,
and their compressed representations on the latent
layer, encode information about chunks – noun,
verb, prepositional phrases – and their linguistic
properties.
The current study investigates the general hy-
pothesis indicated above by specifically exploring
two new research questions in this setting:
1.Whether a targeted sparsification of the sys-
tem maintains a high performance on the task,
indicating that information about chunks in
the sentence is localizable.
2.Contingent on the answer to the first question,
we trace back the signal from the latent layer
to the input sentence embeddings, and analyze
how specific differences in chunk properties
– different number of chunks, or chunks that
differ from each other only on one property
(e.g. grammatical number) – are localized and
reflected in the sentence embeddings.
The code and data are available at
https://github.com/CLCL-Geneva/
BLM-SNFDisentangling .
2 Related work
Sentence embeddings Transformer models in-
duce contextual token embeddings by passing the
embedding vectors through successive layers us-
ing multi-head attention that allows for tokens to
influence each other’s representation at each suc-
cessive step (Vaswani et al., 2017). The modelfocuses on the token embeddings, as the tokens
expected on the output layer provide the training
signal. There are numerous variations on the BERT
(Devlin et al., 2018) transformer model1, that vary
in the way the models are trained (Liu et al., 2019),
how they combine (or not) the positional and to-
ken embeddings (He et al., 2020), how the input
is presented to the model (Liu et al., 2019; Clark
et al., 2020). With regards to the sentence-level
supervision signal, BERT (Devlin et al., 2018) uses
the next sentence prediction objective, ALBERT
(Lan et al., 2019), aiming to improve coherence,
uses sentence order prediction. It is more common
to further train or fine-tune a pre-trained model to
produce sentence embeddings fitting specific tasks,
such as story continuation (Ippolito et al., 2020) or
sentence similarity (Reimers and Gurevych, 2019).
Electra (Clark et al., 2020) does not have a
sentence-level objective, but it relies on replaced
token detection, which relies on the sentence con-
text to determine whether a (number of) token(s)
in the given sentence were replaced by a generator
sample. This leads to sentence embeddings that
perform well on tasks such as Question Answering,
or detecting verb classes (Yi et al., 2022).
Probing embeddings and models for linguistic
information Most work investigating the kind of
knowledge captured by transformer-based models
have focused on analysing the architecture of the
model (Tenney et al., 2019b; Rogers et al., 2020) to
determine the localization and flow of information
through the model’s layers. There is also much
work on analyzing the induced token embeddings
to determine what kind of linguistic information
they encode, such as sentence structure (Hewitt
and Manning, 2019), predicate argument structure
(Conia et al., 2022), subjecthood and objecthood
(Papadimitriou et al., 2021), among others. Testing
whether sentence representation contain specific
types of linguistic information has been done using
task (or information)-specific classifiers (Adi et al.,
2017; Conneau et al., 2018; Goldberg, 2019; Wil-
son et al., 2023). Opitz and Frank (2022) aim to
map subsets of dimensions of fine-tuned sentence
embeddings to semantic features.
Sparsification Deep learning models have bil-
lions of parameters. This makes them not only
incomprehensible, but also expensive to train. The
1https://huggingface.co/docs/transformers/en/
model_summary
lottery ticket hypothesis (Frankle and Carbin, 2018)
posits that large networks can be reduced to sub-
networks that encode efficiently the functionality
of the entire network. Detecting functional subnet-
works can be done a posteriori , over a pre-learned
network to investigate the functionality of detected
subnetworks (Csordás et al., 2021), the potential
compositionality of the learned model (Lepori et al.,
2023), or where task-specific skills are encoded in
a fine-tuned model (Panigrahi et al., 2023).
Instead of learning a sparse network over a pre-
learned model, Cao et al. (2021) use a pruning-
based approach to finding subnetworks in a pre-
trained model that performs some linguistic task.
Pruning can be done at several levels of granularity:
weights, neurons, layers. Their analyses confirm
previous investigations of the types of information
encoded in different layers of a transformer (Con-
neau et al., 2018). Conmy et al. (2023) introduce
the Automatic Circuit DisCovery (ACDC) algo-
rithm, which adapts subnetwork probing and head
importance score for pruning to discover circuits
that implement specific linguistic functions.
Sparsification can also be achieved using L0reg-
ularization, as the pruning would be done directly
during training by encouraging weights to become
exactly zero. Louizos et al. (2018); Savarese et al.
(2020), among others, implement solutions to the
issue that L0regularization is non-differentiable,
and test it on image classification.
The cited work focuses on the parameters of the
model, and sparsification approaches aiming to de-
tect the subnetworks to which specific skills or
linguistic information can be ascribed. Our focus,
instead, is the output of transformer-based mod-
els, in particular sentence embeddings, which we
investigate using targeted sparsification.
3 Approach overview
We investigate whether we can identify specific
sentence properties in sentence embeddings. Nas-
tase and Merlo (2024) have shown that using
an encoder-decoder architecture, sentence embed-
dings can be compressed into a latent representa-
tion that preserves information about chunks in a
sentence, and their properties necessary to solve a
specific linguistic task.
We first test whether we can sparsify this archi-
tecture in a targeted manner, such that each region
of the sentence embedding contributes a signal to
only one unit of the latent layer. This allows us toisolate different parts of the sentence embedding.
After establishing that sparsification does not
lead to a dramatic drop in performance, we trace
back the signal from the latent layer to the sentence
embeddings, and test whether we can localize in-
formation about how different numbers of chunks,
or chunks with different properties, are encoded.
In the final step, we use the sparse encoder-
decoder sentence compression system as the first
in a two-layer system used to solve language tasks –
called Blackbird Language Matrices (Merlo, 2023)
– that require chunk and chunk properties informa-
tion. The first layer will compress each sentence
into a very small latent vector, and this represen-
tation is then used on the second layer to solve a
pattern detection problem that relies on information
about chunks in a sentence and their pattern across
a sequence of sentences.
4 Data
We use two data types: (i) a dataset of sentences
with known chunk structure and chunk properties,
(ii) two datasets representing two multiple-choice
problems, whose solution requires understanding
the chunk structure and chunk properties of the
sentences in each instance.
4.1 A dataset of sentences
We start with an artificially-created set of sentences
built from noun, prepositional and verb phrases.
Each sentence has one of the following structures:
NP [PP 1[PP 2]] VP , where the parentheses sur-
round optional structure. Each chunk can have
singular or plural form, with agreement between
the first NP (the subject) and the VP. This leads to
14’336 sentences with one of 14 patterns.
The dataset consists of ordered pairs of one input
sentence and N(=7) output sentences, extracted
from the set described above. Only one of the out-
put sentences has the same chunk pattern as the
input sentence, and is considered as the correct
output. We select 4004 instances uniformly dis-
tributed over the 14 patterns, which are split into
train:dev:test – 2576:630:798.
4.2 Multiple Choice Problems: Blackbird
Language Matrices
Blackbird Language Matrices (BLMs) (Merlo,
2023) are language versions of the visual Raven
Progressive Matrices (RPMs). Like the RPMs, they
are multiple-choice problems. The input is a se-
quence of 7 sentences built using specific rules, and
BLM agreement problem
CONTEXT TEMPLATE
NP-sg PP1-sg VP-sg
NP-pl PP1-sg VP-pl
NP-sg PP1-pl VP-sg
NP-pl PP1-pl VP-pl
NP-sg PP1-sg PP2-sg VP-sg
NP-pl PP1-sg PP2-sg VP-pl
NP-sg PP1-pl PP2-sg VP-sg
ANSWER SET
NP-sg PP1-sg et NP2 VP-sg Coord
NP-pl PP1-pl NP2-sg VP-pl correct
NP-sg PP1-sg VP-sg WNA
NP-pl PP1-pl NP2-pl VP-sg AE_V
NP-pl PP1-sg NP2-pl VP-sg AE_N1
NP-pl PP1-pl NP2-sg VP-sg AE_N2
NP-pl PP1-sg PP1-sg VP-pl WN1
NP-pl PP1-pl PP2-pl VP-pl WN2BLM verb alternation problem
CONTEXT TEMPLATE
NP-Agent Verb NP-Loc PP-Theme
NP-Theme VerbPass PP-Agent
NP-Theme VerbPass PP-Loc PP-Agent
NP-Theme VerbPass PP-Loc
NP-Loc VerbPass PP-Agent
NP-Loc VerbPass PP-Theme PP-Agent
NP-Loc VerbPass PP-Theme
ANSWER SET
NP-Agent Verb NP-Theme PP-Loc CORRECT
NP-Agent *VerbPass NP-Theme PP-Loc A GENT ACT
NP-Agent Verb NP-Theme *NP-Loc A LT1
NP-Agent Verb *PP-Theme PP-Loc A LT2
NP-Agent Verb *[NP-Theme PP-Loc] N OEMB
NP-Agent Verb NP-Theme *PP-Loc L EXPREP
*NP-Theme Verb NP-Agent PP-Loc SSM1
*NP-Loc Verb NP-Agent PP-Theme SSM2
*NP-Theme Verb NP-Loc PP-Agent AASSM
Figure 1: Structure of two BLM problems, in terms of chunks in sentences and sequence structure.
the correct answer fits within the sequence defined
by these rules. The incorrect options are built by
corrupting some of the underlying generating rules
of the input sentence sequence. Solving the prob-
lem requires identifying the entities (the chunks),
their relevant attributes (their morphological or se-
mantic properties) and their connecting operators.
We use two BLM datasets: (i) BLM-AgrF – sub-
ject verb agreement in French (An et al., 2023),
and (ii) BLM-s/lE – the spray-load verb alterna-
tions in English2(Samo et al., 2023). The structure
of these datasets – in terms of the sentence chunks
and sequence structure – is shown in Figure 1.
Datasets statistics Table 1 shows the datasets
statistics. Each set is split 90:10 into train:test sub-
sets, and then we randomly sample 2000 instances
as train data. 20% of the train data is used for de-
velopment. Types I, II, III correspond to different
amounts of lexical variation within an instance.
Subj.-verb agr. Verb alternations
ALT-ATL ATL-ALT
Type I 2000:252 2000:375 2000:375
Type II 2000:4866 2000:1500 2000:1500
Type III 2000:4869 2000:1500 2000:1500
Table 1: Train:Test statistics for the two BLM problems.
To solve a BLM instance, the system processes
the input sentence sequence and outputs a sentence
representation that will be compared to the repre-
sentation of the sentences in the answer set. The
candidate answer closest to the generated sentence
representation will be considered the correct one.
2Agent-Location-Theme (ALT) – Agent-Theme-Location
(ATL)We run the experiments on the BLMs for agree-
ment and on the verb alternation BLMs. While the
information necessary to solve the agreement task
is more structural, solving the verb alternation task
requires not only structural information on chunks,
but also semantic information, as syntactically sim-
ilar chunks play different roles in a sentence.
5 Experiments
We present a progression of experiments.
1.Using the dataset of sentences with known
chunk structure, we test whether a sparse vari-
ational encoder-decoder system can distill in-
formation about the chunk structure of a sen-
tence from its embedding.
2.We analyze the sparse model, and trace the
information from the latent layer back to the
sentence embedding to understand where in
the sentence embeddings these differences are
encoded.
3.We combine the sparsified variational encoder-
decoder with another V AE-like layer to solve
the BLM tasks, and test whether the latent
layer sentence encodings maintain informa-
tion useful for the tasks.
All experiments use Electra (Clark et al., 2019)3.
We use as sentence representations the embedding
of the [CLS] token, reshaped as a two dimensional
array with shape 32x24.
3Electra pretrained model: google/electra-base-
discriminator
The experiments are analyzed through the out-
put of the system, in terms of average F1 score
over three runs. For the investigations of the sen-
tence embeddings, we also analyze the compressed
vectors on the latent layer, to determine whether
chunk patterns are encoded in these vectors. If
these vectors cluster by the chunk pattern of the
corresponding sentences it will indicate that sen-
tence chunk patterns were indeed detected and are
encoded differently in the latent layer.
5.1 Sparsification
Nastase and Merlo (2024) have shown that sentence
embeddings contain information about the chunk
structure and their properties using an encoder-
decoder architecture that compresses the relevant
information into a small latent layer. They build
on Nastase and Merlo (2023) who show that re-
shaping a sentence embedding from the commonly
used one-dimensional array to a two-dimensional
representation allows grammatical information to
become more readily accessible.
We adopt the system of (Nastase and Merlo,
2024), with the same architecture (including num-
ber of CNN channels and kernel size), and sparsify
it, to determine whether specific information can
be localized in sentence embeddings. The encoder
of the system consists of a CNN layer followed by
a FFNN, that compresses the information into a
latent layer, as illustrated in Figure 2.
input convolution
(40 channels)
CNN FFNNlinearized
output
of CNNlatentEncoder architecture
Figure 2: Details of the encoder architecture
The CNN layer in the encoder detects a different
pattern in the sentence representation on each of its
40 channels. The linear layer compresses the lin-
earized output of the CNN into a very small latent
layer (length 5). A vector is sampled from this, and
then decoded into a sentence representation using
a decoder which is a mirror of the encoder.
An instance consists of an input sentence s, and
7 output sentences, only one of which has the samechunk structure as the input and is considered the
correct one (section 4.1). The aim is to guide
the system to capture information about the chunk
structure of the sentences in the latent layer, by
using a max-margin loss function that assigns a
higher score to the correct option relative to the
others. Formally, if esis the embedding of the in-
put sentence s,ˆesis the embedding output by the
decoder, ecis the embedding of the correct option
andei, i= 1,6are the embeddings of the other
options, and mm is the maxmargin function, then:
loss(s) =mm(ˆes, ec,{ei|i= 1,6}) +KL(zs||N(0,1))
mm(ˆes, ec, ei)=
max(0,1−score (ˆes, ec) +P6
i=1score (ˆes, ei)/6)
We want to sparsify this network in a targeted
way: we enforce that each output unit from the
CNN layer will contribute to only one unit in the
latent layer. Figure 3 illustrates the process.
1
2
3
nA
B
X1
2
3
nA
B
Xlinearized
output
of CNNlatent latent linearized
output
of CNNFFNN sparsification
Figure 3: Separating linguistic signals by masking the
one-layer FFNN
To enforce this behaviour, we use an approach
inspired from sparsification (Savarese et al., 2020)
and subnetworking (Lepori et al., 2023). Instead
of considering the output of the CNN as the input
layer of a linear network, we make each CNN out-
put unit the input of a separate linear network, con-
nected to the latent layer. We apply a mask mto the
weights Wof this network, and compute a masked
weight matrix Wm=W×softmax (M/τ),
where τis a temperature parameter used to push
the softmax function towards a one-hot vector.
We use a kernel 15x154and equal stride (15x15)
to have a very clear separation of the information
flow from the sentence embedding to the latent
4We adopt the size of the kernel from previous work.
layer. This will ensure our sparsification desidera-
tum, and the learned network will have a particular
configuration: if NCNN is the set of output nodes
from the CNN, and NLare the nodes on the latent
layer, then the sets of CNN output nodes connected
to each of the latent units are disjunct:
∀nl∈NL, Sl
CNN ={nc∈NCNN|Wm(nl, nc)>0}
and if i̸=jthenSi
CNN∩Sj
CNN=∅
Sparsification results Despite the fact that this
type of sparsification is very harsh, and channels
the information from the sentence embedding into
very few paths on the way to the latent layer, the
results in terms of average F1-score/standard devi-
ation over three runs without 0.997 (0.0035) and
with sparsification 0.977 (0.0095) are close. While
this difference is rather small, we notice a big-
ger difference in the latent layer. Figure 5 shows
the TSNE projections of the latent layers. As
can be seen, while the full network shows a very
clear and crisp separation of latents that encode
different chunk patterns – with a 0.9928/0.0101
F1 macro-average/standard deviation – when spar-
sifying the information is slightly less crisp in
the 2D TSNE projection, but still high F1 macro-
average/standard deviation (0.9886/0.0038)
5.2 Localizing linguistic information in
sentence embeddings
We approach the isolation of linguistic information
with the following intuition: on each channel, the
CNN discovers different patterns in various regions
of the sentences. Some combination of these pat-
terns – i.e. some combinations of signals from the
CNN output – encode specific properties of the
sentences. These signals eventually reach the la-
tent layer. Previous experiments have shown that
this latent layer contains information about chunks
and their properties. Working backwards from the
latent layer to the sentence embedding – through
the CNN output layer, the different channels and
sentence embedding regions – helps us trace back
where the biggest changes are when the input sen-
tences have different properties.
To verify whether specific linguistic informa-
tion, like different number of chunks, or different
chunk properties, is encoded in different regions of
the sentence embeddings, we analyse the distribu-
tion of values in each network node in the encoder,
namely the CNN output nodes NCNN and the la-
tent nodes NL.
Figure 4: TSNE projection of the latent layer for
encoder-decoder with full network connections.
Figure 5: TSNE projection of the latent layer for sparsi-
fied encoder-decoder.
We denote Spthe set of input sentences that
share the same chunk pattern p(for instance, p=
"NP-s VP-s"). We pass their sentence embeddings
through the learned encoder, and gather the values
in each CNN output node:
Vp
CNN={Vp
CNN(nc)|nc∈NCNN}
Vp
CNN(nc) ={valnc(s)|s∈Sp}
andvalnc(s)is the value in the CNN output node
ncwhen the input is the embedding of sentence s.
To check for differences in how sentence with
different patterns are encoded, we will look at sets
of sentences Sp1andSp2where p1andp2are pat-
terns that differ minimally. We consider three such
minimal differences:
length one pattern has an extra (or one less) chunk
than the other but are otherwise identical ( np-s
vp-s vs.np-s pp1-s vp-s),
grammatical number the two patterns have the
same number of chunks, but one (and only
one) chunk has a different grammatical num-
ber than the other ( np-s pp1- svp-s vs.np-s
pp1-p vp-s),
subject-verb number alternation the two pat-
terns are identical except in the grammatical
number of the subject and verb ( np-spp1-s
vp-s vs.np-p pp1-s vp-p ).
To compare how chunk information is encoded
in sentences that have different patterns p1and
p2, we compare the sets of values in each CNN
output node nc:Vp1
CNN(nc)andVp2
CNN(nc). If
these value distributions are very different, this is
an indication that the area of a sentence embedding
where the signal to ncis coming from is involved
in encoding the type of information that is different
between p1andp2.
We perform this analysis in two steps: (i) a fil-
tering step that eliminates from the analysis the
CNN output nodes that do not encode differences
in behaviour between patterns, and (ii) a quantifi-
cation of the differences in the values in the node
for different patterns.
The filtering step is performed using a
two-sample Kolmogorov-Smirnov test (Hodges,
1958),5which provides information whether two
samples come from the same distribution. As we
are interested in the CNN output nodes where the
value distributions are different when the inputs are
sentences with different patterns, we will filter out
from the analysis the nodes ncwhere the sets of
values Vp
CNN(nc)come from the same distribution
for all patterns prepresented in the data.
For the remaining CNN output nodes, we
project the value distributions onto the same set
of bins, and then quantify the difference using
cosine distance. Specifically, we determine the
range of values for Vp
CNNfor all patterns p–
min VCNN, max VCNN, and split it into 100 bins.
For each CNN output node ncand pattern pwe
make a value distribution vector vp
ncfrom the
node’s set of values Vp
CNN(nc), w.r.t. the 100 bins.
We then compute a score for every pair of mini-
mally different patterns p1, p2for each node ncas
the cosine distance:
score nc(p1, p2) = 1−cos(vp1nc, vp2nc)
This score quantifies how different a region of
the sentence embedding is when encoding sen-
tences with different chunk patterns.
Localization results A first clue that informa-
tion related to chunk patterns in a sentence is lo-
calized is the fact that the filtering step using the
5We use the ks_2samp test in the scipy Python packagetwo-sample Kolmogorov-Smirnov test leads to the
removal of 83 out of 240 (34%) CNN output nodes.
For the remaining nodes where differences in
value distributions between different sentence pat-
terns exist, we compute the cosine distance be-
tween pairs of minimally different patterns with
respect to grammatical number, length and subject-
verb number alternations. Figure 6 shows the
differences in value distributions in each CNN
output nodes from each channel – channels are
reprezented on the y-axis, and the 5 latent units on
the x-axis in different colours. A stronger colour
indicates a stronger effect. More detailed plots are
included in Figure ??in the appendix.
These plots indicate that there
are few channel-sentence region
combinations that encode differ-
ences in chunk structure in the
input sentences. While in the
figure the sentence areas are il-
lustrated with equal sizes, the re-
gions are presented transposed
for space considerations, and
they have the shapes shown in the adjacent fig-
ure. The chunks and the chunk information seems
to be encoded in the bottom part of the sentence
embedding, and much of it in the bottom 2x24 area.
5.3 BLM tasks
To further test whether task specific information
is robust to sparsification, we use the two-level
variational encoder-decoder depicted in Figure 8.
An instance for a BLM task consists of a tuple,
comprising a sequence of sentences S={si|i=
1,7}as input, and an answer set with one correct
answer ac, and several incorrect answers aerr. The
sentence level of the 2-level encoder-decoder com-
presses the sentence embeddings of each of the
sentences in the input sequence into a small latent
vector. The sampled latent representations are then
used as the representations of the sentences in the
input sequence. This sequence representation is
passed as input to the BLM-level encoder-decoder,
it is compressed into a new latent layer, and the
sampled vector is then decoded into a sentence rep-
resentation that best matches the representation of
the correct answer.
BLM task results We evaluate the performance
of the sparsified 2-level V AE on the BLM tasks.
Only the first level of the V AE, the one process-
ing individual sentences, is sparsified as described
Figure 6: Average cosine distance between value distributions in each CNN output node (i.e. each node correspond-
ing to the application of the kernel from each channel on the sentence embeddings, according to the kernel size and
stride) for sets of sentences with minimally different patters: (left) patterns differ in only one grammatical number
attribute for one chunk, (middle) patterns differ only in length, (right) patterns differ only in the number of the
subject and verb. Each panel corresponds to one region of the sentence embedding the size of the kernel. The y-axis
represents the channels of the CNN. The x-axis represents the latent units in different colours (the stronger the color,
the higher the value, max = 1), and the pairs of compared patterns represented as adjacent rectangles.
Figure 7: Results in term of average F1 scores over 3 runs, for the BLM agreement (1) and verb alternations
ALT-ATL (2) and ATL-ALT (3)
Figure 8: A two-level variational encoder-decoder: the
top level compresses the sentence embeddings into a
latent layer, and the bottom level uses the compressed
sentence representations to solve the BLM tasks.
in section 5.1. Figure 7 shows the performance
of three system variations: (i) a one-level V AE
that processes the input sequence of sentences and
produces a sentence representation, (ii) the two-
level V AE described in more detail in (Nastase and
Merlo, 2024), (iii) the sparsified version of the sen-
tence level V AE in the two-level V AE. As in the
previous experiments, sparsification does not cause
harsh drops in performance for either of the two
BLM tasks. The reason for this is the same rea-
son we chose this particular data for experiments:
solving the task relies on the system having infor-
mation about the chunks in the sentence, and their
properties. As long as that type of information ispreserved, the tasks can be solved successfully.
We note two main changes however. In the agree-
ment task, the sparsified system registers a drop
in performance when trained on maximally lexi-
cally different data (type III). The two-level system
without sparsification also registers such a drop
in comparison with the baseline one-level encoder
decoder. Both these effects may be due to the am-
biguous supervision signal at the sentence level of
the system: while using type I and type II data with
little lexical variation, it is easier for the system
to focus on structural differences between the cor-
rect and incorrect output options. When using type
III data with much lexical variation, it is not clear
for the system what is the relevant dimension of
difference between the output options.
In the verb alternation task, previous results on
predicting the Agent-Theme-Location or the Agent-
Location-Theme alternation produced very similar
results. This is not the case here, but understanding
why this happens requires additional analysis.
6 Conclusions
Our aim was to understand how information is en-
coded in sentence embedding, given that previous
work has shown that various types of linguistic
information is encoded in a model’s layers and pa-
rameters. We investigated this question using a
dataset of sentences with specific chunk structure,
and two multiple-choice problems that require in-
formation about sentence chunks and their prop-
erties to be solved successfully. We have shown
that using a sparsified encoder-decoder system, the
sentence representations can be compressed into a
latent layer that encodes chunk structure properties.
We then traced back the signal from the latent layer
to the sentence embedding, to detect which areas
of the sentence embeddings change the most when
comparing sentences with different chunk patterns.
This analysis shows that such information is cap-
tured by a small number of channel-sentence area
combinations. Further experiments with the two
multiple-choice tasks have confirmed that chunk
information and their grammatical properties (for
the agreement BLM) and chunk information and
their semantic role properties (for the verb alterna-
tion BLM) are captured by the sparsified sentence
compression level. We envision further analyses to
see where the differences between chunk patterns
that have different semantic roles are encoded, and
get closer to decoding the sentence embeddings.
7 Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in future work.
Acknowledgments We gratefully acknowledge
the partial support of this work by the Swiss Na-
tional Science Foundation, through grant SNF Ad-
vanced grant TMAG-1_209426 to PM.
References
Yossi Adi, Einat Kermany, Yonatan Belinkov, Ofer Lavi,
and Yoav Goldberg. 2017. Fine-grained analysis
of sentence embeddings using auxiliary prediction
tasks. In 5th International Conference on Learning
Representations, ICLR 2017, Toulon, France, April24-26, 2017, Conference Track Proceedings . Open-
Review.net.
Aixiu An, Chunyang Jiang, Maria A. Rodriguez, Vivi
Nastase, and Paola Merlo. 2023. BLM-AgrF: A new
French benchmark to investigate generalization of
agreement in neural networks. In Proceedings of the
17th Conference of the European Chapter of the As-
sociation for Computational Linguistics , pages 1363–
1374, Dubrovnik, Croatia. Association for Computa-
tional Linguistics.
Steven Cao, Victor Sanh, and Alexander Rush. 2021.
Low-complexity probing via finding subnetworks. In
Proceedings of the 2021 Conference of the North
American Chapter of the Association for Computa-
tional Linguistics: Human Language Technologies ,
pages 960–966, Online. Association for Computa-
tional Linguistics.
Kevin Clark, Urvashi Khandelwal, Omer Levy, and
Christopher D. Manning. 2019. What does BERT
look at? an analysis of BERT’s attention. In Pro-
ceedings of the 2019 ACL Workshop BlackboxNLP:
Analyzing and Interpreting Neural Networks for NLP ,
pages 276–286, Florence, Italy. Association for Com-
putational Linguistics.
Kevin Clark, Minh-Thang Luong, Quoc V . Le, and
Christopher D. Manning. 2020. ELECTRA: Pre-
training text encoders as discriminators rather than
generators. In ICLR .
Simone Conia, Edoardo Barba, Alessandro Scirè, and
Roberto Navigli. 2022. Semantic role labeling meets
definition modeling: Using natural language to de-
scribe predicate-argument structures. In | Findings
of the Association for Computational Linguistics:
EMNLP 2022 , pages 4253–4270, Abu Dhabi, United
Arab Emirates. Association for Computational Lin-
guistics.
Arthur Conmy, Augustine Mavor-Parker, Aengus Lynch,
Stefan Heimersheim, and Adrià Garriga-Alonso.
2023. Towards automated circuit discovery for mech-
anistic interpretability. In Advances in Neural Infor-
mation Processing Systems , volume 36, pages 16318–
16352. Curran Associates, Inc.
Alexis Conneau, German Kruszewski, Guillaume Lam-
ple, Loïc Barrault, and Marco Baroni. 2018. What
you can cram into a single $&!#* vector: Probing
sentence embeddings for linguistic properties. In
Proceedings of the 56th Annual Meeting of the As-
sociation for Computational Linguistics (Volume 1:
Long Papers) , pages 2126–2136, Melbourne, Aus-
tralia. Association for Computational Linguistics.
Róbert Csordás, Sjoerd van Steenkiste, and Jürgen
Schmidhuber. 2021. Are neural nets modular? in-
specting functional modularity through differentiable
weight masks. In Int. Conf. on Learning Representa-
tions (ICLR) , Virtual only.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. BERT: pre-training of
deep bidirectional transformers for language under-
standing. CoRR , abs/1810.04805.
Jonathan Frankle and Michael Carbin. 2018. The lottery
ticket hypothesis: Training pruned neural networks.
CoRR , abs/1803.03635.
Yoav Goldberg. 2019. Assessing bert’s syntactic abili-
ties. arXiv preprint arXiv:1901.05287 .
Pengcheng He, Xiaodong Liu, Jianfeng Gao, and
Weizhu Chen. 2020. Deberta: Decoding-
enhanced BERT with disentangled attention. CoRR ,
abs/2006.03654.
John Hewitt and Christopher D. Manning. 2019. A
structural probe for finding syntax in word represen-
tations. In Proceedings of the 2019 Conference of
the North American Chapter of the Association for
Computational Linguistics: Human Language Tech-
nologies, Volume 1 (Long and Short Papers) , pages
4129–4138, Minneapolis, Minnesota. Association for
Computational Linguistics.
Joseph L. Hodges. 1958. The significance probability
of the smirnov two-sample test. Arkiv für Matematik ,
3:469–486.
Daphne Ippolito, David Grangier, Douglas Eck, and
Chris Callison-Burch. 2020. Toward better storylines
with sentence-level language models. In Proceedings
of the 58th Annual Meeting of the Association for
Computational Linguistics , pages 7472–7478, Online.
Association for Computational Linguistics.
Zhenzhong Lan, Mingda Chen, Sebastian Goodman,
Kevin Gimpel, Piyush Sharma, and Radu Sori-
cut. 2019. ALBERT: A lite BERT for self-
supervised learning of language representations.
CoRR , abs/1909.11942.
Michael Lepori, Thomas Serre, and Ellie Pavlick. 2023.
Break it down: Evidence for structural composition-
ality in neural networks. Advances in Neural Infor-
mation Processing Systems , 36:42623–42660.
Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man-
dar Joshi, Danqi Chen, Omer Levy, Mike Lewis,
Luke Zettlemoyer, and Veselin Stoyanov. 2019.
Roberta: A robustly optimized bert pretraining ap-
proach. arXiv preprint arXiv:1907.11692 .
Christos Louizos, Max Welling, and Diederik P. Kingma.
2018. Learning sparse neural networks through l_0
regularization. In 6th International Conference on
Learning Representations, ICLR 2018, Vancouver,
BC, Canada, April 30 - May 3, 2018, Conference
Track Proceedings . OpenReview.net.
Paola Merlo. 2023. Blackbird language matrices
(BLM), a new task for rule-like generalization in neu-
ral networks: Motivations and formal specifications.
ArXiv , cs.CL 2306.11444.Vivi Nastase and Paola Merlo. 2023. Grammati-
cal information in BERT sentence embeddings as
two-dimensional arrays. In Proceedings of the
8th Workshop on Representation Learning for NLP
(RepL4NLP 2023) , pages 22–39, Toronto, Canada.
Association for Computational Linguistics.
Vivi Nastase and Paola Merlo. 2024. Are there iden-
tifiable structural parts in the sentence embedding
whole?
Dmitry Nikolaev and Sebastian Padó. 2023. The uni-
verse of utterances according to BERT. In Proceed-
ings of the 15th International Conference on Com-
putational Semantics , pages 99–105, Nancy, France.
Association for Computational Linguistics.
Juri Opitz and Anette Frank. 2022. SBERT studies
meaning representations: Decomposing sentence em-
beddings into explainable semantic features. In Pro-
ceedings of the 2nd Conference of the Asia-Pacific
Chapter of the Association for Computational Lin-
guistics and the 12th International Joint Conference
on Natural Language Processing (Volume 1: Long
Papers) , pages 625–638, Online only. Association for
Computational Linguistics.
Abhishek Panigrahi, Nikunj Saunshi, Haoyu Zhao, and
Sanjeev Arora. 2023. Task-specific skill localization
in fine-tuned language models. In International Con-
ference on Machine Learning , pages 27011–27033.
PMLR.
Isabel Papadimitriou, Ethan A. Chi, Richard Futrell, and
Kyle Mahowald. 2021. Deep subjecthood: Higher-
order grammatical features in multilingual BERT. In
Proceedings of the 16th Conference of the European
Chapter of the Association for Computational Lin-
guistics: Main Volume , pages 2522–2532, Online.
Association for Computational Linguistics.
Nils Reimers and Iryna Gurevych. 2019. Sentence-
BERT: Sentence embeddings using Siamese BERT-
networks. In Proceedings of the 2019 Conference on
Empirical Methods in Natural Language Processing
and the 9th International Joint Conference on Natu-
ral Language Processing (EMNLP-IJCNLP) , pages
3982–3992, Hong Kong, China. Association for Com-
putational Linguistics.
Anna Rogers, Olga Kovaleva, and Anna Rumshisky.
2020. A primer in BERTology: What we know about
how BERT works. Transactions of the Association
for Computational Linguistics , 8:842–866.
Giuseppe Samo, Vivi Nastase, Chunyang Jiang, and
Paola Merlo. 2023. BLM-s/lE: A structured dataset
of English spray-load verb alternations for testing
generalization in LLMs. In Findings of the 2023
Conference on Empirical Methods in Natural Lan-
guage Processing .
Pedro Savarese, Hugo Silva, and Michael Maire. 2020.
Winning the lottery with continuous sparsification.
InProceedings of the 34th International Conference
on Neural Information Processing Systems , NIPS’20,
Red Hook, NY , USA. Curran Associates Inc.
Ian Tenney, Dipanjan Das, and Ellie Pavlick. 2019a.
BERT rediscovers the classical NLP pipeline. In
Proceedings of the 57th Annual Meeting of the Asso-
ciation for Computational Linguistics , pages 4593–
4601, Florence, Italy. Association for Computational
Linguistics.
Ian Tenney, Patrick Xia, Berlin Chen, Alex Wang, Adam
Poliak, R Thomas McCoy, Najoung Kim, Benjamin
Van Durme, Samuel R Bowman, Dipanjan Das, et al.
2019b. What do you learn from context? probing for
sentence structure in contextualized word represen-
tations. In The Seventh International Conference on
Learning Representations (ICLR) , pages 235–249.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Michael Wilson, Jackson Petty, and Robert Frank. 2023.
How abstract is linguistic generalization in large lan-
guage models? experiments with argument structure.
Transactions of the Association for Computational
Linguistics , 11:1377–1395.
David Yi, James Bruno, Jiayu Han, Peter Zukerman,
and Shane Steinert-Threlkeld. 2022. Probing for un-
derstanding of English verb classes and alternations
in large pre-trained language models. In Proceedings
of the Fifth BlackboxNLP Workshop on Analyzing
and Interpreting Neural Networks for NLP , pages
142–152, Abu Dhabi, United Arab Emirates (Hybrid).
Association for Computational Linguistics. | Section not found | Section not found | Section not found | Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in | future work. | Conclusions
Our aim was to understand how information is en-
coded in sentence embedding, given that previous
work has shown that various types of linguistic
information is encoded in a model’s layers and pa-
rameters. We investigated this question using a
dataset of sentences with specific chunk structure,
and two multiple-choice problems that require in-
formation about sentence chunks and their prop-
erties to be solved successfully. We have shown
that using a sparsified encoder-decoder system, the
sentence representations can be compressed into a
latent layer that encodes chunk structure properties.
We then traced back the signal from the latent layer
to the sentence embedding, to detect which areas
of the sentence embeddings change the most when
comparing sentences with different chunk patterns.
This analysis shows that such information is cap-
tured by a small number of channel-sentence area
combinations. Further experiments with the two
multiple-choice tasks have confirmed that chunk
information and their grammatical properties (for
the agreement BLM) and chunk information and
their semantic role properties (for the verb alterna-
tion BLM) are captured by the sparsified sentence
compression level. We envision further analyses to
see where the differences between chunk patterns
that have different semantic roles are encoded, and
get closer to decoding the sentence embeddings.
7 Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in future work. | summary
lottery ticket hypothesis (Frankle and Carbin, 2018)
posits that large networks can be reduced to sub-
networks that encode efficiently the functionality
of the entire network. Detecting functional subnet-
works can be done a posteriori , over a pre-learned
network to investigate the functionality of detected
subnetworks (Csordás et al., 2021), the potential
compositionality of the learned model (Lepori et al.,
2023), or where task-specific skills are encoded in
a fine-tuned model (Panigrahi et al., 2023).
Instead of learning a sparse network over a pre-
learned model, Cao et al. (2021) use a pruning-
based approach to finding subnetworks in a pre-
trained model that performs some linguistic task.
Pruning can be done at several levels of granularity:
weights, neurons, layers. Their analyses confirm
previous investigations of the types of information
encoded in different layers of a transformer (Con-
neau et al., 2018). Conmy et al. (2023) introduce
the Automatic Circuit DisCovery (ACDC) algo-
rithm, which adapts subnetwork probing and head
importance score for pruning to discover circuits
that implement specific linguistic functions.
Sparsification can also be achieved using L0reg-
ularization, as the pruning would be done directly
during training by encouraging weights to become
exactly zero. Louizos et al. (2018); Savarese et al.
(2020), among others, implement solutions to the
issue that L0regularization is non-differentiable,
and test it on image classification.
The cited work focuses on the parameters of the
model, and sparsification approaches aiming to de-
tect the subnetworks to which specific skills or
linguistic information can be ascribed. Our focus,
instead, is the output of transformer-based mod-
els, in particular sentence embeddings, which we
investigate using targeted sparsification.
3 Approach overview
We investigate whether we can identify specific
sentence properties in sentence embeddings. Nas-
tase and Merlo (2024) have shown that using
an encoder-decoder architecture, sentence embed-
dings can be compressed into a latent representa-
tion that preserves information about chunks in a
sentence, and their properties necessary to solve a
specific linguistic task.
We first test whether we can sparsify this archi-
tecture in a targeted manner, such that each region
of the sentence embedding contributes a signal to
only one unit of the latent layer. This allows us toisolate different parts of the sentence embedding.
After establishing that sparsification does not
lead to a dramatic drop in performance, we trace
back the signal from the latent layer to the sentence
embeddings, and test whether we can localize in-
formation about how different numbers of chunks,
or chunks with different properties, are encoded.
In the final step, we use the sparse encoder-
decoder sentence compression system as the first
in a two-layer system used to solve language tasks –
called Blackbird Language Matrices (Merlo, 2023)
– that require chunk and chunk properties informa-
tion. The first layer will compress each sentence
into a very small latent vector, and this represen-
tation is then used on the second layer to solve a
pattern detection problem that relies on information
about chunks in a sentence and their pattern across
a sequence of sentences.
4 Data
We use two data types: (i) a dataset of sentences
with known chunk structure and chunk properties,
(ii) two datasets representing two multiple-choice
problems, whose solution requires understanding
the chunk structure and chunk properties of the
sentences in each instance.
4.1 A dataset of sentences
We start with an artificially-created set of sentences
built from noun, prepositional and verb phrases.
Each sentence has one of the following structures:
NP [PP 1[PP 2]] VP , where the parentheses sur-
round optional structure. Each chunk can have
singular or plural form, with agreement between
the first NP (the subject) and the VP. This leads to
14’336 sentences with one of 14 patterns.
The dataset consists of ordered pairs of one input
sentence and N(=7) output sentences, extracted
from the set described above. Only one of the out-
put sentences has the same chunk pattern as the
input sentence, and is considered as the correct
output. We select 4004 instances uniformly dis-
tributed over the 14 patterns, which are split into
train:dev:test – 2576:630:798.
4.2 Multiple Choice Problems: Blackbird
Language Matrices
Blackbird Language Matrices (BLMs) (Merlo,
2023) are language versions of the visual Raven
Progressive Matrices (RPMs). Like the RPMs, they
are multiple-choice problems. The input is a se-
quence of 7 sentences built using specific rules, and
BLM agreement problem
CONTEXT TEMPLATE
NP-sg PP1-sg VP-sg
NP-pl PP1-sg VP-pl
NP-sg PP1-pl VP-sg
NP-pl PP1-pl VP-pl
NP-sg PP1-sg PP2-sg VP-sg
NP-pl PP1-sg PP2-sg VP-pl
NP-sg PP1-pl PP2-sg VP-sg
ANSWER SET
NP-sg PP1-sg et NP2 VP-sg Coord
NP-pl PP1-pl NP2-sg VP-pl correct
NP-sg PP1-sg VP-sg WNA
NP-pl PP1-pl NP2-pl VP-sg AE_V
NP-pl PP1-sg NP2-pl VP-sg AE_N1
NP-pl PP1-pl NP2-sg VP-sg AE_N2
NP-pl PP1-sg PP1-sg VP-pl WN1
NP-pl PP1-pl PP2-pl VP-pl WN2BLM verb alternation problem
CONTEXT TEMPLATE
NP-Agent Verb NP-Loc PP-Theme
NP-Theme VerbPass PP-Agent
NP-Theme VerbPass PP-Loc PP-Agent
NP-Theme VerbPass PP-Loc
NP-Loc VerbPass PP-Agent
NP-Loc VerbPass PP-Theme PP-Agent
NP-Loc VerbPass PP-Theme
ANSWER SET
NP-Agent Verb NP-Theme PP-Loc CORRECT
NP-Agent *VerbPass NP-Theme PP-Loc A GENT ACT
NP-Agent Verb NP-Theme *NP-Loc A LT1
NP-Agent Verb *PP-Theme PP-Loc A LT2
NP-Agent Verb *[NP-Theme PP-Loc] N OEMB
NP-Agent Verb NP-Theme *PP-Loc L EXPREP
*NP-Theme Verb NP-Agent PP-Loc SSM1
*NP-Loc Verb NP-Agent PP-Theme SSM2
*NP-Theme Verb NP-Loc PP-Agent AASSM
Figure 1: Structure of two BLM problems, in terms of chunks in sentences and sequence structure.
the correct answer fits within the sequence defined
by these rules. The incorrect options are built by
corrupting some of the underlying generating rules
of the input sentence sequence. Solving the prob-
lem requires identifying the entities (the chunks),
their relevant attributes (their morphological or se-
mantic properties) and their connecting operators.
We use two BLM datasets: (i) BLM-AgrF – sub-
ject verb agreement in French (An et al., 2023),
and (ii) BLM-s/lE – the spray-load verb alterna-
tions in English2(Samo et al., 2023). The structure
of these datasets – in terms of the sentence chunks
and sequence structure – is shown in Figure 1.
Datasets statistics Table 1 shows the datasets
statistics. Each set is split 90:10 into train:test sub-
sets, and then we randomly sample 2000 instances
as train data. 20% of the train data is used for de-
velopment. Types I, II, III correspond to different
amounts of lexical variation within an instance.
Subj.-verb agr. Verb alternations
ALT-ATL ATL-ALT
Type I 2000:252 2000:375 2000:375
Type II 2000:4866 2000:1500 2000:1500
Type III 2000:4869 2000:1500 2000:1500
Table 1: Train:Test statistics for the two BLM problems.
To solve a BLM instance, the system processes
the input sentence sequence and outputs a sentence
representation that will be compared to the repre-
sentation of the sentences in the answer set. The
candidate answer closest to the generated sentence
representation will be considered the correct one.
2Agent-Location-Theme (ALT) – Agent-Theme-Location
(ATL)We run the experiments on the BLMs for agree-
ment and on the verb alternation BLMs. While the
information necessary to solve the agreement task
is more structural, solving the verb alternation task
requires not only structural information on chunks,
but also semantic information, as syntactically sim-
ilar chunks play different roles in a sentence.
5 Experiments
We present a progression of experiments.
1.Using the dataset of sentences with known
chunk structure, we test whether a sparse vari-
ational encoder-decoder system can distill in-
formation about the chunk structure of a sen-
tence from its embedding.
2.We analyze the sparse model, and trace the
information from the latent layer back to the
sentence embedding to understand where in
the sentence embeddings these differences are
encoded.
3.We combine the sparsified variational encoder-
decoder with another V AE-like layer to solve
the BLM tasks, and test whether the latent
layer sentence encodings maintain informa-
tion useful for the tasks.
All experiments use Electra (Clark et al., 2019)3.
We use as sentence representations the embedding
of the [CLS] token, reshaped as a two dimensional
array with shape 32x24.
3Electra pretrained model: google/electra-base-
discriminator
The experiments are analyzed through the out-
put of the system, in terms of average F1 score
over three runs. For the investigations of the sen-
tence embeddings, we also analyze the compressed
vectors on the latent layer, to determine whether
chunk patterns are encoded in these vectors. If
these vectors cluster by the chunk pattern of the
corresponding sentences it will indicate that sen-
tence chunk patterns were indeed detected and are
encoded differently in the latent layer.
5.1 Sparsification
Nastase and Merlo (2024) have shown that sentence
embeddings contain information about the chunk
structure and their properties using an encoder-
decoder architecture that compresses the relevant
information into a small latent layer. They build
on Nastase and Merlo (2023) who show that re-
shaping a sentence embedding from the commonly
used one-dimensional array to a two-dimensional
representation allows grammatical information to
become more readily accessible.
We adopt the system of (Nastase and Merlo,
2024), with the same architecture (including num-
ber of CNN channels and kernel size), and sparsify
it, to determine whether specific information can
be localized in sentence embeddings. The encoder
of the system consists of a CNN layer followed by
a FFNN, that compresses the information into a
latent layer, as illustrated in Figure 2.
input convolution
(40 channels)
CNN FFNNlinearized
output
of CNNlatentEncoder architecture
Figure 2: Details of the encoder architecture
The CNN layer in the encoder detects a different
pattern in the sentence representation on each of its
40 channels. The linear layer compresses the lin-
earized output of the CNN into a very small latent
layer (length 5). A vector is sampled from this, and
then decoded into a sentence representation using
a decoder which is a mirror of the encoder.
An instance consists of an input sentence s, and
7 output sentences, only one of which has the samechunk structure as the input and is considered the
correct one (section 4.1). The aim is to guide
the system to capture information about the chunk
structure of the sentences in the latent layer, by
using a max-margin loss function that assigns a
higher score to the correct option relative to the
others. Formally, if esis the embedding of the in-
put sentence s,ˆesis the embedding output by the
decoder, ecis the embedding of the correct option
andei, i= 1,6are the embeddings of the other
options, and mm is the maxmargin function, then:
loss(s) =mm(ˆes, ec,{ei|i= 1,6}) +KL(zs||N(0,1))
mm(ˆes, ec, ei)=
max(0,1−score (ˆes, ec) +P6
i=1score (ˆes, ei)/6)
We want to sparsify this network in a targeted
way: we enforce that each output unit from the
CNN layer will contribute to only one unit in the
latent layer. Figure 3 illustrates the process.
1
2
3
nA
B
X1
2
3
nA
B
Xlinearized
output
of CNNlatent latent linearized
output
of CNNFFNN sparsification
Figure 3: Separating linguistic signals by masking the
one-layer FFNN
To enforce this behaviour, we use an approach
inspired from sparsification (Savarese et al., 2020)
and subnetworking (Lepori et al., 2023). Instead
of considering the output of the CNN as the input
layer of a linear network, we make each CNN out-
put unit the input of a separate linear network, con-
nected to the latent layer. We apply a mask mto the
weights Wof this network, and compute a masked
weight matrix Wm=W×softmax (M/τ),
where τis a temperature parameter used to push
the softmax function towards a one-hot vector.
We use a kernel 15x154and equal stride (15x15)
to have a very clear separation of the information
flow from the sentence embedding to the latent
4We adopt the size of the kernel from previous work.
layer. This will ensure our sparsification desidera-
tum, and the learned network will have a particular
configuration: if NCNN is the set of output nodes
from the CNN, and NLare the nodes on the latent
layer, then the sets of CNN output nodes connected
to each of the latent units are disjunct:
∀nl∈NL, Sl
CNN ={nc∈NCNN|Wm(nl, nc)>0}
and if i̸=jthenSi
CNN∩Sj
CNN=∅
Sparsification results Despite the fact that this
type of sparsification is very harsh, and channels
the information from the sentence embedding into
very few paths on the way to the latent layer, the
results in terms of average F1-score/standard devi-
ation over three runs without 0.997 (0.0035) and
with sparsification 0.977 (0.0095) are close. While
this difference is rather small, we notice a big-
ger difference in the latent layer. Figure 5 shows
the TSNE projections of the latent layers. As
can be seen, while the full network shows a very
clear and crisp separation of latents that encode
different chunk patterns – with a 0.9928/0.0101
F1 macro-average/standard deviation – when spar-
sifying the information is slightly less crisp in
the 2D TSNE projection, but still high F1 macro-
average/standard deviation (0.9886/0.0038)
5.2 Localizing linguistic information in
sentence embeddings
We approach the isolation of linguistic information
with the following intuition: on each channel, the
CNN discovers different patterns in various regions
of the sentences. Some combination of these pat-
terns – i.e. some combinations of signals from the
CNN output – encode specific properties of the
sentences. These signals eventually reach the la-
tent layer. Previous experiments have shown that
this latent layer contains information about chunks
and their properties. Working backwards from the
latent layer to the sentence embedding – through
the CNN output layer, the different channels and
sentence embedding regions – helps us trace back
where the biggest changes are when the input sen-
tences have different properties.
To verify whether specific linguistic informa-
tion, like different number of chunks, or different
chunk properties, is encoded in different regions of
the sentence embeddings, we analyse the distribu-
tion of values in each network node in the encoder,
namely the CNN output nodes NCNN and the la-
tent nodes NL.
Figure 4: TSNE projection of the latent layer for
encoder-decoder with full network connections.
Figure 5: TSNE projection of the latent layer for sparsi-
fied encoder-decoder.
We denote Spthe set of input sentences that
share the same chunk pattern p(for instance, p=
"NP-s VP-s"). We pass their sentence embeddings
through the learned encoder, and gather the values
in each CNN output node:
Vp
CNN={Vp
CNN(nc)|nc∈NCNN}
Vp
CNN(nc) ={valnc(s)|s∈Sp}
andvalnc(s)is the value in the CNN output node
ncwhen the input is the embedding of sentence s.
To check for differences in how sentence with
different patterns are encoded, we will look at sets
of sentences Sp1andSp2where p1andp2are pat-
terns that differ minimally. We consider three such
minimal differences:
length one pattern has an extra (or one less) chunk
than the other but are otherwise identical ( np-s
vp-s vs.np-s pp1-s vp-s),
grammatical number the two patterns have the
same number of chunks, but one (and only
one) chunk has a different grammatical num-
ber than the other ( np-s pp1- svp-s vs.np-s
pp1-p vp-s),
subject-verb number alternation the two pat-
terns are identical except in the grammatical
number of the subject and verb ( np-spp1-s
vp-s vs.np-p pp1-s vp-p ).
To compare how chunk information is encoded
in sentences that have different patterns p1and
p2, we compare the sets of values in each CNN
output node nc:Vp1
CNN(nc)andVp2
CNN(nc). If
these value distributions are very different, this is
an indication that the area of a sentence embedding
where the signal to ncis coming from is involved
in encoding the type of information that is different
between p1andp2.
We perform this analysis in two steps: (i) a fil-
tering step that eliminates from the analysis the
CNN output nodes that do not encode differences
in behaviour between patterns, and (ii) a quantifi-
cation of the differences in the values in the node
for different patterns.
The filtering step is performed using a
two-sample Kolmogorov-Smirnov test (Hodges,
1958),5which provides information whether two
samples come from the same distribution. As we
are interested in the CNN output nodes where the
value distributions are different when the inputs are
sentences with different patterns, we will filter out
from the analysis the nodes ncwhere the sets of
values Vp
CNN(nc)come from the same distribution
for all patterns prepresented in the data.
For the remaining CNN output nodes, we
project the value distributions onto the same set
of bins, and then quantify the difference using
cosine distance. Specifically, we determine the
range of values for Vp
CNNfor all patterns p–
min VCNN, max VCNN, and split it into 100 bins.
For each CNN output node ncand pattern pwe
make a value distribution vector vp
ncfrom the
node’s set of values Vp
CNN(nc), w.r.t. the 100 bins.
We then compute a score for every pair of mini-
mally different patterns p1, p2for each node ncas
the cosine distance:
score nc(p1, p2) = 1−cos(vp1nc, vp2nc)
This score quantifies how different a region of
the sentence embedding is when encoding sen-
tences with different chunk patterns.
Localization results A first clue that informa-
tion related to chunk patterns in a sentence is lo-
calized is the fact that the filtering step using the
5We use the ks_2samp test in the scipy Python packagetwo-sample Kolmogorov-Smirnov test leads to the
removal of 83 out of 240 (34%) CNN output nodes.
For the remaining nodes where differences in
value distributions between different sentence pat-
terns exist, we compute the cosine distance be-
tween pairs of minimally different patterns with
respect to grammatical number, length and subject-
verb number alternations. Figure 6 shows the
differences in value distributions in each CNN
output nodes from each channel – channels are
reprezented on the y-axis, and the 5 latent units on
the x-axis in different colours. A stronger colour
indicates a stronger effect. More detailed plots are
included in Figure ??in the appendix.
These plots indicate that there
are few channel-sentence region
combinations that encode differ-
ences in chunk structure in the
input sentences. While in the
figure the sentence areas are il-
lustrated with equal sizes, the re-
gions are presented transposed
for space considerations, and
they have the shapes shown in the adjacent fig-
ure. The chunks and the chunk information seems
to be encoded in the bottom part of the sentence
embedding, and much of it in the bottom 2x24 area.
5.3 BLM tasks
To further test whether task specific information
is robust to sparsification, we use the two-level
variational encoder-decoder depicted in Figure 8.
An instance for a BLM task consists of a tuple,
comprising a sequence of sentences S={si|i=
1,7}as input, and an answer set with one correct
answer ac, and several incorrect answers aerr. The
sentence level of the 2-level encoder-decoder com-
presses the sentence embeddings of each of the
sentences in the input sequence into a small latent
vector. The sampled latent representations are then
used as the representations of the sentences in the
input sequence. This sequence representation is
passed as input to the BLM-level encoder-decoder,
it is compressed into a new latent layer, and the
sampled vector is then decoded into a sentence rep-
resentation that best matches the representation of
the correct answer.
BLM task results We evaluate the performance
of the sparsified 2-level V AE on the BLM tasks.
Only the first level of the V AE, the one process-
ing individual sentences, is sparsified as described
Figure 6: Average cosine distance between value distributions in each CNN output node (i.e. each node correspond-
ing to the application of the kernel from each channel on the sentence embeddings, according to the kernel size and
stride) for sets of sentences with minimally different patters: (left) patterns differ in only one grammatical number
attribute for one chunk, (middle) patterns differ only in length, (right) patterns differ only in the number of the
subject and verb. Each panel corresponds to one region of the sentence embedding the size of the kernel. The y-axis
represents the channels of the CNN. The x-axis represents the latent units in different colours (the stronger the color,
the higher the value, max = 1), and the pairs of compared patterns represented as adjacent rectangles.
Figure 7: Results in term of average F1 scores over 3 runs, for the BLM agreement (1) and verb alternations
ALT-ATL (2) and ATL-ALT (3)
Figure 8: A two-level variational encoder-decoder: the
top level compresses the sentence embeddings into a
latent layer, and the bottom level uses the compressed
sentence representations to solve the BLM tasks.
in section 5.1. Figure 7 shows the performance
of three system variations: (i) a one-level V AE
that processes the input sequence of sentences and
produces a sentence representation, (ii) the two-
level V AE described in more detail in (Nastase and
Merlo, 2024), (iii) the sparsified version of the sen-
tence level V AE in the two-level V AE. As in the
previous experiments, sparsification does not cause
harsh drops in performance for either of the two
BLM tasks. The reason for this is the same rea-
son we chose this particular data for experiments:
solving the task relies on the system having infor-
mation about the chunks in the sentence, and their
properties. As long as that type of information ispreserved, the tasks can be solved successfully.
We note two main changes however. In the agree-
ment task, the sparsified system registers a drop
in performance when trained on maximally lexi-
cally different data (type III). The two-level system
without sparsification also registers such a drop
in comparison with the baseline one-level encoder
decoder. Both these effects may be due to the am-
biguous supervision signal at the sentence level of
the system: while using type I and type II data with
little lexical variation, it is easier for the system
to focus on structural differences between the cor-
rect and incorrect output options. When using type
III data with much lexical variation, it is not clear
for the system what is the relevant dimension of
difference between the output options.
In the verb alternation task, previous results on
predicting the Agent-Theme-Location or the Agent-
Location-Theme alternation produced very similar
results. This is not the case here, but understanding
why this happens requires additional analysis.
6 Conclusions
Our aim was to understand how information is en-
coded in sentence embedding, given that previous
work has shown that various types of linguistic
information is encoded in a model’s layers and pa-
rameters. We investigated this question using a
dataset of sentences with specific chunk structure,
and two multiple-choice problems that require in-
formation about sentence chunks and their prop-
erties to be solved successfully. We have shown
that using a sparsified encoder-decoder system, the
sentence representations can be compressed into a
latent layer that encodes chunk structure properties.
We then traced back the signal from the latent layer
to the sentence embedding, to detect which areas
of the sentence embeddings change the most when
comparing sentences with different chunk patterns.
This analysis shows that such information is cap-
tured by a small number of channel-sentence area
combinations. Further experiments with the two
multiple-choice tasks have confirmed that chunk
information and their grammatical properties (for
the agreement BLM) and chunk information and
their semantic role properties (for the verb alterna-
tion BLM) are captured by the sparsified sentence
compression level. We envision further analyses to
see where the differences between chunk patterns
that have different semantic roles are encoded, and
get closer to decoding the sentence embeddings.
7 Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in future work. | Acknowledgments We gratefully acknowledge
the partial support of this work by the Swiss Na-
tional Science Foundation, through grant SNF Ad-
vanced grant TMAG-1_209426 to PM. | References
Yossi Adi, Einat Kermany, Yonatan Belinkov, Ofer Lavi,
and Yoav Goldberg. 2017. Fine-grained analysis
of sentence embeddings using auxiliary prediction
tasks. In 5th International Conference on Learning
Representations, ICLR 2017, Toulon, France, April24-26, 2017, Conference Track Proceedings . Open-
Review.net.
Aixiu An, Chunyang Jiang, Maria A. Rodriguez, Vivi
Nastase, and Paola Merlo. 2023. BLM-AgrF: A new
French benchmark to investigate generalization of
agreement in neural networks. In Proceedings of the
17th Conference of the European Chapter of the As-
sociation for Computational Linguistics , pages 1363–
1374, Dubrovnik, Croatia. Association for Computa-
tional Linguistics.
Steven Cao, Victor Sanh, and Alexander Rush. 2021.
Low-complexity probing via finding subnetworks. In
Proceedings of the 2021 Conference of the North
American Chapter of the Association for Computa-
tional Linguistics: Human Language Technologies ,
pages 960–966, Online. Association for Computa-
tional Linguistics.
Kevin Clark, Urvashi Khandelwal, Omer Levy, and
Christopher D. Manning. 2019. What does BERT
look at? an analysis of BERT’s attention. In Pro-
ceedings of the 2019 ACL Workshop BlackboxNLP:
Analyzing and Interpreting Neural Networks for NLP ,
pages 276–286, Florence, Italy. Association for Com-
putational Linguistics.
Kevin Clark, Minh-Thang Luong, Quoc V . Le, and
Christopher D. Manning. 2020. ELECTRA: Pre-
training text encoders as discriminators rather than
generators. In ICLR .
Simone Conia, Edoardo Barba, Alessandro Scirè, and
Roberto Navigli. 2022. Semantic role labeling meets
definition modeling: Using natural language to de-
scribe predicate-argument structures. In Findings
of the Association for Computational Linguistics:
EMNLP 2022 , pages 4253–4270, Abu Dhabi, United
Arab Emirates. Association for Computational Lin-
guistics.
Arthur Conmy, Augustine Mavor-Parker, Aengus Lynch,
Stefan Heimersheim, and Adrià Garriga-Alonso.
2023. Towards automated circuit discovery for mech-
anistic interpretability. In Advances in Neural Infor-
mation Processing Systems , volume 36, pages 16318–
16352. Curran Associates, Inc.
Alexis Conneau, German Kruszewski, Guillaume Lam-
ple, Loïc Barrault, and Marco Baroni. 2018. What
you can cram into a single $&!#* vector: Probing
sentence embeddings for linguistic properties. In
Proceedings of the 56th Annual Meeting of the As-
sociation for Computational Linguistics (Volume 1:
Long Papers) , pages 2126–2136, Melbourne, Aus-
tralia. Association for Computational Linguistics.
Róbert Csordás, Sjoerd van Steenkiste, and Jürgen
Schmidhuber. 2021. Are neural nets modular? in-
specting functional modularity through differentiable
weight masks. In Int. Conf. on Learning Representa-
tions (ICLR) , Virtual only.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. BERT: pre-training of
deep bidirectional transformers for language under-
standing. CoRR , abs/1810.04805.
Jonathan Frankle and Michael Carbin. 2018. The lottery
ticket hypothesis: Training pruned neural networks.
CoRR , abs/1803.03635.
Yoav Goldberg. 2019. Assessing bert’s syntactic abili-
ties. arXiv preprint arXiv:1901.05287 .
Pengcheng He, Xiaodong Liu, Jianfeng Gao, and
Weizhu Chen. 2020. Deberta: Decoding-
enhanced BERT with disentangled attention. CoRR ,
abs/2006.03654.
John Hewitt and Christopher D. Manning. 2019. A
structural probe for finding syntax in word represen-
tations. In Proceedings of the 2019 Conference of
the North American Chapter of the Association for
Computational Linguistics: Human Language Tech-
nologies, Volume 1 (Long and Short Papers) , pages
4129–4138, Minneapolis, Minnesota. Association for
Computational Linguistics.
Joseph L. Hodges. 1958. The significance probability
of the smirnov two-sample test. Arkiv für Matematik ,
3:469–486.
Daphne Ippolito, David Grangier, Douglas Eck, and
Chris Callison-Burch. 2020. Toward better storylines
with sentence-level language models. In Proceedings
of the 58th Annual Meeting of the Association for
Computational Linguistics , pages 7472–7478, Online.
Association for Computational Linguistics.
Zhenzhong Lan, Mingda Chen, Sebastian Goodman,
Kevin Gimpel, Piyush Sharma, and Radu Sori-
cut. 2019. ALBERT: A lite BERT for self-
supervised learning of language representations.
CoRR , abs/1909.11942.
Michael Lepori, Thomas Serre, and Ellie Pavlick. 2023.
Break it down: Evidence for structural composition-
ality in neural networks. Advances in Neural Infor-
mation Processing Systems , 36:42623–42660.
Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man-
dar Joshi, Danqi Chen, Omer Levy, Mike Lewis,
Luke Zettlemoyer, and Veselin Stoyanov. 2019.
Roberta: A robustly optimized bert pretraining ap-
proach. arXiv preprint arXiv:1907.11692 .
Christos Louizos, Max Welling, and Diederik P. Kingma.
2018. Learning sparse neural networks through l_0
regularization. In 6th International Conference on
Learning Representations, ICLR 2018, Vancouver,
BC, Canada, April 30 - May 3, 2018, Conference
Track Proceedings . OpenReview.net.
Paola Merlo. 2023. Blackbird language matrices
(BLM), a new task for rule-like generalization in neu-
ral networks: Motivations and formal specifications.
ArXiv , cs.CL 2306.11444.Vivi Nastase and Paola Merlo. 2023. Grammati-
cal information in BERT sentence embeddings as
two-dimensional arrays. In Proceedings of the
8th Workshop on Representation Learning for NLP
(RepL4NLP 2023) , pages 22–39, Toronto, Canada.
Association for Computational Linguistics.
Vivi Nastase and Paola Merlo. 2024. Are there iden-
tifiable structural parts in the sentence embedding
whole?
Dmitry Nikolaev and Sebastian Padó. 2023. The uni-
verse of utterances according to BERT. In Proceed-
ings of the 15th International Conference on Com-
putational Semantics , pages 99–105, Nancy, France.
Association for Computational Linguistics.
Juri Opitz and Anette Frank. 2022. SBERT studies
meaning representations: Decomposing sentence em-
beddings into explainable semantic features. In Pro-
ceedings of the 2nd Conference of the Asia-Pacific
Chapter of the Association for Computational Lin-
guistics and the 12th International Joint Conference
on Natural Language Processing (Volume 1: Long
Papers) , pages 625–638, Online only. Association for
Computational Linguistics.
Abhishek Panigrahi, Nikunj Saunshi, Haoyu Zhao, and
Sanjeev Arora. 2023. Task-specific skill localization
in fine-tuned language models. In International Con-
ference on Machine Learning , pages 27011–27033.
PMLR.
Isabel Papadimitriou, Ethan A. Chi, Richard Futrell, and
Kyle Mahowald. 2021. Deep subjecthood: Higher-
order grammatical features in multilingual BERT. In
Proceedings of the 16th Conference of the European
Chapter of the Association for Computational Lin-
guistics: Main Volume , pages 2522–2532, Online.
Association for Computational Linguistics.
Nils Reimers and Iryna Gurevych. 2019. Sentence-
BERT: Sentence embeddings using Siamese BERT-
networks. In Proceedings of the 2019 Conference on
Empirical Methods in Natural Language Processing
and the 9th International Joint Conference on Natu-
ral Language Processing (EMNLP-IJCNLP) , pages
3982–3992, Hong Kong, China. Association for Com-
putational Linguistics.
Anna Rogers, Olga Kovaleva, and Anna Rumshisky.
2020. A primer in BERTology: What we know about
how BERT works. Transactions of the Association
for Computational Linguistics , 8:842–866.
Giuseppe Samo, Vivi Nastase, Chunyang Jiang, and
Paola Merlo. 2023. BLM-s/lE: A structured dataset
of English spray-load verb alternations for testing
generalization in LLMs. In Findings of the 2023
Conference on Empirical Methods in Natural Lan-
guage Processing .
Pedro Savarese, Hugo Silva, and Michael Maire. 2020.
Winning the lottery with continuous sparsification.
InProceedings of the 34th International Conference
on Neural Information Processing Systems , NIPS’20,
Red Hook, NY , USA. Curran Associates Inc.
Ian Tenney, Dipanjan Das, and Ellie Pavlick. 2019a.
BERT rediscovers the classical NLP pipeline. In
Proceedings of the 57th Annual Meeting of the Asso-
ciation for Computational Linguistics , pages 4593–
4601, Florence, Italy. Association for Computational
Linguistics.
Ian Tenney, Patrick Xia, Berlin Chen, Alex Wang, Adam
Poliak, R Thomas McCoy, Najoung Kim, Benjamin
Van Durme, Samuel R Bowman, Dipanjan Das, et al.
2019b. What do you learn from context? probing for
sentence structure in contextualized word represen-
tations. In The Seventh International Conference on
Learning Representations (ICLR) , pages 235–249.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Michael Wilson, Jackson Petty, and Robert Frank. 2023.
How abstract is linguistic generalization in large lan-
guage models? experiments with argument structure.
Transactions of the Association for Computational
Linguistics , 11:1377–1395.
David Yi, James Bruno, Jiayu Han, Peter Zukerman,
and Shane Steinert-Threlkeld. 2022. Probing for un-
derstanding of English verb classes and alternations
in large pre-trained language models. In Proceedings
of the Fifth BlackboxNLP Workshop on Analyzing
and Interpreting Neural Networks for NLP , pages
142–152, Abu Dhabi, United Arab Emirates (Hybrid).
Association for Computational Linguistics. | appendix.
These plots indicate that there
are few channel-sentence region
combinations that encode differ-
ences in chunk structure in the
input sentences. While in the
figure the sentence areas are il-
lustrated with equal sizes, the re-
gions are presented transposed
for space considerations, and
they have the shapes shown in the adjacent fig-
ure. The chunks and the chunk information seems
to be encoded in the bottom part of the sentence
embedding, and much of it in the bottom 2x24 area.
5.3 BLM tasks
To further test whether task specific information
is robust to sparsification, we use the two-level
variational encoder-decoder depicted in Figure 8.
An instance for a BLM task consists of a tuple,
comprising a sequence of sentences S={si|i=
1,7}as input, and an answer set with one correct
answer ac, and several incorrect answers aerr. The
sentence level of the 2-level encoder-decoder com-
presses the sentence embeddings of each of the
sentences in the input sequence into a small latent
vector. The sampled latent representations are then
used as the representations of the sentences in the
input sequence. This sequence representation is
passed as input to the BLM-level encoder-decoder,
it is compressed into a new latent layer, and the
sampled vector is then decoded into a sentence rep-
resentation that best matches the representation of
the correct answer.
BLM task results We evaluate the performance
of the sparsified 2-level V AE on the BLM tasks.
Only the first level of the V AE, the one process-
ing individual sentences, is sparsified as described
Figure 6: Average cosine distance between value distributions in each CNN output node (i.e. each node correspond-
ing to the application of the kernel from each channel on the sentence embeddings, according to the kernel size and
stride) for sets of sentences with minimally different patters: (left) patterns differ in only one grammatical number
attribute for one chunk, (middle) patterns differ only in length, (right) patterns differ only in the number of the
subject and verb. Each panel corresponds to one region of the sentence embedding the size of the kernel. The y-axis
represents the channels of the CNN. The x-axis represents the latent units in different colours (the stronger the color,
the higher the value, max = 1), and the pairs of compared patterns represented as adjacent rectangles.
Figure 7: Results in term of average F1 scores over 3 runs, for the BLM agreement (1) and verb alternations
ALT-ATL (2) and ATL-ALT (3)
Figure 8: A two-level variational encoder-decoder: the
top level compresses the sentence embeddings into a
latent layer, and the bottom level uses the compressed
sentence representations to solve the BLM tasks.
in section 5.1. Figure 7 shows the performance
of three system variations: (i) a one-level V AE
that processes the input sequence of sentences and
produces a sentence representation, (ii) the two-
level V AE described in more detail in (Nastase and
Merlo, 2024), (iii) the sparsified version of the sen-
tence level V AE in the two-level V AE. As in the
previous experiments, sparsification does not cause
harsh drops in performance for either of the two
BLM tasks. The reason for this is the same rea-
son we chose this particular data for experiments:
solving the task relies on the system having infor-
mation about the chunks in the sentence, and their
properties. As long as that type of information ispreserved, the tasks can be solved successfully.
We note two main changes however. In the agree-
ment task, the sparsified system registers a drop
in performance when trained on maximally lexi-
cally different data (type III). The two-level system
without sparsification also registers such a drop
in comparison with the baseline one-level encoder
decoder. Both these effects may be due to the am-
biguous supervision signal at the sentence level of
the system: while using type I and type II data with
little lexical variation, it is easier for the system
to focus on structural differences between the cor-
rect and incorrect output options. When using type
III data with much lexical variation, it is not clear
for the system what is the relevant dimension of
difference between the output options.
In the verb alternation task, previous results on
predicting the Agent-Theme-Location or the Agent-
Location-Theme alternation produced very similar
results. This is not the case here, but understanding
why this happens requires additional analysis.
6 Conclusions
Our aim was to understand how information is en-
coded in sentence embedding, given that previous
work has shown that various types of linguistic
information is encoded in a model’s layers and pa-
rameters. We investigated this question using a
dataset of sentences with specific chunk structure,
and two multiple-choice problems that require in-
formation about sentence chunks and their prop-
erties to be solved successfully. We have shown
that using a sparsified encoder-decoder system, the
sentence representations can be compressed into a
latent layer that encodes chunk structure properties.
We then traced back the signal from the latent layer
to the sentence embedding, to detect which areas
of the sentence embeddings change the most when
comparing sentences with different chunk patterns.
This analysis shows that such information is cap-
tured by a small number of channel-sentence area
combinations. Further experiments with the two
multiple-choice tasks have confirmed that chunk
information and their grammatical properties (for
the agreement BLM) and chunk information and
their semantic role properties (for the verb alterna-
tion BLM) are captured by the sparsified sentence
compression level. We envision further analyses to
see where the differences between chunk patterns
that have different semantic roles are encoded, and
get closer to decoding the sentence embeddings.
7 Limitations
We have explored sentence embeddings using an
artificially constructed dataset with simple chunk
structure. To check how this kind of information
is localized, we started from a previously devel-
oped system that showed high performance in dis-
tinguishing the patterns of interest. We have not
changed the system’s parameters (such as the ker-
nel size of the CNNs), and have not performed
additional parameter search to narrow down the
locations to smaller regions. We plan to address
sentence complexity issues and parameters for nar-
rower localization of information in future work.
Acknowledgments We gratefully acknowledge
the partial support of this work by the Swiss Na-
tional Science Foundation, through grant SNF Ad-
vanced grant TMAG-1_209426 to PM.
References
Yossi Adi, Einat Kermany, Yonatan Belinkov, Ofer Lavi,
and Yoav Goldberg. 2017. Fine-grained analysis
of sentence embeddings using auxiliary prediction
tasks. In 5th International Conference on Learning
Representations, ICLR 2017, Toulon, France, April24-26, 2017, Conference Track Proceedings . Open-
Review.net.
Aixiu An, Chunyang Jiang, Maria A. Rodriguez, Vivi
Nastase, and Paola Merlo. 2023. BLM-AgrF: A new
French benchmark to investigate generalization of
agreement in neural networks. In Proceedings of the
17th Conference of the European Chapter of the As-
sociation for Computational Linguistics , pages 1363–
1374, Dubrovnik, Croatia. Association for Computa-
tional Linguistics.
Steven Cao, Victor Sanh, and Alexander Rush. 2021.
Low-complexity probing via finding subnetworks. In
Proceedings of the 2021 Conference of the North
American Chapter of the Association for Computa-
tional Linguistics: Human Language Technologies ,
pages 960–966, Online. Association for Computa-
tional Linguistics.
Kevin Clark, Urvashi Khandelwal, Omer Levy, and
Christopher D. Manning. 2019. What does BERT
look at? an analysis of BERT’s attention. In Pro-
ceedings of the 2019 ACL Workshop BlackboxNLP:
Analyzing and Interpreting Neural Networks for NLP ,
pages 276–286, Florence, Italy. Association for Com-
putational Linguistics.
Kevin Clark, Minh-Thang Luong, Quoc V . Le, and
Christopher D. Manning. 2020. ELECTRA: Pre-
training text encoders as discriminators rather than
generators. In ICLR .
Simone Conia, Edoardo Barba, Alessandro Scirè, and
Roberto Navigli. 2022. Semantic role labeling meets
definition modeling: Using natural language to de-
scribe predicate-argument structures. In Findings
of the Association for Computational Linguistics:
EMNLP 2022 , pages 4253–4270, Abu Dhabi, United
Arab Emirates. Association for Computational Lin-
guistics.
Arthur Conmy, Augustine Mavor-Parker, Aengus Lynch,
Stefan Heimersheim, and Adrià Garriga-Alonso.
2023. Towards automated circuit discovery for mech-
anistic interpretability. In Advances in Neural Infor-
mation Processing Systems , volume 36, pages 16318–
16352. Curran Associates, Inc.
Alexis Conneau, German Kruszewski, Guillaume Lam-
ple, Loïc Barrault, and Marco Baroni. 2018. What
you can cram into a single $&!#* vector: Probing
sentence embeddings for linguistic properties. In
Proceedings of the 56th Annual Meeting of the As-
sociation for Computational Linguistics (Volume 1:
Long Papers) , pages 2126–2136, Melbourne, Aus-
tralia. Association for Computational Linguistics.
Róbert Csordás, Sjoerd van Steenkiste, and Jürgen
Schmidhuber. 2021. Are neural nets modular? in-
specting functional modularity through differentiable
weight masks. In Int. Conf. on Learning Representa-
tions (ICLR) , Virtual only.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. BERT: pre-training of
deep bidirectional transformers for language under-
standing. CoRR , abs/1810.04805.
Jonathan Frankle and Michael Carbin. 2018. The lottery
ticket hypothesis: Training pruned neural networks.
CoRR , abs/1803.03635.
Yoav Goldberg. 2019. Assessing bert’s syntactic abili-
ties. arXiv preprint arXiv:1901.05287 .
Pengcheng He, Xiaodong Liu, Jianfeng Gao, and
Weizhu Chen. 2020. Deberta: Decoding-
enhanced BERT with disentangled attention. CoRR ,
abs/2006.03654.
John Hewitt and Christopher D. Manning. 2019. A
structural probe for finding syntax in word represen-
tations. In Proceedings of the 2019 Conference of
the North American Chapter of the Association for
Computational Linguistics: Human Language Tech-
nologies, Volume 1 (Long and Short Papers) , pages
4129–4138, Minneapolis, Minnesota. Association for
Computational Linguistics.
Joseph L. Hodges. 1958. The significance probability
of the smirnov two-sample test. Arkiv für Matematik ,
3:469–486.
Daphne Ippolito, David Grangier, Douglas Eck, and
Chris Callison-Burch. 2020. Toward better storylines
with sentence-level language models. In Proceedings
of the 58th Annual Meeting of the Association for
Computational Linguistics , pages 7472–7478, Online.
Association for Computational Linguistics.
Zhenzhong Lan, Mingda Chen, Sebastian Goodman,
Kevin Gimpel, Piyush Sharma, and Radu Sori-
cut. 2019. ALBERT: A lite BERT for self-
supervised learning of language representations.
CoRR , abs/1909.11942.
Michael Lepori, Thomas Serre, and Ellie Pavlick. 2023.
Break it down: Evidence for structural composition-
ality in neural networks. Advances in Neural Infor-
mation Processing Systems , 36:42623–42660.
Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man-
dar Joshi, Danqi Chen, Omer Levy, Mike Lewis,
Luke Zettlemoyer, and Veselin Stoyanov. 2019.
Roberta: A robustly optimized bert pretraining ap-
proach. arXiv preprint arXiv:1907.11692 .
Christos Louizos, Max Welling, and Diederik P. Kingma.
2018. Learning sparse neural networks through l_0
regularization. In 6th International Conference on
Learning Representations, ICLR 2018, Vancouver,
BC, Canada, April 30 - May 3, 2018, Conference
Track Proceedings . OpenReview.net.
Paola Merlo. 2023. Blackbird language matrices
(BLM), a new task for rule-like generalization in neu-
ral networks: Motivations and formal specifications.
ArXiv , cs.CL 2306.11444.Vivi Nastase and Paola Merlo. 2023. Grammati-
cal information in BERT sentence embeddings as
two-dimensional arrays. In Proceedings of the
8th Workshop on Representation Learning for NLP
(RepL4NLP 2023) , pages 22–39, Toronto, Canada.
Association for Computational Linguistics.
Vivi Nastase and Paola Merlo. 2024. Are there iden-
tifiable structural parts in the sentence embedding
whole?
Dmitry Nikolaev and Sebastian Padó. 2023. The uni-
verse of utterances according to BERT. In Proceed-
ings of the 15th International Conference on Com-
putational Semantics , pages 99–105, Nancy, France.
Association for Computational Linguistics.
Juri Opitz and Anette Frank. 2022. SBERT studies
meaning representations: Decomposing sentence em-
beddings into explainable semantic features. In Pro-
ceedings of the 2nd Conference of the Asia-Pacific
Chapter of the Association for Computational Lin-
guistics and the 12th International Joint Conference
on Natural Language Processing (Volume 1: Long
Papers) , pages 625–638, Online only. Association for
Computational Linguistics.
Abhishek Panigrahi, Nikunj Saunshi, Haoyu Zhao, and
Sanjeev Arora. 2023. Task-specific skill localization
in fine-tuned language models. In International Con-
ference on Machine Learning , pages 27011–27033.
PMLR.
Isabel Papadimitriou, Ethan A. Chi, Richard Futrell, and
Kyle Mahowald. 2021. Deep subjecthood: Higher-
order grammatical features in multilingual BERT. In
Proceedings of the 16th Conference of the European
Chapter of the Association for Computational Lin-
guistics: Main Volume , pages 2522–2532, Online.
Association for Computational Linguistics.
Nils Reimers and Iryna Gurevych. 2019. Sentence-
BERT: Sentence embeddings using Siamese BERT-
networks. In Proceedings of the 2019 Conference on
Empirical Methods in Natural Language Processing
and the 9th International Joint Conference on Natu-
ral Language Processing (EMNLP-IJCNLP) , pages
3982–3992, Hong Kong, China. Association for Com-
putational Linguistics.
Anna Rogers, Olga Kovaleva, and Anna Rumshisky.
2020. A primer in BERTology: What we know about
how BERT works. Transactions of the Association
for Computational Linguistics , 8:842–866.
Giuseppe Samo, Vivi Nastase, Chunyang Jiang, and
Paola Merlo. 2023. BLM-s/lE: A structured dataset
of English spray-load verb alternations for testing
generalization in LLMs. In Findings of the 2023
Conference on Empirical Methods in Natural Lan-
guage Processing .
Pedro Savarese, Hugo Silva, and Michael Maire. 2020.
Winning the lottery with continuous sparsification.
InProceedings of the 34th International Conference
on Neural Information Processing Systems , NIPS’20,
Red Hook, NY , USA. Curran Associates Inc.
Ian Tenney, Dipanjan Das, and Ellie Pavlick. 2019a.
BERT rediscovers the classical NLP pipeline. In
Proceedings of the 57th Annual Meeting of the Asso-
ciation for Computational Linguistics , pages 4593–
4601, Florence, Italy. Association for Computational
Linguistics.
Ian Tenney, Patrick Xia, Berlin Chen, Alex Wang, Adam
Poliak, R Thomas McCoy, Najoung Kim, Benjamin
Van Durme, Samuel R Bowman, Dipanjan Das, et al.
2019b. What do you learn from context? probing for
sentence structure in contextualized word represen-
tations. In The Seventh International Conference on
Learning Representations (ICLR) , pages 235–249.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Michael Wilson, Jackson Petty, and Robert Frank. 2023.
How abstract is linguistic generalization in large lan-
guage models? experiments with argument structure.
Transactions of the Association for Computational
Linguistics , 11:1377–1395.
David Yi, James Bruno, Jiayu Han, Peter Zukerman,
and Shane Steinert-Threlkeld. 2022. Probing for un-
derstanding of English verb classes and alternations
in large pre-trained language models. In Proceedings
of the Fifth BlackboxNLP Workshop on Analyzing
and Interpreting Neural Networks for NLP , pages
142–152, Abu Dhabi, United Arab Emirates (Hybrid).
Association for Computational Linguistics. | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18134v1 | http://arxiv.org/pdf/2407.18134v1 | $\mathbb{X}$-Sample Contrastive Loss: Improving Contrastive Learning with Sample Similarity Graphs | Vlad Sobal, Mark Ibrahim, Randall Balestriero, Vivien Cabannes, Diane Bouchacourt, Pietro Astolfi, Kyunghyun Cho, Yann LeCun | 2024-07-25 | Abstract
Learning good representations involves capturing the diverse ways in which data
samples relate. Contrastive loss—an objective matching related samples—underlies
methods from self-supervised to multimodal learning. Contrastive losses, however,
can be viewed more broadly as modifying a similarity graph to indicate how
samples should relate in the embedding space. This view reveals a shortcoming
in contrastive learning: the similarity graph is binary, as only one sample is the
related positive sample. Crucially, similarities across samples are ignored. Based
on this observation, we revise the standard contrastive loss to explicitly encode how
a sample relates to others. We experiment with this new objective, called X-Sample
Contrastive, to train vision models based on similarities in class or text caption
descriptions. Our study spans three scales: ImageNet-1k with 1 million, CC3M
with 3 million, and CC12M with 12 million samples. The representations learned
via our objective outperform both contrastive self-supervised and vision-language
models trained on the same data across a range of tasks. When training on CC12M,
we outperform CLIP by 0.6%on both ImageNet and ImageNet Real. Our objective
appears to work particularly well in lower-data regimes, with gains over CLIP
of16.8%on ImageNet and 18.1%on ImageNet Real when training with CC3M.
Finally, our objective seems to encourage the model to learn representations that
separate objects from their attributes and backgrounds, with gains of 3.3-5.6%
over CLIP on ImageNet9. We hope the proposed solution takes a small step
towards developing richer learning objectives for understanding sample relations
in foundation models.
1 | Introduction
Contrastive loss underlies methods from self-supervised learning (SSL) to multimodal learning
[Radford et al., 2021, Chen et al., 2020, Oord et al., 2018]. In SSL, contrastive learning encourages
the model to associate a sample with another view of the sample created using hand-crafted data
augmentation—this related view is the positive sample. Other samples are then pushed away as
negative, unrelated samples in the models’ representation space. Contrastive losses also play a crucial
role in multimodal models such as CLIP [Radford et al., 2021], where the model associates an
image with its text caption in representation space. Here contrastive learning designates the caption
and image representations as positives while all other text-image pairs are designated as unrelated
negatives.
More broadly, contrastive losses can be seen as modifying a similarity graph to indicate how samples
should relate in the model’s representation space [Cabannes et al., 2023]. This view reveals a
shortcoming in contrastive learning: the similarity graph is binary, as only one sample is the related
positive sample. Crucially, similarities across samples, containing precious signals about how aspects
of one sample may relate to another, are ignored. For example, as shown in fig. 1, contrastive
Preprint. Correspondence to Vlad Sobal <[email protected]> .arXiv:2407.18134v1 [cs.CV] 25 Jul 2024
Standard Contrastive -Sample Contrastive𝕏
0.408cross-sample similarity:
doggrass
<caption><caption><caption>
<caption>LEARNS SAMPLE SIMILARITIES SAMPLES ARE INDEPENDENT +Figure 1: Capturing similarities across samples in vision-language data with X-Sample Con-
trastive Loss. Standard contrastive losses do not model the relationship across the samples (left),
while our proposed method X-CLR (right) takes into account the soft inter-sample relationships.
X-CLR pushes the representations of two different photos of dogs together. The relationship between
the photos of a dog and a cat on similar grassy | backgrounds, with gains of 3.3-5.6%
over CLIP on ImageNet9. We hope the proposed solution takes a small step
towards developing richer learning objectives for understanding sample relations
in foundation models.
1 Introduction
Contrastive loss underlies methods from self-supervised learning (SSL) to multimodal learning
[Radford et al., 2021, Chen et al., 2020, Oord et al., 2018]. In SSL, contrastive learning encourages
the model to associate a sample with another view of the sample created using hand-crafted data
augmentation—this related view is the positive sample. Other samples are then pushed away as
negative, unrelated samples in the models’ representation space. Contrastive losses also play a crucial
role in multimodal models such as CLIP [Radford et al., 2021], where the model associates an
image with its text caption in representation space. Here contrastive learning designates the caption
and image representations as positives while all other text-image pairs are designated as unrelated
negatives.
More broadly, contrastive losses can be seen as modifying a similarity graph to indicate how samples
should relate in the model’s representation space [Cabannes et al., 2023]. This view reveals a
shortcoming in contrastive learning: the similarity graph is binary, as only one sample is the related
positive sample. Crucially, similarities across samples, containing precious signals about how aspects
of one sample may relate to another, are ignored. For example, as shown in fig. 1, contrastive
Preprint. Correspondence to Vlad Sobal <[email protected]> .arXiv:2407.18134v1 [cs.CV] 25 Jul 2024
Standard Contrastive -Sample Contrastive𝕏
0.408cross-sample similarity:
doggrass
<caption><caption><caption>
<caption>LEARNS SAMPLE SIMILARITIES SAMPLES ARE INDEPENDENT +Figure 1: Capturing similarities across samples in vision-language data with X-Sample Con-
trastive Loss. Standard contrastive losses do not model the relationship across the samples (left),
while our proposed method X-CLR (right) takes into account the soft inter-sample relationships.
X-CLR pushes the representations of two different photos of dogs together. The relationship between
the photos of a dog and a cat on similar grassy backgrounds is also captured, albeit with a smaller
similarity.
learning treats each text-image pair independently, without explicitly encoding similarities in the
images depicting dogs and the others sharing a grassy background. Standard contrastive objectives
do not explicitly account for similarities across samples, thereby limiting the quality of the learned
representations. Here, we explore here how to capture such similarities by modifying the standard
contrastive objective.
To account for similarities across samples, we first remove the binary negative vs. positive designa-
tions in standard contrastive loss. We introduce instead a similarity graph with continuous scalars
capturing the extent to which two samples are related. Consider the example in fig. 1, where the two
dog images have a high similarity while the dog and cat images have a more moderate similarity.
We experiment with this new objective, called X-Sample Contrastive ( X-CLR), by training vision
models using a graph of similarities inferred from class or text caption descriptions found in common
datasets. Our study spans three training dataset scales from 1 million samples with high-quality labels
from ImageNet [Deng et al., 2009] to 3 and 12 million noisy image-text caption pairs from CC3M
and CC12M [Sharma et al., 2018].
We find that compared to contrastive baseline methods trained on the same data, representation
trained using X-CLR outperform contrastive training on a range of tasks from standard classification
to tasks involving the decomposition of objects from their attributes and backgrounds. When training
on CC12M, we outperform CLIP by 0.6% on both ImageNet and ImageNet Real [Beyer et al., 2020].
Furthermore, X-CLR seems to encourage the model to learn representations that separate objects from
their attributes and backgrounds, with gains of 3.4-4.9% over CLIP on ImageNet9 [Xiao et al., 2020].
We also find for fine-grained disambiguation of object attributes, the quality of labels used to infer
the similarity graph is much more important than the data quantity. Compared to noisier web caption
data, we find X-CLR trained on 1 million higher quality class labels outperforms representations
learned via standard contrastive CLIP trained 12×more data. Finally, we find X-CLR appears to
work particularly well in lower-data regimes, with gains over CLIP of 16.8% on ImageNet and
18.1% on ImageNet Real when training with CC3M. In short, we find representations learned using
X-CLR generalize better, decompose objects from their attributes and backgrounds, and are more
data-efficient.
Our contributions are:
2
1.We present a graph similarity perspective of contrastive losses, revealing standard losses
encode a sparse similarity matrix that treats other, related, samples as negatives.
2.Consequently, we propose a new X-CLR loss that explicitly accounts for similarities across
samples
3.We experiment with this objective across three levels of data scale from 1-12 million samples.
4. We find representations learned via X-CLR
(a)Generalize better on standard classification tasks with consistent gains over contrastive
baselines trained on the same data. For example, when training on CC12M we outper-
form CLIP by 0.6% on both ImageNet and ImageNet Real.
(b)Disambiguate aspects of images such as attributes and backgrounds more reliably, with
gains of 3.3-5.6% over CLIP on background robustness benchmarks for ImageNet.
(c)Finally, we find X-CLR learns more efficiently when data is scarce, with gains of 16.8%
on ImageNet and 18.1% on ImageNet Real when pretraining on the smaller 3 million
sample CC3M dataset.
We hope the proposed solution takes a small step towards developing richer learning objectives
for understanding sample relations in foundation models to encode richer, more generalizable
representations.
2 | Related Work
Contrastive learning Various contrastive | Section not found | Section not found | Section not found | objectives for understanding sample relations
in foundation models.
1 Introduction
Contrastive loss underlies | Section not found | Section not found | Section not found | methods from self-supervised to multimodal learning. Contrastive losses, however,
can be viewed more broadly as modifying a similarity graph to indicate how
samples should relate in the embedding space. This view reveals a shortcoming
in contrastive learning: the similarity graph is binary, as only one sample is the
related positive sample. Crucially, similarities across samples are ignored. Based
on this observation, we revise the standard contrastive loss to explicitly encode how
a sample relates to others. We experiment with this new objective, called X-Sample
Contrastive, to train vision models based on similarities in class or text caption
descriptions. Our study spans three scales: ImageNet-1k with 1 million, CC3M
with 3 million, and CC12M with 12 million samples. The representations learned
via our objective outperform both contrastive self-supervised and vision-language
models trained on the same data across a range of tasks. When training on CC12M,
we outperform CLIP by 0.6%on both ImageNet and ImageNet Real. Our objective
appears to work particularly well in lower-data regimes, with gains over CLIP
of16.8%on ImageNet and 18.1%on ImageNet Real when training with CC3M.
Finally, our objective seems to encourage the model to learn representations that
separate objects from their attributes and backgrounds, with gains of 3.3-5.6%
over CLIP on ImageNet9. We hope the proposed solution takes a small step
towards developing richer learning objectives for understanding sample relations
in foundation models.
1 Introduction
Contrastive loss underlies methods from self-supervised learning (SSL) to multimodal learning
[Radford et al., 2021, Chen et al., 2020, Oord et al., 2018]. In SSL, contrastive learning encourages
the model to associate a sample with another view of the sample created using hand-crafted data
augmentation—this related view is the positive sample. Other samples are then pushed away as
negative, unrelated samples in the models’ representation space. Contrastive losses also play a crucial
role in multimodal models such as CLIP [Radford et al., 2021], where the model associates an
image with its text caption in representation space. Here contrastive learning designates the caption
and image representations as positives while all other text-image pairs are designated as unrelated
negatives.
More broadly, contrastive losses can be seen as modifying a similarity graph to indicate how samples
should relate in the model’s representation space [Cabannes et al., 2023]. This view reveals a
shortcoming in contrastive learning: the similarity graph is binary, as only one sample is the related
positive sample. Crucially, similarities across samples, containing precious signals about how aspects
of one sample may relate to another, are ignored. For example, as shown in fig. 1, contrastive
Preprint. Correspondence to Vlad Sobal <[email protected]> .arXiv:2407.18134v1 [cs.CV] 25 Jul 2024
Standard Contrastive -Sample Contrastive𝕏
0.408cross-sample similarity:
doggrass
<caption><caption><caption>
<caption>LEARNS SAMPLE SIMILARITIES SAMPLES ARE INDEPENDENT +Figure 1: Capturing similarities across samples in vision-language data with X-Sample Con-
trastive Loss. Standard contrastive losses do not model the relationship across the samples (left),
while our proposed method X-CLR (right) takes into account the soft inter-sample relationships.
X-CLR pushes the representations of two different photos of dogs together. The relationship between
the photos of a dog and a cat on similar grassy backgrounds is also captured, albeit with a smaller
similarity.
learning treats each text-image pair independently, without explicitly encoding similarities in the
images depicting dogs and the others sharing a grassy background. Standard contrastive objectives
do not explicitly account for similarities across samples, thereby limiting the quality of the learned
representations. Here, we explore here how to capture such similarities by modifying the standard
contrastive objective.
To account for similarities across samples, we first remove the binary negative vs. positive designa-
tions in standard contrastive loss. We introduce instead a similarity graph with continuous scalars
capturing the extent to which two samples are related. Consider the example in fig. 1, where the two
dog images have a high similarity while the dog and cat images have a more moderate similarity.
We experiment with this new objective, called X-Sample Contrastive ( X-CLR), by training vision
models using a graph of similarities inferred from class or text caption descriptions found in common
datasets. Our study spans three training dataset scales from 1 million samples with high-quality labels
from ImageNet [Deng et al., 2009] to 3 and 12 million noisy image-text caption pairs from CC3M
and CC12M [Sharma et al., 2018].
We find that compared to contrastive baseline methods trained on the same data, representation
trained using X-CLR outperform contrastive training on a range of tasks from standard classification
to tasks involving the decomposition of objects from their attributes and backgrounds. When training
on CC12M, we outperform CLIP by 0.6% on both ImageNet and ImageNet Real [Beyer et al., 2020].
Furthermore, X-CLR seems to encourage the model to learn representations that separate objects from
their attributes and backgrounds, with gains of 3.4-4.9% over CLIP on ImageNet9 [Xiao et al., 2020].
We also find for fine-grained disambiguation of object attributes, the quality of labels used to infer
the similarity graph is much more important than the data quantity. Compared to noisier web caption
data, we find X-CLR trained on 1 million higher quality class labels outperforms representations
learned via standard contrastive CLIP trained 12×more data. Finally, we find X-CLR appears to
work particularly well in lower-data regimes, with gains over CLIP of 16.8% on ImageNet and
18.1% on ImageNet Real when training with CC3M. In short, we find representations learned using
X-CLR generalize better, decompose objects from their attributes and backgrounds, and are more
data-efficient.
Our contributions are:
2
1.We present a graph similarity perspective of contrastive losses, revealing standard losses
encode a sparse similarity matrix that treats other, related, samples as negatives.
2.Consequently, we propose a new X-CLR loss that explicitly accounts for similarities across
samples
3.We experiment with this objective across three levels of data scale from 1-12 million samples.
4. We find representations learned via X-CLR
(a)Generalize better on standard classification tasks with consistent gains over contrastive
baselines trained on the same data. For example, when training on CC12M we outper-
form CLIP by 0.6% on both ImageNet and ImageNet Real.
(b)Disambiguate aspects of images such as attributes and backgrounds more reliably, with
gains of 3.3-5.6% over CLIP on background robustness benchmarks for ImageNet.
(c)Finally, we find X-CLR learns more efficiently when data is scarce, with gains of 16.8%
on ImageNet and 18.1% on ImageNet Real when pretraining on the smaller 3 million
sample CC3M dataset.
We hope the proposed solution takes a small step towards developing richer learning objectives
for understanding sample relations in foundation models to encode richer, more generalizable
representations.
2 Related Work
Contrastive learning Various contrastive objectives have been proposed over the years [Chopra
et al., 2005, Schroff et al., 2015]. More recently, the InfoNCE objective [Oord et al., 2018] has been
the most popular choice for self-supervised methods, e.g. SimCLR [Chen et al., 2020] and MoCo
[He et al., 2020]. InfoNCE objective has also been successfully used to learn vision-language models
using CLIP [Radford et al., 2021]. The basis of those objectives is to make positive pairs have similar
representations, while the negatives, which typically are just all other elements in a batch, should
have a different representation. In its original form, InfoNCE is binary, meaning it only works with
positive and negative pairs, and does not support degrees of similarity. The positive pairs are usually
two augmentations of the same sample, which makes well-tuned augmentations crucial for good
performance [Ryali et al., 2021]. Dwibedi et al. [2021] estimate positives using nearest neighbors in
the latent space instead and therefore can use weaker augmentations, while Caron et al. [2020] use
cluster assignment. A few methods have proposed modifications wherein multiple positive pairs are
supported, e.g., Khosla et al. [2020] groups positive by class labels, Hoffmann et al. [2022] propose
using WordNet [Fellbaum, 1998] hierarchy to define ranked positive samples, and Tian et al. [2024]
uses a generative model to obtain multiple positives for the same concept.
Soft targets Using soft targets provides more learning signal to the model, possibly making it
learn better and faster. This has been explored with distillation by Hinton et al. [2015]. Soft targets
have also been used with InfoNCE in the context of distillation by Zheng et al. [2021] and Denize
et al. [2023], where the target cross-sample similarity comes from the teacher model. Similarly, Fini
et al. [2023a] computes soft targets via latent clustering and applies it to semi-supervised learning.
Andonian et al. [2022] proposes to use soft targets for CLIP [Radford et al., 2021] training, and
calculates the targets via self-distillation. Further soft CLIP objectives are explored by Fini et al.
[2023b], who apply label smoothing to obtain soft targets, and Gao et al. [2024], who estimate
soft targets by comparing fine-grained image information. Finally, Huang et al. [2024] train CLIP
with non-zero cross-sample similarities computed based on pre-trained uni-modal models for text
and vision. In this study, we build on the work of Cabannes et al. [2023] who propose a unifying
framework to view SSL and supervised learning objectives as learning with different underlying
similarity graphs. We take inspiration from the soft targets literature and propose using a soft graph.
3 Understanding contrastive losses via similarity graphs
3.1 X-Sample Graphs
Throughout this study, a similarity graph denotes a graph in which the nodes represent data samples,
and edges similarity – relationships. A graph is expressed through its symmetric adjacency matrix
3
sample idx
sample idx
Self-supervised
sample idx
Supervised
sample idx
X-CLR
0.0 0.2 0.4 0.6 0.8 1.0Cat Dog Piano GuitarFigure 2: Sample similarity adjacency matrices of existing methods vs. our X-Sample Con-
trastive similarity loss (right). We show pairwise similarities of 20 samples belonging to 4 classes.
Similarity of 1 means the samples are identical, 0 – they are completely unrelated. In case of self-
supervised learning, none of the inter-sample relationships are modelled (left). Supervised learning
relies on the labels to group samples of the same class together (center). X-CLR models inter-class
relationships by associating cats with dogs and pianos with guitars.
G∈RN×N, the semantic relation between inputs iandjbeing encoded in the real entry Gi,j.
In fig. 2, we show graphs of different learning paradigms. SSL does not rely on labels, but on
positive pairs/tuples/views generated at each epoch. Let us denote by Vthe number of positive views
generated, commonly V= 2for positive pairs, and denote by Ethe training epochs. In that case, the
original Ninput samples are transformed into N×V×E“augmented” samples
X(A)≜[T(x1), . . . ,T(x1)| {z }
repeated V×Etimes, . . . ,T(xN), . . . ,T(xN)]⊤,
where each Thas its own randomness. The corresponding graph is given by:
G(ssl)
i,j=1{⌊i/V E⌋=⌊j/V E⌋}, (1)
where the associated similarity graph captures if two samples were generated as augmentations of the
same original input. Such graphs G, as defined by eq. (1), are the ones used as targets in common
SSL methods, as formalized below denoting Z≜fθ(X)∈RN×K.
Theorem 1 ([Cabannes et al., 2023]) .VICReg [Bardes et al., 2021], SimCLR [Chen et al., 2020],
and BarlowTwins [Zbontar et al., 2021] losses can be expressed in terms of the graph G(1)
LVIC2(Z;G) =∥ZZT−G∥2
F,
LSimCLR (Z;G) =−X
i,j∈[N]Gi,jlog
exp(˜z⊤
i˜zj)P
k∈[N]exp(˜z⊤
i˜zk)!
,
LBT(Z;G) =
˜Z⊤G˜Z−I
2
,
where ˜z≜z/∥z∥and˜Zthe column normalized Zso that each column has unit norm.
In our study, we will focus on contrastive learning, i.e., SimCLR family of losses. We will demonstrate
how to move away from the ad-hoc graph Gfrom eq. (1).
3.2 Revisiting contrastive losses with similarity graphs: X-CLR
We introduce the soft cross-sample similarity to the widely used InfoNCE objective [Oord et al.,
2018]. We note that the proposed framework isn’t necessarily only limited to InfoNCE-based methods
4
and can potentially be integrated into non-contrastive objectives such as BYOL [Grill et al., 2020],
SimSiam [Chen and He, 2020], or VICReg [Bardes et al., 2021], although we leave the extension to
other objectives for future work. In SimCLR [Chen et al., 2020], given a batch of Nimages, each
image is augmented twice, so each sample has a true positive. The 2Nimages are then encoded to
get representation vectors z. Then:
pi,j=exp(sim( zi, zj)/τ)P2N
i=1 1[k̸=i]exp(sim( zi, zk)/τ)
LSimCLR =1
2N2NX
i=1H( 1i′, pi)
where His the cross-entropy, and 1i′is the one-hot distribution where all the probability mass is
assigned to the index of the positive sample corresponding to i, and simis the cosine similarity.
Intuitively, we are training the model to classify positive examples in a batch, so the similarity p
should be high only for the true positive. We introduce the soft objective by replacing the hard
positive distribution 1i′with a distribution si. Or, in terms of graphs, we replace the graph from the
eq. (1) with a soft graph where connection strengths can be any number in [0,1], and, similarly, the
distribution siand does not have to be one-hot. Considering the example of fig. 1, we want the a
photo of a dog to have a representation similar to that of another photo of a dog, somewhat similar to
the representation of a cat photo, and different from the representation of a photo of a mug. Given
that distribution s, we can plug it in directly:
LX-CLR=1
2N2NX
i=1H(si, pi)
There are many possible ways to obtain this distribution s. We could use the meta-data associated
with the dataset; in our case, we utilize a trained text encoder ftext, and encode the text provided with
each image to obtain a representation, which is then used to calculate similarity between samples i
andjusing the cosine similarity. Those pairwise similarities describe the soft graph:
G(soft)
i,j = sim( ftext(ci), ftext(cj))
Where ciis the caption associated with the i-th sample. The last step before plugging the similarities
into the loss function is converting them to a valid probability distribution using a softmax function:
si,j=exp(G(soft)
i,j/τs)
P2N
k=1exp(G(soft)
i,k/τs)
Note that τsis a separate hyperparameter from τin the softmax to calculate the learned similarities.
Higher values of τsput more weight on the ’soft’ positives, while lower values in the limit recover
the original SimCLR objective.
4 Experiments
4.1 | Experimental setup
We test X-CLR on three datasets of varying scale: ImageNet [Deng et al., 2009] (1M), and conceptual
captions 3M and 12M [Sharma et al., 2018]. We blur faces in all datasets before training our models.
We compare to SimCLR [Chen et al., 2020], to CLIP [Radford et al., 2021] when captions are
available, and to SupCon [Khosla et al., 2020] on ImageNet. We use the Sentence Transformer
[Reimers and Gurevych, 2019] as the text encoder to construct similarities. For ImageNet experiments,
we generate captions by using the template "a photo of a _" to generate captions out of class names.
In our experiments with the conceptual captions dataset [Sharma et al., 2018], we use the captions as
is. For experiments on ImageNet, we follow SupCon and use AutoAugment [Cubuk et al., 2018]. All
5
Table 1: X-Sample Contrastive loss outperforms contrastive (SimCLR) and even Supervised
Contrastive with ImageNet pretraining.
Background Decomposition MIT States
Method ImageNet ImageNet Real Same Class Mixed ObjectNet Objects Attributes
SimCLR 63.2 67.5 45.5 38.3 12.5 40.7 28.9
Supervised Contrastive 74.4 79.7 63.3 58.8 24.1 45.3 31.1
X-CLR 75.6 81.6 66.5 62.3 27.7 45.8 30.9
0 200 400 600 800 1000
Samples per class0204060Imagenet Accuracy
X-CLR
SupCon
SimCLR
(a)
20 40 60 80
K Nearest Neighbors value of K5055606570ImageNet Accuracy
X-CLR
SimCLR
SupCon (b)
101
100101
T emperature0204060Accuracy
(c)
Figure 3: (a)X-Sample Contrastive Loss is data efficient with ImageNet pretraining. We
outperform SimCLR in low data regimes and match Supervised Contrastive trained on ground truth
labels at varying levels of data scarcity. (b) KNN performance ImageNet. X-CLR outperforms other
methods with KNN probing for a range of values of K. (c) Sensitivity of X-Sample Contrastive
to temperature. We test the performance of our method when trained with different values of
temperature τson ImageNet data.
experiments on the ImageNet dataset were run for 100 epochs with 1024 batch size. The learning
rate was set to 0.075 for ImageNet models. For experiments on CC3M and CC12M, we used the
standard SimCLR augmentations, and a learning rate of 0.1. The rest of the settings were kept the
same. For more details, see appendix A.5.
In all our experiments, to isolate the effect of our learning objective, we fix the backbone architecture
to be a ResNet-50 [He et al., 2015] model as this is the most widely studied, with optimized
hyperparameters, for standard contrastive self-supervised learning [Chen et al., 2020]. We use
the same architecture for CLIP’s vision encoder and take advantage of already optimized publicly
available checkpoints provided by OpenCLIP [Ilharco et al., 2021] for CC12M. Since no comparable
public checkpoint is available for CC3M, we train our own model, see appendix A.4.
4.2X-Sample Contrastive with Well-Labeled Samples
We first experiment with X-Sample Contrastive using well-labeled samples to understand the effect
of incorporating similarities across samples in the training objective. To do so, we use class labels
from ImageNet. We compare X-Sample Contrastive ( X-CLR) to SimCLR as well as Supervised
Contrastive (SupCon), a model whose objective is to explicitly match samples based on their class
labels. We evaluate all models across a suite of benchmarks to gauge how well representations
generalize in terms of classification performance.
We find in table 1 representations learned via X-CLR improve on standard classification performance,
with gains of 12.4% relative to SimCLR and 1.2% relative to Supervised Contrastive on ImageNet.
We find similar gains when evaluated on revised labels from ImageNet Real of 14.1% and 1.9%,
respectively. Finally, we find by capturing similarities across samples, representations learned via
X-CLR are more capable of disambiguating objects from backgrounds and attributes with gains on
ImageNet-9 (for details see appendix A.3) [Xiao et al., 2020] and ObjectNet [Barbu et al., 2019].
Can we improve contrastive learning under data scarcity? To answer this question, we train all
three models SimCLR, SupCon, and X-CLR by varying the number of samples seen for each class in
ImageNet. We find X-CLR, by incorporating information about how classes relate, is able to learn
representations that match the performance of SupCon trained with ground truth class labels and
outperform SimCLR even when few training samples are available per class as shown in fig. 3a.
6
Table 2: X-Sample Contrastive with CC3M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 57.0 64.0 24.4 18.9 10.8
CLIP 41.0 47.6 12.5 10.6 7.8
X-CLR 58.2 65.6 26.7 20.3 11.5
Table 3: X-Sample Contrastive with CC12M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 58.9 66 24.6 19.8 12.7
CLIP 58.8 66.1 20.5 17.1 11.9
X-CLR 59.4 66.7 26.1 20.4 13.4
4.3X-Sample Contrastive with Noisy Multimodal Samples
Contrastive loss also plays a pivotal role in multimodal vision-language models such as CLIP. The
contrastive training objective matches noisy caption-image pairs. Here we experiment with X-Sample
Contrastive by using the noisy captions to learn similarities across samples. We compare both
SimCLR as a standard contrastive model and CLIP trained on the same caption-image data across
two levels of scale: 3 and 12 million samples from CC3M and CC12M.
We find incorporating X-Contrastive leads to representations with higher classification accuracy and
disambiguation of objects from their attributes and backgrounds. With CC12M training shown in
table 3, X-Contrastive outperforms SimCLR by 0.5% and CLIP by 0.6% with CC12M with similar
gains for ImageNet Real. We also find X-CLR training can better disambiguate object foreground
from backgrounds, with gains of 0.6-1.5% over SimCLR and 3.3-5.6% over CLIP.
We find learning similarites across samples with X-CLR leads to more considerable gains when less
data is available. X-CLR outperforms SimCLR by 1.2% and CLIP by 16.8% on ImageNet, with
similar gains on ImageNet Real as shown in table 2. We find X-CLR training can more considerably
disambiguate object foregrounds from backgrounds compared to CLIP when less training data is
available, with gains of 10.3-13.3% over CLIP.
4.4X-Sample Contrastive can be used to finetune pretrained backbones
We validate whether X-CLR can be used as a finetuning objective for pretrained backbones, given the
growing abundance of publicly available backbones. Here, we evaluate a pretrained SimCLR model
by finetuning for 10 epochs on ImageNet with X-CLR instead of the original SimCLR contrastive
objective. We see in table 4 finetuning with X-CLR improves classification performance on ImageNet
by 3.3% and on ImageNet Real by 6.9%. Furthermore, we see by relating samples during the
finetuning stage, X-CLR can disambiguate object foregrounds from backgrounds with grains of
8.4-11.7% on ImageNet-9 as well as improvements on natural object transformations from ObjectNet
with a gain of 4.9% after finetuning.
Table 4: X-CLR can be used to finetune pretrained models.
Background Decomposition
ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 63.2 67.5 45.5 38.3 12.5
+X-CLR finetuning 66.5 74.4 53.9 50 17.4
7
Table 5: Analyzing the computation overhead of the X-Sample Contrastive objective during
training. X-CLR introduces nearly no computational overhead compared to SimCLR.
Method Seconds per batch ImageNet Seconds per batch CC
SimCLR 0.866 ± 0.008 0.874 ± 0.034
X-CLR 0.866 ± 0.010 0.877 ± 0.032
4.5X-Sample Contrastive introduces only minimal computational overhead
Both for ImageNet and conceptual captions datasets, we don’t run the text encoder for each sample
we see, and instead precompute the similarity values. For more details, see appendix A.5. Avoiding
running the text encoder during model training avoids the extra overhead at the price of some pre-
processing. Pre-processing takes less than 2 hours for CC12M when using one GPU, about 30
minutes for CC3M, and less than 5 minutes for ImageNet. To further analyze how much overhead
there is, we compare the average time it takes to process one batch for SimCLR and X-CLR. The | Section not found | Section not found | results are shown in table 5. Overall, we didn’t notice any significant difference in the amount of
time it takes to train models with the X-CLR objective compared to the regular contrastive objective.
To train on ImageNet, we used 8 Nvidia V100s, and each run took about 30 hours. With the same
setup, CC3M runs took about 50 hours, and CC12M runs took roughly 9 days.
5 Analyzing representations learned via X-Sample Contrastive
5.1 KNN Clustering
To confirm the representations learned via X-CLR also work well for downstream tasks with non-
linear decision boundaries, we perform evaluation using the common K-nearest neighbor (KNN)
protocol. The results shown in fig. 3b demonstrate X-CLR outperforms both SimCLR and SupCon
baselines across a range of choices for K. We also show KNN results for models trained on conceptual
captions in appendix A.2.
5.2 Visualizing the learned graph from X-Sample Contrastive representations
Here we examine whether the learned representations from X-Sample Contrastive capture semanti-
cally meaningful similarities. To do so, we select four groups of three ImageNet classes: felines, dogs,
types of balls, and musical instruments. For each pair of classes, we then compare the representation
similarities using cosine similarity. A higher average pairwise similarity indicates the model’s latent
representations encode the classes similarly. In fig. 4 we show the graph of similarities learned
after training with X-CLR on ImageNet. We find that the image encoder successfully captures the
similarity within the class groups.
5.3 The effect of softmax temperature, and inferred similarity graph
We also examine the effect of hyperparameter choices. We show the sensitivity of X-CLR to
temperature τsin fig. 3c on ImageNet. In the limit, when temperature goes to 0, we recover
Supervised Contrastive method for ImageNet, or SimCLR in case of conceptual captions. With
low temperature, the similarity is 1 only if the captions are exactly the same. As the temperature
increases, more weight is put on the soft positives compared to the true positives (i.e. augmentations
of the same sample). With high temperature, our method is unstable as too much emphasis is put
on the soft positive examples compared to the true positives. We find that the value of 0.1 strikes
the optimal balance and provides an improvement over pure Supervised Contrastive objective, while
still emphasizing true positives enough. For more details regarding how τschanges the objective, see
fig. 7b.
We also experiment with different ways of inferring the graph, including using different text encoders,
using WordNet [Fellbaum, 1998] hierarchy distance, and the purely random graph. We find that over-
all, calculating the similarities using the sentence transformer worked the best [Reimers and Gurevych,
2019]. A more detailed comparison of different graph sources can be found in appendix A.1.
8
Table 6: Label quality matters for fine-grained attribute disambiguation.
Pretraining Data Size Quality MIT States Attributes MIT States Objects
CLIP CC3M 3M Noisy 27.0 40.1
CLIP CC12M 12M Noisy 23.3 36.9
X-CLR CC3M 3M Noisy 29.5 40.7
X-CLR CC12M 12M Noisy 30.1 42.1
X-CLR ImageNet 1M High 30.9 45.8
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00SupCon target similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone0.83 0.50 0.30 0.25 0.21 0.27 0.11 0.11 0.09 0.12 0.08 0.13
0.50 0.80 0.33 0.24 0.15 0.20 0.16 0.20 0.13 0.09 0.02 0.12
0.30 0.33 0.88 0.11 0.30 0.25 0.27 0.38 0.35 0.43 0.42 0.49
0.25 0.24 0.11 0.81 0.37 0.42 0.06 0.00 0.09 0.06 0.17 0.09
0.21 0.15 0.30 0.37 0.86 0.50 0.17 0.21 0.30 0.31 0.34 0.33
0.27 0.20 0.25 0.42 0.50 0.81 0.22 0.09 0.23 0.24 0.24 0.22
0.11 0.16 0.27 0.06 0.17 0.22 1.00 0.70 0.64 0.37 0.34 0.29
0.11 0.20 0.38 0.00 0.21 0.09 0.70 0.96 0.63 0.42 0.34 0.47
0.09 0.13 0.35 0.09 0.30 0.23 0.64 0.63 0.85 0.46 0.36 0.34
0.12 0.09 0.43 0.06 0.31 0.24 0.37 0.42 0.46 0.94 0.54 0.58
0.08 0.02 0.42 0.17 0.34 0.24 0.34 0.34 0.36 0.54 0.95 0.55
0.13 0.12 0.49 0.09 0.33 0.22 0.29 0.47 0.34 0.58 0.55 0.95X-CLR Learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.48 0.23 0.36 0.32 0.37 0.14 0.14 0.16 0.16 0.07 0.12
0.48 1.00 0.29 0.33 0.31 0.41 0.23 0.28 0.23 0.11 0.00 0.20
0.23 0.29 1.00 0.26 0.13 0.12 0.15 0.21 0.23 0.20 0.27 0.34
0.36 0.33 0.26 1.00 0.63 0.64 0.18 0.17 0.20 0.17 0.24 0.23
0.32 0.31 0.13 0.63 1.00 0.60 0.08 0.08 0.15 0.15 0.20 0.25
0.37 0.41 0.12 0.64 0.60 1.00 0.21 0.12 0.15 0.09 0.07 0.21
0.14 0.23 0.15 0.18 0.08 0.21 1.00 0.62 0.63 0.15 0.17 0.09
0.14 0.28 0.21 0.17 0.08 0.12 0.62 1.00 0.62 0.23 0.16 0.35
0.16 0.23 0.23 0.20 0.15 0.15 0.63 0.62 1.00 0.36 0.21 0.20
0.16 0.11 0.20 0.17 0.15 0.09 0.15 0.23 0.36 1.00 0.35 0.36
0.07 0.00 0.27 0.24 0.20 0.07 0.17 0.16 0.21 0.35 1.00 0.32
0.12 0.20 0.34 0.23 0.25 0.21 0.09 0.35 0.20 0.36 0.32 1.00X-CLR target similarities
Felines Dogs Types of balls Musical instruments
Figure 4: Visualizing pairwise similarities SupCon [Khosla et al., 2020] objective does not encour-
age non-zero similarity between samples of different classes (left), while X-CLR target similarities
take into account semantic closeness within categories such as dogs or types of balls (center). On the
right, we see that the trained model successfully learns the soft similarity. For more graphs, see fig. 5.
5.4 The impact of label quality for fine-grained attribute disambiguation
we show in table 6 how label quality can impact downstream performance on finer-grained attribute
disambiguation. we find larger labels from noisy captions degrades performance for fine-grained
object attributes in mit states [Isola et al., 2015] for both contrastive and clip. we find X-CLR
with high quality labels from imagenet, can outperform models trained on much larger noisier data.
compared to clip trained on 12 ×larger data, X-CLR achieves 30.9% vs. 23.3% for clip on attribute
classification and 45.8% vs. 36.9% for clip on object classification under different states. to see more
details regarding the mit states evaluation, see appendix A.5.
6 | Section not found | Discussion
In the present work, we have proposed a new graph perspective on the commonly used contrastive
learning methods and used our insights to develop a better learning objective, X-CLR, by using a
soft similarity graph. The adjacency matrix of the proposed graph contains not just 0 and 1, but
also any values between, with the ability to capture the degree of similarity across samples. We
experiment with different ways of constructing the graph, and find that indeed we can build a soft
graph that improves over the existing binary graph contrastive methods. However, we believe that
there are better ways of constructing the graph than what we found, particularly for the conceptual
captions dataset where the captions are quite noisy. A better graph can possibly be built using other
metadata, such as location or time. We also believe that ideas from X-CLR can possibly be integrated
into non-contrastive objectives such as BYOL [Grill et al., 2020] or VICReg [Bardes et al., 2021] to
enrich representations with similarities across samples. | Section not found | Section not found | Limitations The main limitation of the present work is that constructing the cross-sample similarity
graph requires extra data, as well as some extra memory to store it. When the extra data is not
available, the only options remaining are to build the graph using the augmentations, self-distillation,
or other pre-trained models. The resulting method is also highly dependent on the quality of the
graph, as we have seen with conceptual captions datasets.
9 | future work. In SimCLR [Chen et al., 2020], given a batch of Nimages, each
image is augmented twice, so each sample has a true positive. The 2Nimages are then encoded to
get representation vectors z. Then:
pi,j=exp(sim( zi, zj)/τ)P2N
i=1 1[k̸=i]exp(sim( zi, zk)/τ)
LSimCLR =1
2N2NX
i=1H( 1i′, pi)
where His the cross-entropy, and 1i′is the one-hot distribution where all the probability mass is
assigned to the index of the positive sample corresponding to i, and simis the cosine similarity.
Intuitively, we are training the model to classify positive examples in a batch, so the similarity p
should be high only for the true positive. We introduce the soft objective by replacing the hard
positive distribution 1i′with a distribution si. Or, in terms of graphs, we replace the graph from the
eq. (1) with a soft graph where connection strengths can be any number in [0,1], and, similarly, the
distribution siand does not have to be one-hot. Considering the example of fig. 1, we want the a
photo of a dog to have a representation similar to that of another photo of a dog, somewhat similar to
the representation of a cat photo, and different from the representation of a photo of a mug. Given
that distribution s, we can plug it in directly:
LX-CLR=1
2N2NX
i=1H(si, pi)
There are many possible ways to obtain this distribution s. We could use the meta-data associated
with the dataset; in our case, we utilize a trained text encoder ftext, and encode the text provided with
each image to obtain a representation, which is then used to calculate similarity between samples i
andjusing the cosine similarity. Those pairwise similarities describe the soft graph:
G(soft)
i,j = sim( ftext(ci), ftext(cj))
Where ciis the caption associated with the i-th sample. The last step before plugging the similarities
into the loss function is converting them to a valid probability distribution using a softmax function:
si,j=exp(G(soft)
i,j/τs)
P2N
k=1exp(G(soft)
i,k/τs)
Note that τsis a separate hyperparameter from τin the softmax to calculate the learned similarities.
Higher values of τsput more weight on the ’soft’ positives, while lower values in the limit recover
the original SimCLR objective.
4 Experiments
4.1 Experimental setup
We test X-CLR on three datasets of varying scale: ImageNet [Deng et al., 2009] (1M), and conceptual
captions 3M and 12M [Sharma et al., 2018]. We blur faces in all datasets before training our models.
We compare to SimCLR [Chen et al., 2020], to CLIP [Radford et al., 2021] when captions are
available, and to SupCon [Khosla et al., 2020] on ImageNet. We use the Sentence Transformer
[Reimers and Gurevych, 2019] as the text encoder to construct similarities. For ImageNet experiments,
we generate captions by using the template "a photo of a _" to generate captions out of class names.
In our experiments with the conceptual captions dataset [Sharma et al., 2018], we use the captions as
is. For experiments on ImageNet, we follow SupCon and use AutoAugment [Cubuk et al., 2018]. All
5
Table 1: X-Sample Contrastive loss outperforms contrastive (SimCLR) and even Supervised
Contrastive with ImageNet pretraining.
Background Decomposition MIT States
Method ImageNet ImageNet Real Same Class Mixed ObjectNet Objects Attributes
SimCLR 63.2 67.5 45.5 38.3 12.5 40.7 28.9
Supervised Contrastive 74.4 79.7 63.3 58.8 24.1 45.3 31.1
X-CLR 75.6 81.6 66.5 62.3 27.7 45.8 30.9
0 200 400 600 800 1000
Samples per class0204060Imagenet Accuracy
X-CLR
SupCon
SimCLR
(a)
20 40 60 80
K Nearest Neighbors value of K5055606570ImageNet Accuracy
X-CLR
SimCLR
SupCon (b)
101
100101
T emperature0204060Accuracy
(c)
Figure 3: (a)X-Sample Contrastive Loss is data efficient with ImageNet pretraining. We
outperform SimCLR in low data regimes and match Supervised Contrastive trained on ground truth
labels at varying levels of data scarcity. (b) KNN performance ImageNet. X-CLR outperforms other
methods with KNN probing for a range of values of K. (c) Sensitivity of X-Sample Contrastive
to temperature. We test the performance of our method when trained with different values of
temperature τson ImageNet data.
experiments on the ImageNet dataset were run for 100 epochs with 1024 batch size. The learning
rate was set to 0.075 for ImageNet models. For experiments on CC3M and CC12M, we used the
standard SimCLR augmentations, and a learning rate of 0.1. The rest of the settings were kept the
same. For more details, see appendix A.5.
In all our experiments, to isolate the effect of our learning objective, we fix the backbone architecture
to be a ResNet-50 [He et al., 2015] model as this is the most widely studied, with optimized
hyperparameters, for standard contrastive self-supervised learning [Chen et al., 2020]. We use
the same architecture for CLIP’s vision encoder and take advantage of already optimized publicly
available checkpoints provided by OpenCLIP [Ilharco et al., 2021] for CC12M. Since no comparable
public checkpoint is available for CC3M, we train our own model, see appendix A.4.
4.2X-Sample Contrastive with Well-Labeled Samples
We first experiment with X-Sample Contrastive using well-labeled samples to understand the effect
of incorporating similarities across samples in the training objective. To do so, we use class labels
from ImageNet. We compare X-Sample Contrastive ( X-CLR) to SimCLR as well as Supervised
Contrastive (SupCon), a model whose objective is to explicitly match samples based on their class
labels. We evaluate all models across a suite of benchmarks to gauge how well representations
generalize in terms of classification performance.
We find in table 1 representations learned via X-CLR improve on standard classification performance,
with gains of 12.4% relative to SimCLR and 1.2% relative to Supervised Contrastive on ImageNet.
We find similar gains when evaluated on revised labels from ImageNet Real of 14.1% and 1.9%,
respectively. Finally, we find by capturing similarities across samples, representations learned via
X-CLR are more capable of disambiguating objects from backgrounds and attributes with gains on
ImageNet-9 (for details see appendix A.3) [Xiao et al., 2020] and ObjectNet [Barbu et al., 2019].
Can we improve contrastive learning under data scarcity? To answer this question, we train all
three models SimCLR, SupCon, and X-CLR by varying the number of samples seen for each class in
ImageNet. We find X-CLR, by incorporating information about how classes relate, is able to learn
representations that match the performance of SupCon trained with ground truth class labels and
outperform SimCLR even when few training samples are available per class as shown in fig. 3a.
6
Table 2: X-Sample Contrastive with CC3M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 57.0 64.0 24.4 18.9 10.8
CLIP 41.0 47.6 12.5 10.6 7.8
X-CLR 58.2 65.6 26.7 20.3 11.5
Table 3: X-Sample Contrastive with CC12M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 58.9 66 24.6 19.8 12.7
CLIP 58.8 66.1 20.5 17.1 11.9
X-CLR 59.4 66.7 26.1 20.4 13.4
4.3X-Sample Contrastive with Noisy Multimodal Samples
Contrastive loss also plays a pivotal role in multimodal vision-language models such as CLIP. The
contrastive training objective matches noisy caption-image pairs. Here we experiment with X-Sample
Contrastive by using the noisy captions to learn similarities across samples. We compare both
SimCLR as a standard contrastive model and CLIP trained on the same caption-image data across
two levels of scale: 3 and 12 million samples from CC3M and CC12M.
We find incorporating X-Contrastive leads to representations with higher classification accuracy and
disambiguation of objects from their attributes and backgrounds. With CC12M training shown in
table 3, X-Contrastive outperforms SimCLR by 0.5% and CLIP by 0.6% with CC12M with similar
gains for ImageNet Real. We also find X-CLR training can better disambiguate object foreground
from backgrounds, with gains of 0.6-1.5% over SimCLR and 3.3-5.6% over CLIP.
We find learning similarites across samples with X-CLR leads to more considerable gains when less
data is available. X-CLR outperforms SimCLR by 1.2% and CLIP by 16.8% on ImageNet, with
similar gains on ImageNet Real as shown in table 2. We find X-CLR training can more considerably
disambiguate object foregrounds from backgrounds compared to CLIP when less training data is
available, with gains of 10.3-13.3% over CLIP.
4.4X-Sample Contrastive can be used to finetune pretrained backbones
We validate whether X-CLR can be used as a finetuning objective for pretrained backbones, given the
growing abundance of publicly available backbones. Here, we evaluate a pretrained SimCLR model
by finetuning for 10 epochs on ImageNet with X-CLR instead of the original SimCLR contrastive
objective. We see in table 4 finetuning with X-CLR improves classification performance on ImageNet
by 3.3% and on ImageNet Real by 6.9%. Furthermore, we see by relating samples during the
finetuning stage, X-CLR can disambiguate object foregrounds from backgrounds with grains of
8.4-11.7% on ImageNet-9 as well as improvements on natural object transformations from ObjectNet
with a gain of 4.9% after finetuning.
Table 4: X-CLR can be used to finetune pretrained models.
Background Decomposition
ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 63.2 67.5 45.5 38.3 12.5
+X-CLR finetuning 66.5 74.4 53.9 50 17.4
7
Table 5: Analyzing the computation overhead of the X-Sample Contrastive objective during
training. X-CLR introduces nearly no computational overhead compared to SimCLR.
Method Seconds per batch ImageNet Seconds per batch CC
SimCLR 0.866 ± 0.008 0.874 ± 0.034
X-CLR 0.866 ± 0.010 0.877 ± 0.032
4.5X-Sample Contrastive introduces only minimal computational overhead
Both for ImageNet and conceptual captions datasets, we don’t run the text encoder for each sample
we see, and instead precompute the similarity values. For more details, see appendix A.5. Avoiding
running the text encoder during model training avoids the extra overhead at the price of some pre-
processing. Pre-processing takes less than 2 hours for CC12M when using one GPU, about 30
minutes for CC3M, and less than 5 minutes for ImageNet. To further analyze how much overhead
there is, we compare the average time it takes to process one batch for SimCLR and X-CLR. The
results are shown in table 5. Overall, we didn’t notice any significant difference in the amount of
time it takes to train models with the X-CLR objective compared to the regular contrastive objective.
To train on ImageNet, we used 8 Nvidia V100s, and each run took about 30 hours. With the same
setup, CC3M runs took about 50 hours, and CC12M runs took roughly 9 days.
5 Analyzing representations learned via X-Sample Contrastive
5.1 KNN Clustering
To confirm the representations learned via X-CLR also work well for downstream tasks with non-
linear decision boundaries, we perform evaluation using the common K-nearest neighbor (KNN)
protocol. The results shown in fig. 3b demonstrate X-CLR outperforms both SimCLR and SupCon
baselines across a range of choices for K. We also show KNN results for models trained on conceptual
captions in appendix A.2.
5.2 Visualizing the learned graph from X-Sample Contrastive representations
Here we examine whether the learned representations from X-Sample Contrastive capture semanti-
cally meaningful similarities. To do so, we select four groups of three ImageNet classes: felines, dogs,
types of balls, and musical instruments. For each pair of classes, we then compare the representation
similarities using cosine similarity. A higher average pairwise similarity indicates the model’s latent
representations encode the classes similarly. In fig. 4 we show the graph of similarities learned
after training with X-CLR on ImageNet. We find that the image encoder successfully captures the
similarity within the class groups.
5.3 The effect of softmax temperature, and inferred similarity graph
We also examine the effect of hyperparameter choices. We show the sensitivity of X-CLR to
temperature τsin fig. 3c on ImageNet. In the limit, when temperature goes to 0, we recover
Supervised Contrastive method for ImageNet, or SimCLR in case of conceptual captions. With
low temperature, the similarity is 1 only if the captions are exactly the same. As the temperature
increases, more weight is put on the soft positives compared to the true positives (i.e. augmentations
of the same sample). With high temperature, our method is unstable as too much emphasis is put
on the soft positive examples compared to the true positives. We find that the value of 0.1 strikes
the optimal balance and provides an improvement over pure Supervised Contrastive objective, while
still emphasizing true positives enough. For more details regarding how τschanges the objective, see
fig. 7b.
We also experiment with different ways of inferring the graph, including using different text encoders,
using WordNet [Fellbaum, 1998] hierarchy distance, and the purely random graph. We find that over-
all, calculating the similarities using the sentence transformer worked the best [Reimers and Gurevych,
2019]. A more detailed comparison of different graph sources can be found in appendix A.1.
8
Table 6: Label quality matters for fine-grained attribute disambiguation.
Pretraining Data Size Quality MIT States Attributes MIT States Objects
CLIP CC3M 3M Noisy 27.0 40.1
CLIP CC12M 12M Noisy 23.3 36.9
X-CLR CC3M 3M Noisy 29.5 40.7
X-CLR CC12M 12M Noisy 30.1 42.1
X-CLR ImageNet 1M High 30.9 45.8
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00SupCon target similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone0.83 0.50 0.30 0.25 0.21 0.27 0.11 0.11 0.09 0.12 0.08 0.13
0.50 0.80 0.33 0.24 0.15 0.20 0.16 0.20 0.13 0.09 0.02 0.12
0.30 0.33 0.88 0.11 0.30 0.25 0.27 0.38 0.35 0.43 0.42 0.49
0.25 0.24 0.11 0.81 0.37 0.42 0.06 0.00 0.09 0.06 0.17 0.09
0.21 0.15 0.30 0.37 0.86 0.50 0.17 0.21 0.30 0.31 0.34 0.33
0.27 0.20 0.25 0.42 0.50 0.81 0.22 0.09 0.23 0.24 0.24 0.22
0.11 0.16 0.27 0.06 0.17 0.22 1.00 0.70 0.64 0.37 0.34 0.29
0.11 0.20 0.38 0.00 0.21 0.09 0.70 0.96 0.63 0.42 0.34 0.47
0.09 0.13 0.35 0.09 0.30 0.23 0.64 0.63 0.85 0.46 0.36 0.34
0.12 0.09 0.43 0.06 0.31 0.24 0.37 0.42 0.46 0.94 0.54 0.58
0.08 0.02 0.42 0.17 0.34 0.24 0.34 0.34 0.36 0.54 0.95 0.55
0.13 0.12 0.49 0.09 0.33 0.22 0.29 0.47 0.34 0.58 0.55 0.95X-CLR Learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.48 0.23 0.36 0.32 0.37 0.14 0.14 0.16 0.16 0.07 0.12
0.48 1.00 0.29 0.33 0.31 0.41 0.23 0.28 0.23 0.11 0.00 0.20
0.23 0.29 1.00 0.26 0.13 0.12 0.15 0.21 0.23 0.20 0.27 0.34
0.36 0.33 0.26 1.00 0.63 0.64 0.18 0.17 0.20 0.17 0.24 0.23
0.32 0.31 0.13 0.63 1.00 0.60 0.08 0.08 0.15 0.15 0.20 0.25
0.37 0.41 0.12 0.64 0.60 1.00 0.21 0.12 0.15 0.09 0.07 0.21
0.14 0.23 0.15 0.18 0.08 0.21 1.00 0.62 0.63 0.15 0.17 0.09
0.14 0.28 0.21 0.17 0.08 0.12 0.62 1.00 0.62 0.23 0.16 0.35
0.16 0.23 0.23 0.20 0.15 0.15 0.63 0.62 1.00 0.36 0.21 0.20
0.16 0.11 0.20 0.17 0.15 0.09 0.15 0.23 0.36 1.00 0.35 0.36
0.07 0.00 0.27 0.24 0.20 0.07 0.17 0.16 0.21 0.35 1.00 0.32
0.12 0.20 0.34 0.23 0.25 0.21 0.09 0.35 0.20 0.36 0.32 1.00X-CLR target similarities
Felines Dogs Types of balls Musical instruments
Figure 4: Visualizing pairwise similarities SupCon [Khosla et al., 2020] objective does not encour-
age non-zero similarity between samples of different classes (left), while X-CLR target similarities
take into account semantic closeness within categories such as dogs or types of balls (center). On the
right, we see that the trained model successfully learns the soft similarity. For more graphs, see fig. 5.
5.4 The impact of label quality for fine-grained attribute disambiguation
we show in table 6 how label quality can impact downstream performance on finer-grained attribute
disambiguation. we find larger labels from noisy captions degrades performance for fine-grained
object attributes in mit states [Isola et al., 2015] for both contrastive and clip. we find X-CLR
with high quality labels from imagenet, can outperform models trained on much larger noisier data.
compared to clip trained on 12 ×larger data, X-CLR achieves 30.9% vs. 23.3% for clip on attribute
classification and 45.8% vs. 36.9% for clip on object classification under different states. to see more
details regarding the mit states evaluation, see appendix A.5.
6 Discussion
In the present work, we have proposed a new graph perspective on the commonly used contrastive
learning methods and used our insights to develop a better learning objective, X-CLR, by using a
soft similarity graph. The adjacency matrix of the proposed graph contains not just 0 and 1, but
also any values between, with the ability to capture the degree of similarity across samples. We
experiment with different ways of constructing the graph, and find that indeed we can build a soft
graph that improves over the existing binary graph contrastive methods. However, we believe that
there are better ways of constructing the graph than what we found, particularly for the conceptual
captions dataset where the captions are quite noisy. A better graph can possibly be built using other
metadata, such as location or time. We also believe that ideas from X-CLR can possibly be integrated
into non-contrastive objectives such as BYOL [Grill et al., 2020] or VICReg [Bardes et al., 2021] to
enrich representations with similarities across samples.
Limitations The main limitation of the present work is that constructing the cross-sample similarity
graph requires extra data, as well as some extra memory to store it. When the extra data is not
available, the only options remaining are to build the graph using the augmentations, self-distillation,
or other pre-trained models. The resulting method is also highly dependent on the quality of the
graph, as we have seen with conceptual captions datasets.
9 | Section not found | Section not found | Section not found | References
Alex Andonian, Shixing Chen, and Raffay Hamid. Robust cross-modal representation learning with
progressive self-distillation. In Proceedings of the IEEE/CVF Conference on Computer Vision and
Pattern Recognition , pages 16430–16441, 2022.
Andrei Barbu, David Mayo, Julian Alverio, William Luo, Christopher Wang, Dan Gutfreund, Josh
Tenenbaum, and Boris Katz. Objectnet: A large-scale bias-controlled dataset for pushing the limits
of object recognition models. Advances in neural information processing systems , 32, 2019.
Adrien Bardes, Jean Ponce, and Yann LeCun. Vicreg: Variance-invariance-covariance regularization
for self-supervised learning. arXiv preprint arXiv:2105.04906 , 2021.
Lucas Beyer, Olivier J Hénaff, Alexander Kolesnikov, Xiaohua Zhai, and Aäron van den Oord. Are
we done with imagenet? arXiv preprint arXiv:2006.07159 , 2020.
Vivien Cabannes, Leon Bottou, Yann Lecun, and Randall Balestriero. Active self-supervised learning:
A few low-cost relationships are all you need. In Proceedings of the IEEE/CVF International
Conference on Computer Vision , pages 16274–16283, 2023.
Mathilde Caron, Ishan Misra, Julien Mairal, Priya Goyal, Piotr Bojanowski, and Armand Joulin.
Unsupervised learning of visual features by contrasting cluster assignments. Advances in neural
information processing systems , 33:9912–9924, 2020.
Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. A simple framework for
contrastive learning of visual representations. In International conference on machine learning ,
pages 1597–1607. PMLR, 2020.
Xinlei Chen and Kaiming He. Exploring simple siamese representation learning. in 2021 ieee. In
CVF conference on computer vision and pattern recognition (CVPR) , pages 15745–15753, 2020.
S. Chopra, R. Hadsell, and Y . LeCun. Learning a similarity metric discriminatively, with application
to face verification. In 2005 IEEE Computer Society Conference on Computer Vision and Pattern
Recognition (CVPR’05) , volume 1, pages 539–546 vol. 1, 2005. doi: 10.1109/CVPR.2005.202.
Ekin D Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, and Quoc V Le. Autoaugment:
Learning augmentation policies from data. arXiv preprint arXiv:1805.09501 , 2018.
Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. Imagenet: A large-scale hier-
archical image database. In 2009 IEEE Conference on Computer Vision and Pattern Recognition ,
pages 248–255, 2009. doi: 10.1109/CVPR.2009.5206848.
Julien Denize, Jaonary Rabarisoa, Astrid Orcesi, Romain Hérault, and Stéphane Canu. Similarity
contrastive estimation for self-supervised soft contrastive learning. In Proceedings of the IEEE/CVF
Winter Conference on Applications of Computer Vision , pages 2706–2716, 2023.
Debidatta Dwibedi, Yusuf Aytar, Jonathan Tompson, Pierre Sermanet, and Andrew Zisserman. With
a little help from my friends: Nearest-neighbor contrastive learning of visual representations. In
Proceedings of the IEEE/CVF International Conference on Computer Vision , pages 9588–9597,
2021.
Christiane Fellbaum. WordNet: An Electronic Lexical Database . Bradford Books, 1998. URL
https://mitpress.mit.edu/9780262561167/ .
Enrico Fini, Pietro Astolfi, Karteek Alahari, Xavier Alameda-Pineda, Julien Mairal, Moin Nabi, and
Elisa Ricci. Semi-supervised learning made simple with self-supervised clustering. In Proceedings
of the IEEE/CVF conference on computer vision and pattern recognition , pages 3187–3197, 2023a.
Enrico Fini, Pietro Astolfi, Adriana Romero-Soriano, Jakob Verbeek, and Michal Drozdzal. Im-
proved baselines for vision-language pre-training. Transactions on Machine Learning Research ,
2023b. ISSN 2835-8856. URL https://openreview.net/forum?id=a7nvXxNmdV . Featured
Certification.
10
Yuting Gao, Jinfeng Liu, Zihan Xu, Tong Wu, Enwei Zhang, Ke Li, Jie Yang, Wei Liu, and Xing
Sun. Softclip: Softer cross-modal alignment makes clip stronger. In Proceedings of the AAAI
Conference on Artificial Intelligence , volume 38, pages 1860–1868, 2024.
Jean-Bastien Grill, Florian Strub, Florent Altché, Corentin Tallec, Pierre Richemond, Elena
Buchatskaya, Carl Doersch, Bernardo Avila Pires, Zhaohan Guo, Mohammad Gheshlaghi Azar,
et al. Bootstrap your own latent-a new approach to self-supervised learning. Advances in neural
information processing systems , 33:21271–21284, 2020.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image
recognition. corr abs/1512.03385 (2015), 2015.
Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, and Ross Girshick. Momentum contrast for
unsupervised visual representation learning. In Proceedings of the IEEE/CVF conference on
computer vision and pattern recognition , pages 9729–9738, 2020.
Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv
preprint arXiv:1503.02531 , 2015.
David T Hoffmann, Nadine Behrmann, Juergen Gall, Thomas Brox, and Mehdi Noroozi. Ranking info
noise contrastive estimation: Boosting contrastive learning via ranked positives. In Proceedings of
the AAAI Conference on Artificial Intelligence , volume 36, pages 897–905, 2022.
Hailang Huang, Zhijie Nie, Ziqiao Wang, and Ziyu Shang. Cross-modal and uni-modal soft-label
alignment for image-text retrieval. In Proceedings of the AAAI Conference on Artificial Intelligence ,
volume 38, pages 18298–18306, 2024.
Gabriel Ilharco, Mitchell Wortsman, Ross Wightman, Cade Gordon, Nicholas Carlini, Rohan Taori,
Achal Dave, Vaishaal Shankar, Hongseok Namkoong, John Miller, Hannaneh Hajishirzi, Ali
Farhadi, and Ludwig Schmidt. Openclip, July 2021. URL https://doi.org/10.5281/zenodo.
5143773 . If you use this software, please cite it as below.
Phillip Isola, Joseph J Lim, and Edward H Adelson. Discovering states and transformations in image
collections. In Proceedings of the IEEE conference on computer vision and pattern recognition ,
pages 1383–1391, 2015.
Prannay Khosla, Piotr Teterwak, Chen Wang, Aaron Sarna, Yonglong Tian, Phillip Isola, Aaron
Maschinot, Ce Liu, and Dilip Krishnan. Supervised contrastive learning. Advances in neural
information processing systems , 33:18661–18673, 2020.
Aaron van den Oord, Yazhe Li, and Oriol Vinyals. Representation learning with contrastive predictive
coding. arXiv preprint arXiv:1807.03748 , 2018.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal,
Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual
models from natural language supervision. In International conference on machine learning , pages
8748–8763. PMLR, 2021.
Nils Reimers and Iryna Gurevych. Sentence-bert: Sentence embeddings using siamese bert-networks.
arXiv preprint arXiv:1908.10084 , 2019.
Chaitanya K Ryali, David J Schwab, and Ari S Morcos. Characterizing and improving the robustness
of self-supervised learning through background augmentations. arXiv preprint arXiv:2103.12719 ,
2021.
Florian Schroff, Dmitry Kalenichenko, and James Philbin. Facenet: A unified embedding for face
recognition and clustering. In Proceedings of the IEEE conference on computer vision and pattern
recognition , pages 815–823, 2015.
Piyush Sharma, Nan Ding, Sebastian Goodman, and Radu Soricut. Conceptual captions: A cleaned,
hypernymed, image alt-text dataset for automatic image captioning. In Proceedings of the 56th
Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) , pages
2556–2565, 2018.
11
Yonglong Tian, Lijie Fan, Phillip Isola, Huiwen Chang, and Dilip Krishnan. Stablerep: Synthetic
images from text-to-image models make strong visual representation learners. Advances in Neural
Information Processing Systems , 36, 2024.
Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. Llama 2: Open foundation
and fine-tuned chat models. arXiv preprint arXiv:2307.09288 , 2023.
Kai Xiao, Logan Engstrom, Andrew Ilyas, and Aleksander Madry. Noise or signal: The role of image
backgrounds in object recognition. arXiv preprint arXiv:2006.09994 , 2020.
Yang You, Igor Gitman, and Boris Ginsburg. Large batch training of convolutional networks. arXiv
preprint arXiv:1708.03888 , 2017.
Jure Zbontar, Li Jing, Ishan Misra, Yann LeCun, and Stéphane Deny. Barlow twins: Self-supervised
learning via redundancy reduction. International Conference on Machine Learning , 2021.
Mingkai Zheng, Shan You, Fei Wang, Chen Qian, Changshui Zhang, Xiaogang Wang, and Chang
Xu. Ressl: Relational self-supervised learning with weak augmentation. Advances in Neural
Information Processing Systems , 34:2543–2555, 2021.
12
Table 7: The effect of the similarity source on the model performance.
Similarity source ImageNet ImageNet Real Same Class Mixed ObjectNet
Augmentation graph only (SimCLR) 63.2 67.5 45.5 38.3 12.5
Sentence Transformer ( X-CLR) 75.6 81.6 66.5 62.3 27.7
CLIP text encoder 74.4 80.6 67.5 64.2 24.5
LLama2 text encoder 40.9 45.8 38.3 36.0 4.3
Random per class pair, 1 for same class 74.5 80.8 71.0 68.0 26.6
Random per sample pair 0.1 0.1 0 0 0
True class graph (SupCon) 74.4 79.7 63.3 58.8 24.1
Distance in WordNet hierarchy 68.3 74.9 55.7 52.1 21.2
A | appendix A.5.
In all our experiments, to isolate the effect of our learning objective, we fix the backbone architecture
to be a ResNet-50 [He et al., 2015] model as this is the most widely studied, with optimized
hyperparameters, for standard contrastive self-supervised learning [Chen et al., 2020]. We use
the same architecture for CLIP’s vision encoder and take advantage of already optimized publicly
available checkpoints provided by OpenCLIP [Ilharco et al., 2021] for CC12M. Since no comparable
public checkpoint is available for CC3M, we train our own model, see appendix A.4.
4.2X-Sample Contrastive with Well-Labeled Samples
We first experiment with X-Sample Contrastive using well-labeled samples to understand the effect
of incorporating similarities across samples in the training objective. To do so, we use class labels
from ImageNet. We compare X-Sample Contrastive ( X-CLR) to SimCLR as well as Supervised
Contrastive (SupCon), a model whose objective is to explicitly match samples based on their class
labels. We evaluate all models across a suite of benchmarks to gauge how well representations
generalize in terms of classification performance.
We find in table 1 representations learned via X-CLR improve on standard classification performance,
with gains of 12.4% relative to SimCLR and 1.2% relative to Supervised Contrastive on ImageNet.
We find similar gains when evaluated on revised labels from ImageNet Real of 14.1% and 1.9%,
respectively. Finally, we find by capturing similarities across samples, representations learned via
X-CLR are more capable of disambiguating objects from backgrounds and attributes with gains on
ImageNet-9 (for details see appendix A.3) [Xiao et al., 2020] and ObjectNet [Barbu et al., 2019].
Can we improve contrastive learning under data scarcity? To answer this question, we train all
three models SimCLR, SupCon, and X-CLR by varying the number of samples seen for each class in
ImageNet. We find X-CLR, by incorporating information about how classes relate, is able to learn
representations that match the performance of SupCon trained with ground truth class labels and
outperform SimCLR even when few training samples are available per class as shown in fig. 3a.
6
Table 2: X-Sample Contrastive with CC3M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 57.0 64.0 24.4 18.9 10.8
CLIP 41.0 47.6 12.5 10.6 7.8
X-CLR 58.2 65.6 26.7 20.3 11.5
Table 3: X-Sample Contrastive with CC12M training outperforms contrastive baselines.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 58.9 66 24.6 19.8 12.7
CLIP 58.8 66.1 20.5 17.1 11.9
X-CLR 59.4 66.7 26.1 20.4 13.4
4.3X-Sample Contrastive with Noisy Multimodal Samples
Contrastive loss also plays a pivotal role in multimodal vision-language models such as CLIP. The
contrastive training objective matches noisy caption-image pairs. Here we experiment with X-Sample
Contrastive by using the noisy captions to learn similarities across samples. We compare both
SimCLR as a standard contrastive model and CLIP trained on the same caption-image data across
two levels of scale: 3 and 12 million samples from CC3M and CC12M.
We find incorporating X-Contrastive leads to representations with higher classification accuracy and
disambiguation of objects from their attributes and backgrounds. With CC12M training shown in
table 3, X-Contrastive outperforms SimCLR by 0.5% and CLIP by 0.6% with CC12M with similar
gains for ImageNet Real. We also find X-CLR training can better disambiguate object foreground
from backgrounds, with gains of 0.6-1.5% over SimCLR and 3.3-5.6% over CLIP.
We find learning similarites across samples with X-CLR leads to more considerable gains when less
data is available. X-CLR outperforms SimCLR by 1.2% and CLIP by 16.8% on ImageNet, with
similar gains on ImageNet Real as shown in table 2. We find X-CLR training can more considerably
disambiguate object foregrounds from backgrounds compared to CLIP when less training data is
available, with gains of 10.3-13.3% over CLIP.
4.4X-Sample Contrastive can be used to finetune pretrained backbones
We validate whether X-CLR can be used as a finetuning objective for pretrained backbones, given the
growing abundance of publicly available backbones. Here, we evaluate a pretrained SimCLR model
by finetuning for 10 epochs on ImageNet with X-CLR instead of the original SimCLR contrastive
objective. We see in table 4 finetuning with X-CLR improves classification performance on ImageNet
by 3.3% and on ImageNet Real by 6.9%. Furthermore, we see by relating samples during the
finetuning stage, X-CLR can disambiguate object foregrounds from backgrounds with grains of
8.4-11.7% on ImageNet-9 as well as improvements on natural object transformations from ObjectNet
with a gain of 4.9% after finetuning.
Table 4: X-CLR can be used to finetune pretrained models.
Background Decomposition
ImageNet ImageNet Real Same Class Mixed ObjectNet
SimCLR 63.2 67.5 45.5 38.3 12.5
+X-CLR finetuning 66.5 74.4 53.9 50 17.4
7
Table 5: Analyzing the computation overhead of the X-Sample Contrastive objective during
training. X-CLR introduces nearly no computational overhead compared to SimCLR.
Method Seconds per batch ImageNet Seconds per batch CC
SimCLR 0.866 ± 0.008 0.874 ± 0.034
X-CLR 0.866 ± 0.010 0.877 ± 0.032
4.5X-Sample Contrastive introduces only minimal computational overhead
Both for ImageNet and conceptual captions datasets, we don’t run the text encoder for each sample
we see, and instead precompute the similarity values. For more details, see appendix A.5. Avoiding
running the text encoder during model training avoids the extra overhead at the price of some pre-
processing. Pre-processing takes less than 2 hours for CC12M when using one GPU, about 30
minutes for CC3M, and less than 5 minutes for ImageNet. To further analyze how much overhead
there is, we compare the average time it takes to process one batch for SimCLR and X-CLR. The
results are shown in table 5. Overall, we didn’t notice any significant difference in the amount of
time it takes to train models with the X-CLR objective compared to the regular contrastive objective.
To train on ImageNet, we used 8 Nvidia V100s, and each run took about 30 hours. With the same
setup, CC3M runs took about 50 hours, and CC12M runs took roughly 9 days.
5 Analyzing representations learned via X-Sample Contrastive
5.1 KNN Clustering
To confirm the representations learned via X-CLR also work well for downstream tasks with non-
linear decision boundaries, we perform evaluation using the common K-nearest neighbor (KNN)
protocol. The results shown in fig. 3b demonstrate X-CLR outperforms both SimCLR and SupCon
baselines across a range of choices for K. We also show KNN results for models trained on conceptual
captions in appendix A.2.
5.2 Visualizing the learned graph from X-Sample Contrastive representations
Here we examine whether the learned representations from X-Sample Contrastive capture semanti-
cally meaningful similarities. To do so, we select four groups of three ImageNet classes: felines, dogs,
types of balls, and musical instruments. For each pair of classes, we then compare the representation
similarities using cosine similarity. A higher average pairwise similarity indicates the model’s latent
representations encode the classes similarly. In fig. 4 we show the graph of similarities learned
after training with X-CLR on ImageNet. We find that the image encoder successfully captures the
similarity within the class groups.
5.3 The effect of softmax temperature, and inferred similarity graph
We also examine the effect of hyperparameter choices. We show the sensitivity of X-CLR to
temperature τsin fig. 3c on ImageNet. In the limit, when temperature goes to 0, we recover
Supervised Contrastive method for ImageNet, or SimCLR in case of conceptual captions. With
low temperature, the similarity is 1 only if the captions are exactly the same. As the temperature
increases, more weight is put on the soft positives compared to the true positives (i.e. augmentations
of the same sample). With high temperature, our method is unstable as too much emphasis is put
on the soft positive examples compared to the true positives. We find that the value of 0.1 strikes
the optimal balance and provides an improvement over pure Supervised Contrastive objective, while
still emphasizing true positives enough. For more details regarding how τschanges the objective, see
fig. 7b.
We also experiment with different ways of inferring the graph, including using different text encoders,
using WordNet [Fellbaum, 1998] hierarchy distance, and the purely random graph. We find that over-
all, calculating the similarities using the sentence transformer worked the best [Reimers and Gurevych,
2019]. A more detailed comparison of different graph sources can be found in appendix A.1.
8
Table 6: Label quality matters for fine-grained attribute disambiguation.
Pretraining Data Size Quality MIT States Attributes MIT States Objects
CLIP CC3M 3M Noisy 27.0 40.1
CLIP CC12M 12M Noisy 23.3 36.9
X-CLR CC3M 3M Noisy 29.5 40.7
X-CLR CC12M 12M Noisy 30.1 42.1
X-CLR ImageNet 1M High 30.9 45.8
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00SupCon target similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone0.83 0.50 0.30 0.25 0.21 0.27 0.11 0.11 0.09 0.12 0.08 0.13
0.50 0.80 0.33 0.24 0.15 0.20 0.16 0.20 0.13 0.09 0.02 0.12
0.30 0.33 0.88 0.11 0.30 0.25 0.27 0.38 0.35 0.43 0.42 0.49
0.25 0.24 0.11 0.81 0.37 0.42 0.06 0.00 0.09 0.06 0.17 0.09
0.21 0.15 0.30 0.37 0.86 0.50 0.17 0.21 0.30 0.31 0.34 0.33
0.27 0.20 0.25 0.42 0.50 0.81 0.22 0.09 0.23 0.24 0.24 0.22
0.11 0.16 0.27 0.06 0.17 0.22 1.00 0.70 0.64 0.37 0.34 0.29
0.11 0.20 0.38 0.00 0.21 0.09 0.70 0.96 0.63 0.42 0.34 0.47
0.09 0.13 0.35 0.09 0.30 0.23 0.64 0.63 0.85 0.46 0.36 0.34
0.12 0.09 0.43 0.06 0.31 0.24 0.37 0.42 0.46 0.94 0.54 0.58
0.08 0.02 0.42 0.17 0.34 0.24 0.34 0.34 0.36 0.54 0.95 0.55
0.13 0.12 0.49 0.09 0.33 0.22 0.29 0.47 0.34 0.58 0.55 0.95X-CLR Learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.48 0.23 0.36 0.32 0.37 0.14 0.14 0.16 0.16 0.07 0.12
0.48 1.00 0.29 0.33 0.31 0.41 0.23 0.28 0.23 0.11 0.00 0.20
0.23 0.29 1.00 0.26 0.13 0.12 0.15 0.21 0.23 0.20 0.27 0.34
0.36 0.33 0.26 1.00 0.63 0.64 0.18 0.17 0.20 0.17 0.24 0.23
0.32 0.31 0.13 0.63 1.00 0.60 0.08 0.08 0.15 0.15 0.20 0.25
0.37 0.41 0.12 0.64 0.60 1.00 0.21 0.12 0.15 0.09 0.07 0.21
0.14 0.23 0.15 0.18 0.08 0.21 1.00 0.62 0.63 0.15 0.17 0.09
0.14 0.28 0.21 0.17 0.08 0.12 0.62 1.00 0.62 0.23 0.16 0.35
0.16 0.23 0.23 0.20 0.15 0.15 0.63 0.62 1.00 0.36 0.21 0.20
0.16 0.11 0.20 0.17 0.15 0.09 0.15 0.23 0.36 1.00 0.35 0.36
0.07 0.00 0.27 0.24 0.20 0.07 0.17 0.16 0.21 0.35 1.00 0.32
0.12 0.20 0.34 0.23 0.25 0.21 0.09 0.35 0.20 0.36 0.32 1.00X-CLR target similarities
Felines Dogs Types of balls Musical instruments
Figure 4: Visualizing pairwise similarities SupCon [Khosla et al., 2020] objective does not encour-
age non-zero similarity between samples of different classes (left), while X-CLR target similarities
take into account semantic closeness within categories such as dogs or types of balls (center). On the
right, we see that the trained model successfully learns the soft similarity. For more graphs, see fig. 5.
5.4 The impact of label quality for fine-grained attribute disambiguation
we show in table 6 how label quality can impact downstream performance on finer-grained attribute
disambiguation. we find larger labels from noisy captions degrades performance for fine-grained
object attributes in mit states [Isola et al., 2015] for both contrastive and clip. we find X-CLR
with high quality labels from imagenet, can outperform models trained on much larger noisier data.
compared to clip trained on 12 ×larger data, X-CLR achieves 30.9% vs. 23.3% for clip on attribute
classification and 45.8% vs. 36.9% for clip on object classification under different states. to see more
details regarding the mit states evaluation, see appendix A.5.
6 Discussion
In the present work, we have proposed a new graph perspective on the commonly used contrastive
learning methods and used our insights to develop a better learning objective, X-CLR, by using a
soft similarity graph. The adjacency matrix of the proposed graph contains not just 0 and 1, but
also any values between, with the ability to capture the degree of similarity across samples. We
experiment with different ways of constructing the graph, and find that indeed we can build a soft
graph that improves over the existing binary graph contrastive methods. However, we believe that
there are better ways of constructing the graph than what we found, particularly for the conceptual
captions dataset where the captions are quite noisy. A better graph can possibly be built using other
metadata, such as location or time. We also believe that ideas from X-CLR can possibly be integrated
into non-contrastive objectives such as BYOL [Grill et al., 2020] or VICReg [Bardes et al., 2021] to
enrich representations with similarities across samples.
Limitations The main limitation of the present work is that constructing the cross-sample similarity
graph requires extra data, as well as some extra memory to store it. When the extra data is not
available, the only options remaining are to build the graph using the augmentations, self-distillation,
or other pre-trained models. The resulting method is also highly dependent on the quality of the
graph, as we have seen with conceptual captions datasets.
9
References
Alex Andonian, Shixing Chen, and Raffay Hamid. Robust cross-modal representation learning with
progressive self-distillation. In Proceedings of the IEEE/CVF Conference on Computer Vision and
Pattern Recognition , pages 16430–16441, 2022.
Andrei Barbu, David Mayo, Julian Alverio, William Luo, Christopher Wang, Dan Gutfreund, Josh
Tenenbaum, and Boris Katz. Objectnet: A large-scale bias-controlled dataset for pushing the limits
of object recognition models. Advances in neural information processing systems , 32, 2019.
Adrien Bardes, Jean Ponce, and Yann LeCun. Vicreg: Variance-invariance-covariance regularization
for self-supervised learning. arXiv preprint arXiv:2105.04906 , 2021.
Lucas Beyer, Olivier J Hénaff, Alexander Kolesnikov, Xiaohua Zhai, and Aäron van den Oord. Are
we done with imagenet? arXiv preprint arXiv:2006.07159 , 2020.
Vivien Cabannes, Leon Bottou, Yann Lecun, and Randall Balestriero. Active self-supervised learning:
A few low-cost relationships are all you need. In Proceedings of the IEEE/CVF International
Conference on Computer Vision , pages 16274–16283, 2023.
Mathilde Caron, Ishan Misra, Julien Mairal, Priya Goyal, Piotr Bojanowski, and Armand Joulin.
Unsupervised learning of visual features by contrasting cluster assignments. Advances in neural
information processing systems , 33:9912–9924, 2020.
Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. A simple framework for
contrastive learning of visual representations. In International conference on machine learning ,
pages 1597–1607. PMLR, 2020.
Xinlei Chen and Kaiming He. Exploring simple siamese representation learning. in 2021 ieee. In
CVF conference on computer vision and pattern recognition (CVPR) , pages 15745–15753, 2020.
S. Chopra, R. Hadsell, and Y . LeCun. Learning a similarity metric discriminatively, with application
to face verification. In 2005 IEEE Computer Society Conference on Computer Vision and Pattern
Recognition (CVPR’05) , volume 1, pages 539–546 vol. 1, 2005. doi: 10.1109/CVPR.2005.202.
Ekin D Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, and Quoc V Le. Autoaugment:
Learning augmentation policies from data. arXiv preprint arXiv:1805.09501 , 2018.
Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. Imagenet: A large-scale hier-
archical image database. In 2009 IEEE Conference on Computer Vision and Pattern Recognition ,
pages 248–255, 2009. doi: 10.1109/CVPR.2009.5206848.
Julien Denize, Jaonary Rabarisoa, Astrid Orcesi, Romain Hérault, and Stéphane Canu. Similarity
contrastive estimation for self-supervised soft contrastive learning. In Proceedings of the IEEE/CVF
Winter Conference on Applications of Computer Vision , pages 2706–2716, 2023.
Debidatta Dwibedi, Yusuf Aytar, Jonathan Tompson, Pierre Sermanet, and Andrew Zisserman. With
a little help from my friends: Nearest-neighbor contrastive learning of visual representations. In
Proceedings of the IEEE/CVF International Conference on Computer Vision , pages 9588–9597,
2021.
Christiane Fellbaum. WordNet: An Electronic Lexical Database . Bradford Books, 1998. URL
https://mitpress.mit.edu/9780262561167/ .
Enrico Fini, Pietro Astolfi, Karteek Alahari, Xavier Alameda-Pineda, Julien Mairal, Moin Nabi, and
Elisa Ricci. Semi-supervised learning made simple with self-supervised clustering. In Proceedings
of the IEEE/CVF conference on computer vision and pattern recognition , pages 3187–3197, 2023a.
Enrico Fini, Pietro Astolfi, Adriana Romero-Soriano, Jakob Verbeek, and Michal Drozdzal. Im-
proved baselines for vision-language pre-training. Transactions on Machine Learning Research ,
2023b. ISSN 2835-8856. URL https://openreview.net/forum?id=a7nvXxNmdV . Featured
Certification.
10
Yuting Gao, Jinfeng Liu, Zihan Xu, Tong Wu, Enwei Zhang, Ke Li, Jie Yang, Wei Liu, and Xing
Sun. Softclip: Softer cross-modal alignment makes clip stronger. In Proceedings of the AAAI
Conference on Artificial Intelligence , volume 38, pages 1860–1868, 2024.
Jean-Bastien Grill, Florian Strub, Florent Altché, Corentin Tallec, Pierre Richemond, Elena
Buchatskaya, Carl Doersch, Bernardo Avila Pires, Zhaohan Guo, Mohammad Gheshlaghi Azar,
et al. Bootstrap your own latent-a new approach to self-supervised learning. Advances in neural
information processing systems , 33:21271–21284, 2020.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image
recognition. corr abs/1512.03385 (2015), 2015.
Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, and Ross Girshick. Momentum contrast for
unsupervised visual representation learning. In Proceedings of the IEEE/CVF conference on
computer vision and pattern recognition , pages 9729–9738, 2020.
Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv
preprint arXiv:1503.02531 , 2015.
David T Hoffmann, Nadine Behrmann, Juergen Gall, Thomas Brox, and Mehdi Noroozi. Ranking info
noise contrastive estimation: Boosting contrastive learning via ranked positives. In Proceedings of
the AAAI Conference on Artificial Intelligence , volume 36, pages 897–905, 2022.
Hailang Huang, Zhijie Nie, Ziqiao Wang, and Ziyu Shang. Cross-modal and uni-modal soft-label
alignment for image-text retrieval. In Proceedings of the AAAI Conference on Artificial Intelligence ,
volume 38, pages 18298–18306, 2024.
Gabriel Ilharco, Mitchell Wortsman, Ross Wightman, Cade Gordon, Nicholas Carlini, Rohan Taori,
Achal Dave, Vaishaal Shankar, Hongseok Namkoong, John Miller, Hannaneh Hajishirzi, Ali
Farhadi, and Ludwig Schmidt. Openclip, July 2021. URL https://doi.org/10.5281/zenodo.
5143773 . If you use this software, please cite it as below.
Phillip Isola, Joseph J Lim, and Edward H Adelson. Discovering states and transformations in image
collections. In Proceedings of the IEEE conference on computer vision and pattern recognition ,
pages 1383–1391, 2015.
Prannay Khosla, Piotr Teterwak, Chen Wang, Aaron Sarna, Yonglong Tian, Phillip Isola, Aaron
Maschinot, Ce Liu, and Dilip Krishnan. Supervised contrastive learning. Advances in neural
information processing systems , 33:18661–18673, 2020.
Aaron van den Oord, Yazhe Li, and Oriol Vinyals. Representation learning with contrastive predictive
coding. arXiv preprint arXiv:1807.03748 , 2018.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal,
Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual
models from natural language supervision. In International conference on machine learning , pages
8748–8763. PMLR, 2021.
Nils Reimers and Iryna Gurevych. Sentence-bert: Sentence embeddings using siamese bert-networks.
arXiv preprint arXiv:1908.10084 , 2019.
Chaitanya K Ryali, David J Schwab, and Ari S Morcos. Characterizing and improving the robustness
of self-supervised learning through background augmentations. arXiv preprint arXiv:2103.12719 ,
2021.
Florian Schroff, Dmitry Kalenichenko, and James Philbin. Facenet: A unified embedding for face
recognition and clustering. In Proceedings of the IEEE conference on computer vision and pattern
recognition , pages 815–823, 2015.
Piyush Sharma, Nan Ding, Sebastian Goodman, and Radu Soricut. Conceptual captions: A cleaned,
hypernymed, image alt-text dataset for automatic image captioning. In Proceedings of the 56th
Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) , pages
2556–2565, 2018.
11
Yonglong Tian, Lijie Fan, Phillip Isola, Huiwen Chang, and Dilip Krishnan. Stablerep: Synthetic
images from text-to-image models make strong visual representation learners. Advances in Neural
Information Processing Systems , 36, 2024.
Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. Llama 2: Open foundation
and fine-tuned chat models. arXiv preprint arXiv:2307.09288 , 2023.
Kai Xiao, Logan Engstrom, Andrew Ilyas, and Aleksander Madry. Noise or signal: The role of image
backgrounds in object recognition. arXiv preprint arXiv:2006.09994 , 2020.
Yang You, Igor Gitman, and Boris Ginsburg. Large batch training of convolutional networks. arXiv
preprint arXiv:1708.03888 , 2017.
Jure Zbontar, Li Jing, Ishan Misra, Yann LeCun, and Stéphane Deny. Barlow twins: Self-supervised
learning via redundancy reduction. International Conference on Machine Learning , 2021.
Mingkai Zheng, Shan You, Fei Wang, Chen Qian, Changshui Zhang, Xiaogang Wang, and Chang
Xu. Ressl: Relational self-supervised learning with weak augmentation. Advances in Neural
Information Processing Systems , 34:2543–2555, 2021.
12
Table 7: The effect of the similarity source on the model performance.
Similarity source ImageNet ImageNet Real Same Class Mixed ObjectNet
Augmentation graph only (SimCLR) 63.2 67.5 45.5 38.3 12.5
Sentence Transformer ( X-CLR) 75.6 81.6 66.5 62.3 27.7
CLIP text encoder 74.4 80.6 67.5 64.2 24.5
LLama2 text encoder 40.9 45.8 38.3 36.0 4.3
Random per class pair, 1 for same class 74.5 80.8 71.0 68.0 26.6
Random per sample pair 0.1 0.1 0 0 0
True class graph (SupCon) 74.4 79.7 63.3 58.8 24.1
Distance in WordNet hierarchy 68.3 74.9 55.7 52.1 21.2
A Appendix / supplemental material
A.1 More learned similarities comparisons
We compare inferring the similarity graph using different text encoders:
• Graph with connections only between samples of the same class (SupCon);
• Graph with connections only between augmentations of the same image (SimCLR);
•Graph where soft similarity is inferred by comparing representations of the sample captions.
The representations are computed using the sentence transformer [Reimers and Gurevych,
2019], CLIP text encoder [Radford et al., 2021], LLama2 encoder [Touvron et al., 2023];
•Graph where the connection strength is defined by the distance in WordNet [Fellbaum, 1998]
hierarchy;
• Random graph where the cross-sample connections’ strengths are fully random;
The results are shown in table 7. We find that overall, the Sentence Transformer graph performs the
best, although the CLIP text encoder achieves good performance as well. Interestingly, we find that
using WordNet hierarchy distance did not work well. We visualize learned and target similarities for
SupCon graph and for the graph built using CLIP text encoder in fig. 5.
Visualising similarities In fig. 4, to visualize learned similarities, for each class we pick 100
examples from the dataset, encode them. Then, to calculate the average learned similarity between
two classes, we take the 100 examples for each of the two classes, and calculate the Cartesian product,
yielding 10,000 similarities. We take the mean over those 10,000 similarities to represent the average
learn similarity for a class pair.
A.2 KNN evaluation
Apart from testing the models trained on ImageNet using KNN, we also evaluate the models trained
on CC3M and CC12M. The results are shown in fig. 6. We see that X-CLR performs better on CC3M,
and comparatively with SimCLR when trained on CC12M.
A.3 ImageNet-9 details
ImageNet-9 [Xiao et al., 2020] proposes multiple benchmarks to test model robustness to the back-
ground perturbation. In our work, we use "Mixed-Same" and "Mixed-Rand" tasks from ImageNet-9,
and refer to them together as "Background Decomposition".
A.4 CLIP details
In CC3M experiments, we train the model from scratch, as OpenCLIP didn’t have a checkpoint
trained on that dataset. We trained both for 32 and 100 epochs, and found that the model trained for
100 epochs performs better. Since 32 epochs is the default CLIP number of epochs, we also report
results for 32 epochs. The results are shown in table 8.
13
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone0.93 0.70 0.46 0.24 0.37 0.29 0.00 0.10 0.19 0.16 0.15 0.18
0.70 0.93 0.67 0.36 0.29 0.16 0.00 0.13 0.19 0.15 0.17 0.12
0.46 0.67 0.91 0.35 0.38 0.31 0.06 0.13 0.29 0.19 0.19 0.10
0.24 0.36 0.35 0.92 0.21 0.29 0.21 0.16 0.33 0.25 0.24 0.20
0.37 0.29 0.38 0.21 0.89 0.51 0.17 0.20 0.34 0.13 0.13 0.21
0.29 0.16 0.31 0.29 0.51 0.88 0.16 0.17 0.32 0.19 0.25 0.19
0.00 0.00 0.06 0.21 0.17 0.16 1.00 0.68 0.32 0.15 0.21 0.23
0.10 0.13 0.13 0.16 0.20 0.17 0.68 0.98 0.34 0.15 0.14 0.13
0.19 0.19 0.29 0.33 0.34 0.32 0.32 0.34 0.83 0.15 0.06 0.22
0.16 0.15 0.19 0.25 0.13 0.19 0.15 0.15 0.15 0.91 0.38 0.41
0.15 0.17 0.19 0.24 0.13 0.25 0.21 0.14 0.06 0.38 0.92 0.40
0.18 0.12 0.10 0.20 0.21 0.19 0.23 0.13 0.22 0.41 0.40 0.86Learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00T arget similarities
Felines Dogs Types of balls Musical instruments(a) SupCon target and learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone0.92 0.72 0.66 0.57 0.58 0.57 0.11 0.16 0.30 0.11 0.14 0.20
0.72 0.96 0.78 0.66 0.68 0.67 0.07 0.14 0.40 0.03 0.11 0.19
0.66 0.78 0.99 0.81 0.81 0.82 0.00 0.10 0.44 0.01 0.17 0.22
0.57 0.66 0.81 1.00 0.80 0.78 0.00 0.11 0.48 0.07 0.18 0.21
0.58 0.68 0.81 0.80 0.99 0.86 0.00 0.12 0.47 0.03 0.18 0.18
0.57 0.67 0.82 0.78 0.86 1.00 0.02 0.13 0.47 0.02 0.17 0.20
0.11 0.07 0.00 0.00 0.00 0.02 0.86 0.67 0.31 0.31 0.25 0.23
0.16 0.14 0.10 0.11 0.12 0.13 0.67 0.85 0.39 0.26 0.17 0.19
0.30 0.40 0.44 0.48 0.47 0.47 0.31 0.39 0.81 0.13 0.18 0.15
0.11 0.03 0.01 0.07 0.03 0.02 0.31 0.26 0.13 0.85 0.39 0.39
0.14 0.11 0.17 0.18 0.18 0.17 0.25 0.17 0.18 0.39 0.82 0.39
0.20 0.19 0.22 0.21 0.18 0.20 0.23 0.19 0.15 0.39 0.39 0.78Learned similarities
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone
cougar
lynx
tabby
Maltese dog
German shepherd
Doberman
basketball
volleyball
tennis ball
acoustic guitar
grand piano
saxophone1.00 0.47 0.47 0.08 0.19 0.16 0.23 0.20 0.12 0.18 0.06 0.24
0.47 1.00 0.46 0.04 0.23 0.15 0.20 0.13 0.09 0.04 0.00 0.20
0.47 0.46 1.00 0.18 0.33 0.30 0.36 0.27 0.21 0.25 0.24 0.39
0.08 0.04 0.18 1.00 0.27 0.08 0.09 0.03 0.14 0.11 0.12 0.10
0.19 0.23 0.33 0.27 1.00 0.48 0.17 0.13 0.14 0.13 0.12 0.16
0.16 0.15 0.30 0.08 0.48 1.00 0.18 0.14 0.08 0.07 0.05 0.16
0.23 0.20 0.36 0.09 0.17 0.18 1.00 0.72 0.54 0.41 0.34 0.39
0.20 0.13 0.27 0.03 0.13 0.14 0.72 1.00 0.56 0.35 0.21 0.28
0.12 0.09 0.21 0.14 0.14 0.08 0.54 0.56 1.00 0.26 0.19 0.22
0.18 0.04 0.25 0.11 0.13 0.07 0.41 0.35 0.26 1.00 0.44 0.45
0.06 0.00 0.24 0.12 0.12 0.05 0.34 0.21 0.19 0.44 1.00 0.46
0.24 0.20 0.39 0.10 0.16 0.16 0.39 0.28 0.22 0.45 0.46 1.00T arget similarities
Felines Dogs Types of balls Musical instruments
(b) CLIP target and learned similarities
Figure 5: Target and learned similarities for different graphs.
20 40 60 80
K Nearest Neighbors value of K5055606570ImageNet Accuracy
Trained on ImageNet
X-CLR
SimCLR
SupCon
20 40 60 80
K Nearest Neighbors value of K37383940
Trained on CC3M
X-CLR
SimCLR
20 40 60 80
K Nearest Neighbors value of K38394041
Trained on CC12M
X-CLR
SimCLR
Figure 6: Results of models trained on ImageNet, CC3M, CC12M on ImageNet validation when
using KNN classifier.
14
Table 8: CLIP on CC3M We train our own models on CC3M and find that training longer improves
the performance. Nevertheless, CLIP struggles with small datasets.
Background Decomposition
Method ImageNet ImageNet Real Same Class Mixed ObjectNet
CLIP 100 epochs 41.0 47.6 12.5 10.6 7.8
CLIP 32 epochs 36.8 42.0 11.5 9.8 6.0
0.0 0.2 0.4 0.6 0.8 1.00.00.20.40.60.81.01e7 CC3M similarities
0.0 0.2 0.4 0.6 0.8 1.00.00.51.01.52.01e6ImageNet similarities
(a)
32 64 128 256 512 1024 2048 4096 8192
Batch size0.00.20.40.60.81.0True positive probability mass
True Positive Probability Mass vs Batch Size
SimCLR
CC3M s=0.05
CC3M s=0.1
CC3M s=0.15
ImageNet s=0.05
ImageNet s=0.1
ImageNet s=0.15
(b)
Figure 7: (a) Histograms of the similarities calculated using Sentence Transformer on ImageNet
and CC3M. While for ImageNet the average similarity is around 0.35, it is much lower on CC3M,
signifying that the graph contains less information for CC3M. (b) Effect of the temperature and batch
size on the weight assigned to the true positvie.
A.5 More training details
We train SimCLR, SupCon and X-CLR using the LARS optimizer [You et al., 2017]. In all cases, we
use the same ResNet-50, with a two layer projector on top. The output dimension of the projector is
128.
Fetching similarities For ImageNet, since the number of classes is known, we pre-compute the
similarity matrix of dimension 1000×1000 , and retrieve elements from it depending on the associated
class labels for a given sample pair to obtain the similarity value. For conceptual captions, we run the
text encoder on the full dataset and save the encodings to disk. Then, when loading an image from
disk, we also load the associated encoding of the corresponding caption. The similarity matrix for a
given batch is then obtained by calculating the Cartesian product of those encodings.
MIT States In order to evaluate on this dataset using linear probing, we split the dataset randomly
into two even parts, one used for training the linear layer, the other for evaluation. We train separately
to classify objects and attributes.
A.6 Understanding similarities
To understand the graphs we built using for different datasets, we investigate the average cross-sample
similarity in the dataset. The result is shown in fig. 7a. We find that CC3M similarities are in
general lower, possibly because of lower quality annotations. We also investigate how much weight
is assigned to the true positive examples. For SimCLR, it’s always 1. For our method, the amount of
similarity assigned to other samples in the batch depends on the temperature τs, and the batch size.
The exact relationship is shown in fig. 7b.
15 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18103v1 | http://arxiv.org/pdf/2407.18103v1 | Fine-Tuning Large Language Models for Stock Return Prediction Using Newsflow | Tian Guo, Emmanuel Hauptmann | 2024-07-25 | Abstract
Large language models (LLMs) and their fine-tuning techniques have demon-
strated superior performance in various language understanding and generation
tasks. This paper explores fine-tuning LLMs for stock return forecasting with fi-
nancial newsflow. In quantitative investing, return forecasting is fundamental for
subsequent tasks like stock picking, portfolio optimization, etc. We formulate
the model to include text representation and forecasting modules. We propose
to compare the encoder-only and decoder-only LLMs, considering they generate
text representations in distinct ways. The impact of these different representa-
tions on forecasting performance remains an open question. Meanwhile, we com-
pare two simple methods of integrating LLMs’ token-level representations into
the forecasting module. The experiments on real news and investment universes
reveal that: (1) aggregated representations from LLMs’ token-level embeddings
generally produce return predictions that enhance the performance of long-only
and long-short portfolios; (2) in the relatively large investment universe, the de-
coder LLMs-based prediction model leads to stronger portfolios, whereas in the
small universes, there are no consistent winners. Among the three LLMs studied
(DeBERTa, Mistral, Llama), Mistral performs more robustly across different uni-
verses; (3) return predictions derived from LLMs’ text representations are a strong
signal for portfolio construction, outperforming conventional sentiment scores.
1 | Introduction
Quantitative investing relies on extracting quantitative features or signals from various data sources
including market prices, economic indicators, financial text, etc., to build and optimize investment
portfolios [11, 2]. In recent years, the use of text data for quantitative investing has grown signif-
icantly, thanks to the advancement of natural language processing (NLP) techniques [45, 35, 30].
In particular, large language models (LLMs) have demonstrated superior performance on various
language understanding and generation tasks [14, 5, 19, 37], and the fine-tuning technique allows
for adapting the pre-trained LLMs to fit investing-related applications [16, 10].
This paper is focused on return forecasting with financial news for stock picking. Return forecasting
is useful for picking stocks with profit potentials to include in portfolios. Financial news reports on
events and announcements related to companies, industries, the economy, etc., and shows notable
predictive power for stock future performance in previous studies [27, 17].
The conventional way of applying financial news data to stock picking involves a multi-step
extraction-and-validation process as illustrated in Fig. 1(a), i.e., formulating the numerical features
(e.g., sentiments, topics, popularity, etc.) with the expectation that these features have a predictive
relationship with stock future performance (e.g., forward return, volatility, etc.) [1, 36], developing
the calculation processes or machine learning models to extract features from the news (e.g., train
∗Correspondence to [email protected]:2407.18103v1 [q-fin.CP] 25 Jul 2024
News Sentiment
News of Stocks
Forward Return
a
b
Features are expected to have a
predictive relationship with stock
performance e.g.,forward returns
Forecasting Model by Fine-tuning LLMs
Pre-trained Fine-tuned(a)
(b)Inference
Feature Formulation
a
b
Extraction and Validation
To backtest
To backteste.g., train a financial sentiment model
??
?
Training Data
Training Data
Development of Feature Extraction Tools Figure 1: Comparison of different workflows of utilizing financial news for stock picking. (a) Con-
ventional feature extraction-and-validation process, e.g., financial sentiments. (b) News-to-return
forecasting by fine-tuning LLMs.
a financial sentiment classification model), and validating the predictive power of extracted features
by statistical analysis or building forecasting models. This process might be time-consuming and
require additional data (e.g., labeled financial sentiment data) and continuous refinements.
LLMs generate numerical representations (or embeddings) of text that capture semantic relations,
and these representations can naturally serve as features for forecasting tasks. Given this intuition,
this paper explores direct news-to-return prediction through fine-tuning LLMs. Fig. 1 illustrates
the difference between the conventional feature extraction-and-validation process and our LLM-
based news-to-return process. Though some previous works attempted to use text embedding for
forecasting [27, 41, 30, 13], few works have explored the potential of fine-tuning LLMs for stock
return forecasting with newsflow. Moreover, this paper has the contribution as follows:
• We design an LLM-based return prediction model comprising the text representation and
the forecasting modules.
• We hypothesize that the text representations from encoder-only and decoder-only LLMs
will perform differently due to their distinct methods of encoding text sequences during
pre-training and fine-tuning; thus we propose to compare the encoder-only (DeBERTa)
and decoder-only LLMs (Mistral, Llama3) as the representation module of the prediction
model.
• Considering that LLM-generated text representations are at the token level, we present two
simple methods to integrate token representations into the forecasting module: bottleneck
representations and aggregated representations.
• We perform experiments on real financial news and various investment universes. In addi-
tion to evaluating prediction errors, we assess two types of portfolios built on return predic-
tions through backtesting in out-of-sample periods. The experimental comparison between
encoder-only and decoder-only LLMs, as well as between bottleneck and aggregated repre-
sentations, offers insights for identifying suitable text representations for different investing
strategies and markets.
2 | Section not found | Related Work
Numerous works have investigated using financial text data for forecasting tasks. Previous works
mostly used word-level embedding techniques lacking the ability of contextual modeling. [44, 45]
extracted the sentiment score from financial newsflow, social media, and tweets for stock price
predicting. [27, 17] explored learning numeric representations of financial news by attention mech-
anisms for modeling stock movements. [41] studied combining sentiment and text representations
for return prediction. [7] studied the embedding aggregate strategy of news for forex prediction.
2
The advent of LLMs and related techniques provides a new powerful way of using text data for fore-
casting tasks in quantitative investing [47, 26]. LLMs can be broadly categorized into three main
types. Encoder-only models such as BERT (Bidirectional Encoder Representations from Transform-
ers) [9] and DeBERTa (Decoding-enhanced BERT with disentangled attention) [15, 14], focus on
learning contextual embeddings for input text. Decoder-only models like GPT-3 (Generative Pre-
trained Transformer 3) [31] and Mistral [19] are trained to generate text by predicting the next token
in a sequence. Encoder-decoder models including T5 (Text-To-Text Transfer Transformer) [25] and
BART (Bidirectional and Auto-Regressive Transformers) [33] are a mix of both encoder and decoder
architectures and suitable for sequence-to-sequence tasks such as machine translation, summariza-
tion, and question-answering.
LLMs are pre-trained on vast amounts of text data to learn general language patterns. Following
pre-training, there are two main approaches to applying LLMs to downstream tasks. The prompt
technique is to design specific inputs to guide the pre-trained LLM to produce the desired output
without modifying the LLM’s parameters [32, 6, 21]. The second approach is to fine-tune LLMs by
adjusting the pre-trained LLM’s parameters to adapt to specific tasks [12, 42, 10, 8]. In particular,
parameter-efficient fine-tuning techniques have gained popularity [16, 10, 28]. For instance, LoRA
(Low-Rank Adaptation) [16] introduces low-rank adaptations to the pre-trained model parameters,
thereby reducing the computational and memory overhead of fine-tuning.
Some recent works use LLMs as feature extractors to obtain predictive signals from text. Authors
in [3, 29] explored the fine-tuning of pre-trained LLMs to provide more accurate financial sentiment
analysis. Instead of fine-tuning LLMs, [40] extracted factors from the financial news and price
history by prompts on generative LLMs. [20] used chain-of-thought prompts [43] on generative
LLMs to analyze financial statements.
Unlike existing works that extract features from text using LLMs, this paper focuses on fine-tuning
LLMs to directly model the relation between financial text and stocks’ future performance, i.e.,
newsflow and forward return. Meanwhile, we evaluate the text representations from different types
of LLMs to study their different effectiveness for the return forecasting task.
3 From Financial Newsflow to Stock Portfolios through LLMs
3.1 | Section not found | Problem Statement
Assume an investment universe consisting of a set of stocks denoted by U={s}S
s=1, where s
represents the stock index. In quantitative investing, the stock-picking process selects a subset of the
universe as the investing portfolio based on quantitative criteria. As market conditions and various
information change, the stock-picking process is repeatedly performed to update or rebalance the
portfolios at (regular) time intervals, e.g., weekly, monthly, etc.
LLM-based Return
Forecasting Model
Return
Forecasts
Ranking
high
low
Long-only
Portfolio
Long-short
Portfolio
aStocks with
Financial Newsflow
a
b
b
c
c
text
forecasting
module
text to vector
representation
through LLM
Figure 2: Illustration of the LLM-based return forecasting model for the stock-picking process.
Assume an investment universe of 3 stocks denoted by a, b, c . Each stock has an associated list of
news. Then, given the return forecasts and ranks, stocks can be selected into long-only or long-short
portfolios.
This paper is interested in predicting stock returns with news for stock picking. Specifically, let
rs,t+n∈Rbe the n-step forward return of stock sw.r.t. timestep t. The textual content of financial
news reported at time iand w.r.t. stock sis denoted by xs,i, a list of text tokens. At time t, the news
3
text available for predicting rs,t+ℓin a look-back time window Wis{xs,i}i∈Ts,<twhere Ts,<t
represents the set of timesteps of available news.
Considering the large sequence length that LLMs can process nowadays [47, 26], we concatenate
the set of news in the look-back window into one sequence denoted by Xs,<t=⊕{xs,i}i∈Ts,<t,
where ⊕denotes the concatenation operation. Next, we formulate the return forecasting model as a
composite structure of a text representation module and a forecasting module as defined in Eq. 1:
ˆrs,t+ℓ=f◦g(Xs,<t) (1)
We aim to explore realizing Eq. 1 by jointly fine-tuning a pre-trained LLM as g(·)and training a
dense layer as f(·). In particular, Eq. 1 is a sequence-level task requiring the text representation
module g:Xs,<t7→hs,<t to encode the sequence Xs,<t into a numerical vector hs,<t∈RD.
Then, the forecasting module f:hs,<t7→ˆrs,ttransforms hs,<t to the return forecast. We train
the model using a set of data instances pooled from individual stocks and associated news, i.e.,
{(rs,t+ℓ,Xs,<t)}s∈U,t∈Twhere Trepresents the timestamps in the training period.
At test time, besides evaluating prediction errors such as the root mean square error (RMSE), we
implement the return prediction-based stock picking to construct long-only and long-short portfolios
which are subsequently backtested. This process is illustrated in Fig. 2.
Long-Only Portfolios is intended to include stocks with the expectation of a price rise above the
universe average. In practice, it is built by ranking the stocks based on the return forecasts and
selecting the top-K stocks. Kis usually chosen according to the decile or quantile of the universe,
e.g.,10% of the total number of stocks.
Long-Short Portfolios includes both the stocks with the expectation of a price rise and drop. For the
stocks with a price drop expectation, the portfolio can profit by selling them at the present price and
repurchasing them at a lower price in the future. In this paper, the long-short portfolio is built by
including the top-K and bottom-K stocks based on the forecast ranks.
3.2 Methodology
Transformer-based LLMs can be categorized into three main types: encoder-only, decoder-only,
and the hybrid encoder-decoder. All these LLMs transform text into high-dimensional vector repre-
sentations, however, their different pre-training | Section not found | objectives lead to text representations with varying
implications.
In the following, we describe the text representation difference in encoder-only and decoder-only
LLMs. Then, we present two simple | Section not found | Section not found | Methodology
Transformer-based LLMs can be categorized into three main types: encoder-only, decoder-only,
and the hybrid encoder-decoder. All these LLMs transform text into high-dimensional vector repre-
sentations, however, their different pre-training objectives lead to text representations with varying
implications.
In the following, we describe the text representation difference in encoder-only and decoder-only
LLMs. Then, we present two simple | methods of integrating LLMs’ token-level representations into
the forecasting module. The experiments on real news and investment universes
reveal that: (1) aggregated representations from LLMs’ token-level embeddings
generally produce return predictions that enhance the performance of long-only
and long-short portfolios; (2) in the relatively large investment universe, the de-
coder LLMs-based prediction model leads to stronger portfolios, whereas in the
small universes, there are no consistent winners. Among the three LLMs studied
(DeBERTa, Mistral, Llama), Mistral performs more robustly across different uni-
verses; (3) return predictions derived from LLMs’ text representations are a strong
signal for portfolio construction, outperforming conventional sentiment scores.
1 Introduction
Quantitative investing relies on extracting quantitative features or signals from various data sources
including market prices, economic indicators, financial text, etc., to build and optimize investment
portfolios [11, 2]. In recent years, the use of text data for quantitative investing has grown signif-
icantly, thanks to the advancement of natural language processing (NLP) techniques [45, 35, 30].
In particular, large language models (LLMs) have demonstrated superior performance on various
language understanding and generation tasks [14, 5, 19, 37], and the fine-tuning technique allows
for adapting the pre-trained LLMs to fit investing-related applications [16, 10].
This paper is focused on return forecasting with financial news for stock picking. Return forecasting
is useful for picking stocks with profit potentials to include in portfolios. Financial news reports on
events and announcements related to companies, industries, the economy, etc., and shows notable
predictive power for stock future performance in previous studies [27, 17].
The conventional way of applying financial news data to stock picking involves a multi-step
extraction-and-validation process as illustrated in Fig. 1(a), i.e., formulating the numerical features
(e.g., sentiments, topics, popularity, etc.) with the expectation that these features have a predictive
relationship with stock future performance (e.g., forward return, volatility, etc.) [1, 36], developing
the calculation processes or machine learning models to extract features from the news (e.g., train
∗Correspondence to [email protected]:2407.18103v1 [q-fin.CP] 25 Jul 2024
News Sentiment
News of Stocks
Forward Return
a
b
Features are expected to have a
predictive relationship with stock
performance e.g.,forward returns
Forecasting Model by Fine-tuning LLMs
Pre-trained Fine-tuned(a)
(b)Inference
Feature Formulation
a
b
Extraction and Validation
To backtest
To backteste.g., train a financial sentiment model
??
?
Training Data
Training Data
Development of Feature Extraction Tools Figure 1: Comparison of different workflows of utilizing financial news for stock picking. (a) Con-
ventional feature extraction-and-validation process, e.g., financial sentiments. (b) News-to-return
forecasting by fine-tuning LLMs.
a financial sentiment classification model), and validating the predictive power of extracted features
by statistical analysis or building forecasting models. This process might be time-consuming and
require additional data (e.g., labeled financial sentiment data) and continuous refinements.
LLMs generate numerical representations (or embeddings) of text that capture semantic relations,
and these representations can naturally serve as features for forecasting tasks. Given this intuition,
this paper explores direct news-to-return prediction through fine-tuning LLMs. Fig. 1 illustrates
the difference between the conventional feature extraction-and-validation process and our LLM-
based news-to-return process. Though some previous works attempted to use text embedding for
forecasting [27, 41, 30, 13], few works have explored the potential of fine-tuning LLMs for stock
return forecasting with newsflow. Moreover, this paper has the contribution as follows:
• We design an LLM-based return prediction model comprising the text representation and
the forecasting modules.
• We hypothesize that the text representations from encoder-only and decoder-only LLMs
will perform differently due to their distinct methods of encoding text sequences during
pre-training and fine-tuning; thus we propose to compare the encoder-only (DeBERTa)
and decoder-only LLMs (Mistral, Llama3) as the representation module of the prediction
model.
• Considering that LLM-generated text representations are at the token level, we present two
simple methods to integrate token representations into the forecasting module: bottleneck
representations and aggregated representations.
• We perform experiments on real financial news and various investment universes. In addi-
tion to evaluating prediction errors, we assess two types of portfolios built on return predic-
tions through backtesting in out-of-sample periods. The experimental comparison between
encoder-only and decoder-only LLMs, as well as between bottleneck and aggregated repre-
sentations, offers insights for identifying suitable text representations for different investing
strategies and markets.
2 Related Work
Numerous works have investigated using financial text data for forecasting tasks. Previous works
mostly used word-level embedding techniques lacking the ability of contextual modeling. [44, 45]
extracted the sentiment score from financial newsflow, social media, and tweets for stock price
predicting. [27, 17] explored learning numeric representations of financial news by attention mech-
anisms for modeling stock movements. [41] studied combining sentiment and text representations
for return prediction. [7] studied the embedding aggregate strategy of news for forex prediction.
2
The advent of LLMs and related techniques provides a new powerful way of using text data for fore-
casting tasks in quantitative investing [47, 26]. LLMs can be broadly categorized into three main
types. Encoder-only models such as BERT (Bidirectional Encoder Representations from Transform-
ers) [9] and DeBERTa (Decoding-enhanced BERT with disentangled attention) [15, 14], focus on
learning contextual embeddings for input text. Decoder-only models like GPT-3 (Generative Pre-
trained Transformer 3) [31] and Mistral [19] are trained to generate text by predicting the next token
in a sequence. Encoder-decoder models including T5 (Text-To-Text Transfer Transformer) [25] and
BART (Bidirectional and Auto-Regressive Transformers) [33] are a mix of both encoder and decoder
architectures and suitable for sequence-to-sequence tasks such as machine translation, summariza-
tion, and question-answering.
LLMs are pre-trained on vast amounts of text data to learn general language patterns. Following
pre-training, there are two main approaches to applying LLMs to downstream tasks. The prompt
technique is to design specific inputs to guide the pre-trained LLM to produce the desired output
without modifying the LLM’s parameters [32, 6, 21]. The second approach is to fine-tune LLMs by
adjusting the pre-trained LLM’s parameters to adapt to specific tasks [12, 42, 10, 8]. In particular,
parameter-efficient fine-tuning techniques have gained popularity [16, 10, 28]. For instance, LoRA
(Low-Rank Adaptation) [16] introduces low-rank adaptations to the pre-trained model parameters,
thereby reducing the computational and memory overhead of fine-tuning.
Some recent works use LLMs as feature extractors to obtain predictive signals from text. Authors
in [3, 29] explored the fine-tuning of pre-trained LLMs to provide more accurate financial sentiment
analysis. Instead of fine-tuning LLMs, [40] extracted factors from the financial news and price
history by prompts on generative LLMs. [20] used chain-of-thought prompts [43] on generative
LLMs to analyze financial statements.
Unlike existing works that extract features from text using LLMs, this paper focuses on fine-tuning
LLMs to directly model the relation between financial text and stocks’ future performance, i.e.,
newsflow and forward return. Meanwhile, we evaluate the text representations from different types
of LLMs to study their different effectiveness for the return forecasting task.
3 From Financial Newsflow to Stock Portfolios through LLMs
3.1 Problem Statement
Assume an investment universe consisting of a set of stocks denoted by U={s}S
s=1, where s
represents the stock index. In quantitative investing, the stock-picking process selects a subset of the
universe as the investing portfolio based on quantitative criteria. As market conditions and various
information change, the stock-picking process is repeatedly performed to update or rebalance the
portfolios at (regular) time intervals, e.g., weekly, monthly, etc.
LLM-based Return
Forecasting Model
Return
Forecasts
Ranking
high
low
Long-only
Portfolio
Long-short
Portfolio
aStocks with
Financial Newsflow
a
b
b
c
c
text
forecasting
module
text to vector
representation
through LLM
Figure 2: Illustration of the LLM-based return forecasting model for the stock-picking process.
Assume an investment universe of 3 stocks denoted by a, b, c . Each stock has an associated list of
news. Then, given the return forecasts and ranks, stocks can be selected into long-only or long-short
portfolios.
This paper is interested in predicting stock returns with news for stock picking. Specifically, let
rs,t+n∈Rbe the n-step forward return of stock sw.r.t. timestep t. The textual content of financial
news reported at time iand w.r.t. stock sis denoted by xs,i, a list of text tokens. At time t, the news
3
text available for predicting rs,t+ℓin a look-back time window Wis{xs,i}i∈Ts,<twhere Ts,<t
represents the set of timesteps of available news.
Considering the large sequence length that LLMs can process nowadays [47, 26], we concatenate
the set of news in the look-back window into one sequence denoted by Xs,<t=⊕{xs,i}i∈Ts,<t,
where ⊕denotes the concatenation operation. Next, we formulate the return forecasting model as a
composite structure of a text representation module and a forecasting module as defined in Eq. 1:
ˆrs,t+ℓ=f◦g(Xs,<t) (1)
We aim to explore realizing Eq. 1 by jointly fine-tuning a pre-trained LLM as g(·)and training a
dense layer as f(·). In particular, Eq. 1 is a sequence-level task requiring the text representation
module g:Xs,<t7→hs,<t to encode the sequence Xs,<t into a numerical vector hs,<t∈RD.
Then, the forecasting module f:hs,<t7→ˆrs,ttransforms hs,<t to the return forecast. We train
the model using a set of data instances pooled from individual stocks and associated news, i.e.,
{(rs,t+ℓ,Xs,<t)}s∈U,t∈Twhere Trepresents the timestamps in the training period.
At test time, besides evaluating prediction errors such as the root mean square error (RMSE), we
implement the return prediction-based stock picking to construct long-only and long-short portfolios
which are subsequently backtested. This process is illustrated in Fig. 2.
Long-Only Portfolios is intended to include stocks with the expectation of a price rise above the
universe average. In practice, it is built by ranking the stocks based on the return forecasts and
selecting the top-K stocks. Kis usually chosen according to the decile or quantile of the universe,
e.g.,10% of the total number of stocks.
Long-Short Portfolios includes both the stocks with the expectation of a price rise and drop. For the
stocks with a price drop expectation, the portfolio can profit by selling them at the present price and
repurchasing them at a lower price in the future. In this paper, the long-short portfolio is built by
including the top-K and bottom-K stocks based on the forecast ranks.
3.2 Methodology
Transformer-based LLMs can be categorized into three main types: encoder-only, decoder-only,
and the hybrid encoder-decoder. All these LLMs transform text into high-dimensional vector repre-
sentations, however, their different pre-training objectives lead to text representations with varying
implications.
In the following, we describe the text representation difference in encoder-only and decoder-only
LLMs. Then, we present two simple methods of integrating the token-level representations from
LLMs into the forecasting module. These methods introduce no additional parameters to learn and
provide a clear comparison of the native representations of different LLMs for return forecasting.
Encoder-only LLMs vs. Decoder-only LLMs. Given a sequence of text tokens X=
{x1,···, xL}, LLMs output a sequence of vector representations {h1,···,hL}corresponding to
the input tokens. However, as presented below, the vector representations from encoder-only and
decoder-only LLMs encode the different parts of the input sequence.
Pre-training an encoder LLM is mostly based on masked-language modeling [9, 23, 15]. Con-
cretely, it prepares a training text sequence Xby randomly masking some tokens, leading to
ˆX={xmaskifi∈ M elsexi∀i= 1,···, L}.M ⊂ { 1,···, L}represents the indices of to-
kens to mask. The mask token xmaskis a special token without concrete meaning and plays as the
placeholder. Then, the pre-training objective is to predict the masked tokens, i.e., maximizing the
likelihood of masked tokens as:
logp
{xm}m∈M|ˆX
=X
m∈Mlogp(xm|X<m, xmask,X>m)≈X
m∈Mlogp(xm|hm)(2)
In Eq. 2, X<m={x1,···, xm−1}andX>m={xm,···, xL}represent the tokens before and
afterxm. Maximizing Eq. 2 encourages the representation hmto incorporate both the left and
right contexts, i.e., X>mandX<m, for predicting the masked token. Particularly, in the attention
mechanism of Transformers, hmis derived based on the similarities between the mask token xmask
and the context tokens X>mandX<m.
4
On the other hand, a decoder-only LLM models an input sequence autoregressively using the next-
token prediction task [31, 37]. The pre-training objective function is defined in Eq. 3:
logp(x1,···, xL|ˇX) =X
i=1,···,Llogp(xi|X<i)≈X
ilogp(xi|hi−1) (3)
For modeling the first token, the practical way is to add a Beginning-of-Sequence (BOS) token,
i.e.,ˇX=xbos⊕X. Similar to the mask token, the BOS token has no concrete meaning. The
representation hi−1encodes the information from already seen tokens and is derived based on the
relation between xi−1andX<i−1={x1,···, xi−2}.
Bottleneck Representations vs. Aggregated Representations. As LLMs output the token-level
vector representations, to obtain a representation encoding the sequence, the idea of bottleneck rep-
resentation is to push LLMs to compress the sequence information into a single vector representation
during fine-tuning [46, 38, 39].
In practice, this is achieved by appending an End-of-Sequence (EOS) xEOSto the input sequence,
e.g.,Xs,<t⊕xEOS. AsxEOSis constant across sequences, its vector representation hEOSdepends on
the real tokens of the sequence. During fine-tuning, hEOSis fed into the forecasting module as shown
in Eq. 4. The backpropagation process propels hEOSto summarize real tokens’s representations
through the forecasting module.
ˆrs,t+ℓ=f(hEOS) (4)
The bottleneck representation has different implications for encoder-only and decoder-only LLMs.
In encoder-only LLMs, the vector used for predicting is obtained based on the mask token and the
real context tokens during the pre-training, as explained in Eq. 2. As a result, appending an EOS
token (identical to the mask token used in pre-training) aligns the fine-tuning with the pre-training.
This consistency might facilitate the EOS token representation to summarize sequence-level features
effectively. In decoder-only LLMs, the vector representation of each token is conditioned on the
already-seen tokens; thus, the last token of a sequence naturally summarizes the whole sequence,
making an additional EOS token redundant.
In experiments, we observed that appending the EOS token is more helpful for encoder-only LLMs.
For a comparison on the same ground, we append EOS tokens for both encoder-only and decoder-
only LLMs and leave the study on the different impacts of appending tokens to future work.
Meanwhile, considering the recent works on the representation collapse issue of the last token in
certain conditions [4], we present a simple alternative to bottleneck representation, i.e., allowing the
forecasting module to aggregate the representations of all tokens. This can be done using various
methods like averaging, or sophisticated ones like attention mechanisms [24]. In this paper, we
choose the simple averaging method, since it introduces no additional parameters to train and enables
a clear comparison with the bottleneck representation.
ˆrs,t+ℓ=f
1
LX
lhl!
(5)
For encoder-only LLMs, the pre-training and fine-tuning discrepancy arises when using aggregated
representations, because each token’s representation is based on context and itself, instead of the
mask token in pre-training. For decoder-only LLMs, averaging all representations might lead to bias
towards the early tokens of the input sequence. This is because, in the autoregressive setting, the
early tokens are repeatedly incorporated into the representations of all subsequent ones.
Implementations. The text representation module and the forecasting module are respectively ini-
tialized by a pre-trained LLM and a dense layer. Then, the training process jointly fine-tunes the
LLM and learns the forecasting module to minimize the mean squared error (MSE) between the
forecasts and true values. We applied Low-Rank Adaptation (LoRA) to fine-tune LLMs [16]. Other
techniques including gradient checkpointing, mixed precision training, and DeepSpeed are used to
reduce GPU memory [34].
We experiment with one encoder-only LLM, i.e., DeBERTa [14], and two different decoder-only
LLMs, i.e., Mistral-7B and Llama3-8B base models [37, 19]. DeBERTa is a recent encoder-only
LLM that improves upon the BERT model with disentangled content and position embeddings.
5
Mistral-7B is a 7-billion-parameter decoder-only LLM that uses grouped query and sliding win-
dow attention to improve performance. Llama3-8B is an 8-billion-parameter decoder-only LLM
pre-trained on data mixed from different sources, e.g., multilingual, codes, etc., to improve the gen-
eralization ability.
4 Experiments
Data. We use company-level financial newsflow data from 2003 to 2019 provided by a financial data
vendor. Each piece of news has an attribute including the company identifier(s) the news is primarily
about. Meanwhile, we have two investment universe datasets of the North American (NA), European
(EU), and Emerging (EM) markets, which consist of dates, stock identifiers, and the true monthly
forward returns of corresponding stocks and dates. The training and validation data is from 2003 to
2014 for each universe, while the rest is for the out-of-sample testing data. Each instance is built
by linking an entry in the universe data to related news through the stock identifier and a look-back
time window (e.g., one week). Table 2 shows the data stats.
Setup. We train the model only once and then apply the model to obtain the return predictions in the
testing period. We conduct the model training using a batch size of 32, a learning rate of 1e-5, and
a warmup phase of 100steps followed by a linear decay. To fine-tune LLMs, we applied Low-Rank
Adaptation (LoRA) with rank 4to all linear layers. We employ a maximum context length of 4k for
all LLMs used in experiments. All models are trained for 10epochs on 2A100GPUs.
The long-only portfolio is built by taking the stocks with the return predictions falling in the top
(9th) decile of prediction rankings. The long-short portfolios take the stocks in the top ( 9th) and
bottom ( 0th) deciles. The stocks in all portfolios are equally weighted.
We perform backtesting to evaluate the portfolios in monthly rebalancing. It stimulates the trading
of monthly constructed portfolios and reports the cumulative return chart and performance statistics
like annualized returns and Sharpe ratios in the testing period. When backtesting the long-only and
long-short portfolios, besides comparing the portfolios built on return predictions by different LLMs,
we also compare them with the sentiment-based portfolio construction. Specifically, FinBERT is a
fine-tuned BERT (Bidirectional Encoder Representations from Transformers) for financial sentiment
analysis [3]. FinVader is a dictionary-based method with a financial sentiment lexicon [18, 22]. The
sentiment-based portfolios are built using the same method but with sentiment values as the ranking
criteria.
Metrics. As mentioned in the problem statement of Sec. 3.1, the downstream stock picking for
building portfolios is based on the deciles of forecasts; thus we report three decile-wise metrics to
align with downstream scenarios, i.e., decile RMSE, decile precision, and decile return. The decile
return is the actual return of stocks allocated to the decile based on predictions and is directly related
to the portfolio performance. Analyzing the decile return along with the decile RMSE and precision
provides insights into the relation between portfolio performance and prediction accuracy.
Specifically, at each date in the testing data, we group the predictions with the true returns into
deciles based on the ranking of predictions (i.e., the highest predictions are in the top 9th decile and
the lowest ones are in the bottom 0th decile). Then, with the true and predicted returns in each decile
across dates, we calculate the decile RMSE, decile precision, and decile return. The decile precision
is the percentage of the true returns whose decile based on the ranking of true values is equal to the
current decile. It is related to the portfolio performance, because, for instance, a high precision of
the top decile implies that a high proportion of stocks in this decile has a high true forward return,
thereby benefiting the portfolio including stocks from the top decile.
For portfolio backtesting, we report the cumulative return charts and performance statistics like
annualized returns and Sharpe ratios in the testing period. | Section not found | Section not found | Section not found | Results. In the following, we present and discuss mainly the results of the NA universe. The results
of the EU and EM universe are in the Appendix section.
Bottleneck Representations vs. Aggregated Representations: In Fig. 3, we compare the bottleneck
and aggregated representations for the three LLMs in the North American universes through the
decile RMSE, precision, and returns. Each column of Fig. 3 corresponds to a LLM. Meanwhile,
6
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnLlama, Decile Absolute Return
Bottleneck
AggregatedFigure 3: Decile Performance of Bottleneck and Aggregated Representations in the North American
Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom
Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 1: Statistics of Portfolios in the North American Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.76 0.68 − −
Sentiment FinVader 12.26 0.72 2.92 0.39
Sentiment FinBert 20.64 1.22 8.81 0.92
DeBERTa Bottleneck 17.47 0.96 10.83 0.94
DeBERTa Aggregated 25.15 1.20 12.87 1.07
Mistral Bottleneck 21.27 1.15 15.08 1.49
Mistral Aggregated 25.38 1.12 18.30 1.26
Llama Bottleneck 27.00 1.32 20.46 1.49
Llama Aggregated 18.86 1.00 14.29 1.30
Fig. 4 shows the cumulative return charts of portfolios and Table 1 reports the detailed performance
stats of portfolios.
In the bottom row of Fig. 3, the returns from the 0th decile to the 9th decile generally present an
upward trend, implying that overall the return predictions are aligned with actual future performance.
Moreover, we are particularly interested in the top 9th and bottom 0th deciles as they are the main
constituents of portfolios. For the top 9th decile, the aggregated representation model generates a
higher return and benefits the long portfolio, except for Llama. For the EU and EM universe, as
presented in the Appendix section, the aggregated representation model consistently outperforms
the bottleneck one.
Interestingly, the higher returns do not necessarily imply low RMSE in the 9th decile. For instance,
in Fig. 3, the aggregated representation model has a higher decile return, but a higher RMSE, in the
9th decile corresponding to the long-only portfolio for DeBERTa and Mistral. An explanation is that
the9th decile is regarding predicting high-value returns and less accurate predictions of these returns
might have high RMSE. But, if the return prediction still falls into the 9th decile as the true return,
the corresponding decile return is retained. In this case, the decile precision is more indicative of the
decile return, for instance, in Fig. 3 the outperforming representations mostly have a higher precision
in the 9th decile.
As for the bottom 0th decile, a lower return is preferred as the short side of a long-short portfolio
benefits from stocks with underperforming forward returns. In Fig. 3, the aggregated representation
model falls short of lowering the 0th decile’s return for DeBERta and Mistral, however, Table 1
7
shows that the return and Sharpe ratios of long-short portfolios are mostly improved with aggregated
representations compared to the bottleneck representations.
Meanwhile, in the 0th decile, there are complexities in how prediction errors translate to actual
returns. For instance, for DeBERTa, the aggregated representation has higher RMSE and precision
in the bottom 0th decile, implying that some stocks with higher true returns are misallocated to the
0th decile by the prediction. As a result, the 0th decile return of the aggregated representation is
higher. However, when the aggregated representation of Llama has the same pattern in the bottom
decile, the return is as low as expected. This might be because the high precision offsets the impact
of misallocated high returns.
Fig. 4 visualizes the cumulative return of the portfolios using the bottleneck and aggregated repre-
sentation models. The performance of long-only and long-short portfolios correspond to the top and
bottom deciles in Fig. 3. The return curves of the aggregated representation model are notably higher
except for Llama. As shown in the Appendix, the aggregated representation constantly outperforms
the bottleneck representation for the EU and EM universes.
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 4: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Rep-
resentation Models in the North American Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
Encoder-only LLMs vs. Decoder-only LLMs: Fig. 5 shows the comparison of encoder-only and
decoder-only LLMs with the suitable representations for the NA universe, i.e., the aggregated rep-
resentation for DeBERTa and Mistral, and the bottleneck representation for Llama. For the EU and
EM universes in the Appendix, the aggregated representation is favored for all three LLMs.
The decile return in Fig. 5 exhibits that decoder-only Mistral and LLama generate high returns in
the top 9th decile and lower returns in the bottom 0th decile, thereby leading to the outperforming
long-only and long-short portfolios as shown in the cumulative return charts. In particular, the
performances of long-only portfolios are comparable among encoder and decoder LLMs, however,
in long-short portfolios, the short side drags down the performance of the long side, especially for
the encoder-only DeBERTa. This highlights the importance of effective stock selection on both sides
of the portfolio. Meanwhile, all the prediction-based portfolios yield higher returns than the universe
average.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 5: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the North American Universe (best viewed in color).
Prediction-based vs. Sentiment-based Portfolios: In this part, we compare the prediction-based port-
folios with conventional sentiment-based portfolios. Fig. 6 shows the decile returns and the return
8
charts of portfolios, and the performance statistics are in Table 1. The prediction-based portfo-
lios are from the forecasting model with the suited representations, as in the above comparison of
encoder-only and decoder-only LLMs.
In Table 1, the prediction-based long-only and long-short portfolios outperform the sentiment-based
portfolios both in returns and Sharp ratios. In Fig. 6, the return charts of prediction-based portfolios
are above the sentiment-based portfolios. In particular, for the long-short portfolios, as shown in the
return chart, the short side of the sentiment-based method negatively offsets the long side, leading
to underperformance compared with the universe. In contrast, the prediction-based long-short port-
folios have smoother return curves than the long-only portfolios, because the short side mitigates
the overall portfolio’s volatility. The outperformance of prediction-based portfolios suggests that
the return prediction models capture more relevant information from text representations for future
stock performance, leading to effective stock picking.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 6: Comparison with Sentiment-based Portfolios in the North American Universe (best viewed
in color).
5 Conclusion
This paper focuses on return forecasting with financial newsflow for quantitative portfolio con-
struction. Unlike the conventional feature extraction-and-validation workflow, this paper explores
fine-tuning LLMs to directly model the relationship between text representations and stock forward
return. Considering that different LLMs generate token-level representations in distinct ways, we
compare the design choices on two aspects: the encoder-only versus decoder-only LLMs, and the
bottleneck versus aggregated representations.
Our experiments are conducted on real financial news, various investment universes, and differ-
ent portfolios. The results reveal the key | findings: (1) aggregated representations from LLMs’
token-level embeddings generally produce the return predictions that enhance the performance of
long-only and long-short portfolios; (2) in the relatively large investment universe, the decoder
LLMs-based prediction model leads to stronger portfolios, whereas in the small universes, there
are no consistent winners. Among the three LLMs studied (DeBERTa, Mistral, Llama), Mistral
performs more robustly across different universes; (3) return predictions derived from LLMs’ text
representations are a strong signal for portfolio construction, outperforming conventional sentiment
scores.
Several open questions remain for future research. For instance, it is unclear whether the under-
performance of encoder-only DeBERTa in the large investment universe is due to the model size or
other factors, and why DeBERTa has varying performance in different small universes. Evaluating
recently proposed large encoder-only LLMs [39, 5] would be an interesting follow-up. Additionally,
within the decoder-only LLM family, compared with Mistral’s robust performance across investment
universes, the reasons behind Llama’s performance variation need further exploration. | Section not found | Section not found | implications.
In the following, we describe the text representation difference in encoder-only and decoder-only
LLMs. Then, we present two simple methods of integrating the token-level representations from
LLMs into the forecasting module. These methods introduce no additional parameters to learn and
provide a clear comparison of the native representations of different LLMs for return forecasting.
Encoder-only LLMs vs. Decoder-only LLMs. Given a sequence of text tokens X=
{x1,···, xL}, LLMs output a sequence of vector representations {h1,···,hL}corresponding to
the input tokens. However, as presented below, the vector representations from encoder-only and
decoder-only LLMs encode the different parts of the input sequence.
Pre-training an encoder LLM is mostly based on masked-language modeling [9, 23, 15]. Con-
cretely, it prepares a training text sequence Xby randomly masking some tokens, leading to
ˆX={xmaskifi∈ M elsexi∀i= 1,···, L}.M ⊂ { 1,···, L}represents the indices of to-
kens to mask. The mask token xmaskis a special token without concrete meaning and plays as the
placeholder. Then, the pre-training objective is to predict the masked tokens, i.e., maximizing the
likelihood of masked tokens as:
logp
{xm}m∈M|ˆX
=X
m∈Mlogp(xm|X<m, xmask,X>m)≈X
m∈Mlogp(xm|hm)(2)
In Eq. 2, X<m={x1,···, xm−1}andX>m={xm,···, xL}represent the tokens before and
afterxm. Maximizing Eq. 2 encourages the representation hmto incorporate both the left and
right contexts, i.e., X>mandX<m, for predicting the masked token. Particularly, in the attention
mechanism of Transformers, hmis derived based on the similarities between the mask token xmask
and the context tokens X>mandX<m.
4
On the other hand, a decoder-only LLM models an input sequence autoregressively using the next-
token prediction task [31, 37]. The pre-training objective function is defined in Eq. 3:
logp(x1,···, xL|ˇX) =X
i=1,···,Llogp(xi|X<i)≈X
ilogp(xi|hi−1) (3)
For modeling the first token, the practical way is to add a Beginning-of-Sequence (BOS) token,
i.e.,ˇX=xbos⊕X. Similar to the mask token, the BOS token has no concrete meaning. The
representation hi−1encodes the information from already seen tokens and is derived based on the
relation between xi−1andX<i−1={x1,···, xi−2}.
Bottleneck Representations vs. Aggregated Representations. As LLMs output the token-level
vector representations, to obtain a representation encoding the sequence, the idea of bottleneck rep-
resentation is to push LLMs to compress the sequence information into a single vector representation
during fine-tuning [46, 38, 39].
In practice, this is achieved by appending an End-of-Sequence (EOS) xEOSto the input sequence,
e.g.,Xs,<t⊕xEOS. AsxEOSis constant across sequences, its vector representation hEOSdepends on
the real tokens of the sequence. During fine-tuning, hEOSis fed into the forecasting module as shown
in Eq. 4. The backpropagation process propels hEOSto summarize real tokens’s representations
through the forecasting module.
ˆrs,t+ℓ=f(hEOS) (4)
The bottleneck representation has different implications for encoder-only and decoder-only LLMs.
In encoder-only LLMs, the vector used for predicting is obtained based on the mask token and the
real context tokens during the pre-training, as explained in Eq. 2. As a result, appending an EOS
token (identical to the mask token used in pre-training) aligns the fine-tuning with the pre-training.
This consistency might facilitate the EOS token representation to summarize sequence-level features
effectively. In decoder-only LLMs, the vector representation of each token is conditioned on the
already-seen tokens; thus, the last token of a sequence naturally summarizes the whole sequence,
making an additional EOS token redundant.
In experiments, we observed that appending the EOS token is more helpful for encoder-only LLMs.
For a comparison on the same ground, we append EOS tokens for both encoder-only and decoder-
only LLMs and leave the study on the different impacts of appending tokens to | Section not found | future work.
Meanwhile, considering the recent works on the representation collapse issue of the last token in
certain conditions [4], we present a simple alternative to bottleneck representation, i.e., allowing the
forecasting module to aggregate the representations of all tokens. This can be done using various
methods like averaging, or sophisticated ones like attention mechanisms [24]. In this paper, we
choose the simple averaging method, since it introduces no additional parameters to train and enables
a clear comparison with the bottleneck representation.
ˆrs,t+ℓ=f
1
LX
lhl!
(5)
For encoder-only LLMs, the pre-training and fine-tuning discrepancy arises when using aggregated
representations, because each token’s representation is based on context and itself, instead of the
mask token in pre-training. For decoder-only LLMs, averaging all representations might lead to bias
towards the early tokens of the input sequence. This is because, in the autoregressive setting, the
early tokens are repeatedly incorporated into the representations of all subsequent ones.
Implementations. The text representation module and the forecasting module are respectively ini-
tialized by a pre-trained LLM and a dense layer. Then, the training process jointly fine-tunes the
LLM and learns the forecasting module to minimize the mean squared error (MSE) between the
forecasts and true values. We applied Low-Rank Adaptation (LoRA) to fine-tune LLMs [16]. Other
techniques including gradient checkpointing, mixed precision training, and DeepSpeed are used to
reduce GPU memory [34].
We experiment with one encoder-only LLM, i.e., DeBERTa [14], and two different decoder-only
LLMs, i.e., Mistral-7B and Llama3-8B base models [37, 19]. DeBERTa is a recent encoder-only
LLM that improves upon the BERT model with disentangled content and position embeddings.
5
Mistral-7B is a 7-billion-parameter decoder-only LLM that uses grouped query and sliding win-
dow attention to improve performance. Llama3-8B is an 8-billion-parameter decoder-only LLM
pre-trained on data mixed from different sources, e.g., multilingual, codes, etc., to improve the gen-
eralization ability.
4 Experiments
Data. We use company-level financial newsflow data from 2003 to 2019 provided by a financial data
vendor. Each piece of news has an attribute including the company identifier(s) the news is primarily
about. Meanwhile, we have two investment universe datasets of the North American (NA), European
(EU), and Emerging (EM) markets, which consist of dates, stock identifiers, and the true monthly
forward returns of corresponding stocks and dates. The training and validation data is from 2003 to
2014 for each universe, while the rest is for the out-of-sample testing data. Each instance is built
by linking an entry in the universe data to related news through the stock identifier and a look-back
time window (e.g., one week). Table 2 shows the data stats.
Setup. We train the model only once and then apply the model to obtain the return predictions in the
testing period. We conduct the model training using a batch size of 32, a learning rate of 1e-5, and
a warmup phase of 100steps followed by a linear decay. To fine-tune LLMs, we applied Low-Rank
Adaptation (LoRA) with rank 4to all linear layers. We employ a maximum context length of 4k for
all LLMs used in experiments. All models are trained for 10epochs on 2A100GPUs.
The long-only portfolio is built by taking the stocks with the return predictions falling in the top
(9th) decile of prediction rankings. The long-short portfolios take the stocks in the top ( 9th) and
bottom ( 0th) deciles. The stocks in all portfolios are equally weighted.
We perform backtesting to evaluate the portfolios in monthly rebalancing. It stimulates the trading
of monthly constructed portfolios and reports the cumulative return chart and performance statistics
like annualized returns and Sharpe ratios in the testing period. When backtesting the long-only and
long-short portfolios, besides comparing the portfolios built on return predictions by different LLMs,
we also compare them with the sentiment-based portfolio construction. Specifically, FinBERT is a
fine-tuned BERT (Bidirectional Encoder Representations from Transformers) for financial sentiment
analysis [3]. FinVader is a dictionary-based method with a financial sentiment lexicon [18, 22]. The
sentiment-based portfolios are built using the same method but with sentiment values as the ranking
criteria.
Metrics. As mentioned in the problem statement of Sec. 3.1, the downstream stock picking for
building portfolios is based on the deciles of forecasts; thus we report three decile-wise metrics to
align with downstream scenarios, i.e., decile RMSE, decile precision, and decile return. The decile
return is the actual return of stocks allocated to the decile based on predictions and is directly related
to the portfolio performance. Analyzing the decile return along with the decile RMSE and precision
provides insights into the relation between portfolio performance and prediction accuracy.
Specifically, at each date in the testing data, we group the predictions with the true returns into
deciles based on the ranking of predictions (i.e., the highest predictions are in the top 9th decile and
the lowest ones are in the bottom 0th decile). Then, with the true and predicted returns in each decile
across dates, we calculate the decile RMSE, decile precision, and decile return. The decile precision
is the percentage of the true returns whose decile based on the ranking of true values is equal to the
current decile. It is related to the portfolio performance, because, for instance, a high precision of
the top decile implies that a high proportion of stocks in this decile has a high true forward return,
thereby benefiting the portfolio including stocks from the top decile.
For portfolio backtesting, we report the cumulative return charts and performance statistics like
annualized returns and Sharpe ratios in the testing period.
Results. In the following, we present and discuss mainly the results of the NA universe. The results
of the EU and EM universe are in the Appendix section.
Bottleneck Representations vs. Aggregated Representations: In Fig. 3, we compare the bottleneck
and aggregated representations for the three LLMs in the North American universes through the
decile RMSE, precision, and returns. Each column of Fig. 3 corresponds to a LLM. Meanwhile,
6
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnLlama, Decile Absolute Return
Bottleneck
AggregatedFigure 3: Decile Performance of Bottleneck and Aggregated Representations in the North American
Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom
Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 1: Statistics of Portfolios in the North American Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.76 0.68 − −
Sentiment FinVader 12.26 0.72 2.92 0.39
Sentiment FinBert 20.64 1.22 8.81 0.92
DeBERTa Bottleneck 17.47 0.96 10.83 0.94
DeBERTa Aggregated 25.15 1.20 12.87 1.07
Mistral Bottleneck 21.27 1.15 15.08 1.49
Mistral Aggregated 25.38 1.12 18.30 1.26
Llama Bottleneck 27.00 1.32 20.46 1.49
Llama Aggregated 18.86 1.00 14.29 1.30
Fig. 4 shows the cumulative return charts of portfolios and Table 1 reports the detailed performance
stats of portfolios.
In the bottom row of Fig. 3, the returns from the 0th decile to the 9th decile generally present an
upward trend, implying that overall the return predictions are aligned with actual future performance.
Moreover, we are particularly interested in the top 9th and bottom 0th deciles as they are the main
constituents of portfolios. For the top 9th decile, the aggregated representation model generates a
higher return and benefits the long portfolio, except for Llama. For the EU and EM universe, as
presented in the Appendix section, the aggregated representation model consistently outperforms
the bottleneck one.
Interestingly, the higher returns do not necessarily imply low RMSE in the 9th decile. For instance,
in Fig. 3, the aggregated representation model has a higher decile return, but a higher RMSE, in the
9th decile corresponding to the long-only portfolio for DeBERTa and Mistral. An explanation is that
the9th decile is regarding predicting high-value returns and less accurate predictions of these returns
might have high RMSE. But, if the return prediction still falls into the 9th decile as the true return,
the corresponding decile return is retained. In this case, the decile precision is more indicative of the
decile return, for instance, in Fig. 3 the outperforming representations mostly have a higher precision
in the 9th decile.
As for the bottom 0th decile, a lower return is preferred as the short side of a long-short portfolio
benefits from stocks with underperforming forward returns. In Fig. 3, the aggregated representation
model falls short of lowering the 0th decile’s return for DeBERta and Mistral, however, Table 1
7
shows that the return and Sharpe ratios of long-short portfolios are mostly improved with aggregated
representations compared to the bottleneck representations.
Meanwhile, in the 0th decile, there are complexities in how prediction errors translate to actual
returns. For instance, for DeBERTa, the aggregated representation has higher RMSE and precision
in the bottom 0th decile, implying that some stocks with higher true returns are misallocated to the
0th decile by the prediction. As a result, the 0th decile return of the aggregated representation is
higher. However, when the aggregated representation of Llama has the same pattern in the bottom
decile, the return is as low as expected. This might be because the high precision offsets the impact
of misallocated high returns.
Fig. 4 visualizes the cumulative return of the portfolios using the bottleneck and aggregated repre-
sentation models. The performance of long-only and long-short portfolios correspond to the top and
bottom deciles in Fig. 3. The return curves of the aggregated representation model are notably higher
except for Llama. As shown in the Appendix, the aggregated representation constantly outperforms
the bottleneck representation for the EU and EM universes.
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 4: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Rep-
resentation Models in the North American Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
Encoder-only LLMs vs. Decoder-only LLMs: Fig. 5 shows the comparison of encoder-only and
decoder-only LLMs with the suitable representations for the NA universe, i.e., the aggregated rep-
resentation for DeBERTa and Mistral, and the bottleneck representation for Llama. For the EU and
EM universes in the Appendix, the aggregated representation is favored for all three LLMs.
The decile return in Fig. 5 exhibits that decoder-only Mistral and LLama generate high returns in
the top 9th decile and lower returns in the bottom 0th decile, thereby leading to the outperforming
long-only and long-short portfolios as shown in the cumulative return charts. In particular, the
performances of long-only portfolios are comparable among encoder and decoder LLMs, however,
in long-short portfolios, the short side drags down the performance of the long side, especially for
the encoder-only DeBERTa. This highlights the importance of effective stock selection on both sides
of the portfolio. Meanwhile, all the prediction-based portfolios yield higher returns than the universe
average.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 5: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the North American Universe (best viewed in color).
Prediction-based vs. Sentiment-based Portfolios: In this part, we compare the prediction-based port-
folios with conventional sentiment-based portfolios. Fig. 6 shows the decile returns and the return
8
charts of portfolios, and the performance statistics are in Table 1. The prediction-based portfo-
lios are from the forecasting model with the suited representations, as in the above comparison of
encoder-only and decoder-only LLMs.
In Table 1, the prediction-based long-only and long-short portfolios outperform the sentiment-based
portfolios both in returns and Sharp ratios. In Fig. 6, the return charts of prediction-based portfolios
are above the sentiment-based portfolios. In particular, for the long-short portfolios, as shown in the
return chart, the short side of the sentiment-based method negatively offsets the long side, leading
to underperformance compared with the universe. In contrast, the prediction-based long-short port-
folios have smoother return curves than the long-only portfolios, because the short side mitigates
the overall portfolio’s volatility. The outperformance of prediction-based portfolios suggests that
the return prediction models capture more relevant information from text representations for future
stock performance, leading to effective stock picking.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 6: Comparison with Sentiment-based Portfolios in the North American Universe (best viewed
in color).
5 | Conclusion
This paper focuses on return forecasting with financial newsflow for quantitative portfolio con-
struction. Unlike the conventional feature extraction-and-validation workflow, this paper explores
fine-tuning LLMs to directly model the relationship between text representations and stock forward
return. Considering that different LLMs generate token-level representations in distinct ways, we
compare the design choices on two aspects: the encoder-only versus decoder-only LLMs, and the
bottleneck versus aggregated representations.
Our experiments are conducted on real financial news, various investment universes, and differ-
ent portfolios. The results reveal the key findings: (1) aggregated representations from LLMs’
token-level embeddings generally produce the return predictions that enhance the performance of
long-only and long-short portfolios; (2) in the relatively large investment universe, the decoder
LLMs-based prediction model leads to stronger portfolios, whereas in the small universes, there
are no consistent winners. Among the three LLMs studied (DeBERTa, Mistral, Llama), Mistral
performs more robustly across different universes; (3) return predictions derived from LLMs’ text
representations are a strong signal for portfolio construction, outperforming conventional sentiment
scores.
Several open questions remain for future research. For instance, it is unclear whether the under-
performance of encoder-only DeBERTa in the large investment universe is due to the model size or
other factors, and why DeBERTa has varying performance in different small universes. Evaluating
recently proposed large encoder-only LLMs [39, 5] would be an interesting follow-up. Additionally,
within the decoder-only LLM family, compared with Mistral’s robust performance across investment
universes, the reasons behind Llama’s performance variation need further exploration. | Section not found | Section not found | References
[1] David E Allen, Michael McAleer, and Abhay K Singh. Daily market news sentiment and stock
prices. Applied Economics , 51(30):3212–3235, 2019.
[2] Andrew Ang. Asset management: A systematic approach to factor investing . Oxford University
Press, 2014.
[3] Dogu Araci. Finbert: Financial sentiment analysis with pre-trained language models. arXiv
preprint arXiv:1908.10063 , 2019.
9
[4] Federico Barbero, Andrea Banino, Steven Kapturowski, Dharshan Kumaran, Jo ˜ao GM Ara ´ujo,
Alex Vitvitskyi, Razvan Pascanu, and Petar Veli ˇckovi ´c. Transformers need glasses! informa-
tion over-squashing in language tasks. arXiv preprint arXiv:2406.04267 , 2024.
[5] Parishad BehnamGhader, Vaibhav Adlakha, Marius Mosbach, Dzmitry Bahdanau, Nicolas
Chapados, and Siva Reddy. Llm2vec: Large language models are secretly powerful text en-
coders. arXiv preprint arXiv:2404.05961 , 2024.
[6] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhari-
wal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language mod-
els are few-shot learners. Advances in neural information processing systems , 33:1877–1901,
2020.
[7] Deli Chen, Keiko Harimoto, Ruihan Bao, Qi Su, Xu Sun, et al. Group, extract and aggregate:
Summarizing a large amount of finance news for forex movement prediction. arXiv preprint
arXiv:1910.05032 , 2019.
[8] Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Yunxuan
Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, et al. Scaling instruction-finetuned
language models. Journal of Machine Learning Research , 25(70):1–53, 2024.
[9] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of
deep bidirectional transformers for language understanding. In Proceedings of the 2019 Con-
ference of the North American Chapter of the Association for Computational Linguistics: Hu-
man Language Technologies, Volume 1 (Long and Short Papers) , pages 4171–4186, 2019.
[10] Ning Ding, Yujia Qin, Guang Yang, Fuchao Wei, Zonghan Yang, Yusheng Su, Shengding Hu,
Yulin Chen, Chi-Min Chan, Weize Chen, et al. Parameter-efficient fine-tuning of large-scale
pre-trained language models. Nature Machine Intelligence , 5(3):220–235, 2023.
[11] Eugene F Fama and Kenneth R French. Multifactor explanations of asset pricing anomalies.
The journal of finance , 51(1):55–84, 1996.
[12] Beliz Gunel, Jingfei Du, Alexis Conneau, and Ves Stoyanov. Supervised contrastive learning
for pre-trained language model fine-tuning. arXiv preprint arXiv:2011.01403 , 2020.
[13] Tian Guo, Nicolas Jamet, Valentin Betrix, Louis-Alexandre Piquet, and Emmanuel Haupt-
mann. Esg2risk: A deep learning framework from esg news to stock volatility prediction.
arXiv preprint arXiv:2005.02527 , 2020.
[14] Pengcheng He, Jianfeng Gao, and Weizhu Chen. Debertav3: Improving deberta using
electra-style pre-training with gradient-disentangled embedding sharing. arXiv preprint
arXiv:2111.09543 , 2021.
[15] Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. Deberta: Decoding-enhanced
bert with disentangled attention. arXiv preprint arXiv:2006.03654 , 2020.
[16] Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang,
Lu Wang, and Weizhu Chen. Lora: Low-rank adaptation of large language models. arXiv
preprint arXiv:2106.09685 , 2021.
[17] Ziniu Hu, Weiqing Liu, Jiang Bian, Xuanzhe Liu, and Tie-Yan Liu. Listening to chaotic
whispers: A deep learning framework for news-oriented stock trend prediction. In Proceedings
of the eleventh ACM international conference on web search and data mining , pages 261–269,
2018.
[18] Clayton Hutto and Eric Gilbert. Vader: A parsimonious rule-based model for sentiment anal-
ysis of social media text. In Proceedings of the international AAAI conference on web and
social media , volume 8, pages 216–225, 2014.
[19] Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh
Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile
Saulnier, et al. Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[20] Alex Kim, Maximilian Muhn, and Valeri V Nikolaev. Financial statement analysis with large
language models. Chicago Booth Research Paper Forthcoming, Fama-Miller Working Paper ,
2024.
[21] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa.
Large language models are zero-shot reasoners. Advances in neural information processing
systems , 35:22199–22213, 2022.
10
[22] Petr Korab. Finvader: Financial sentiment analysis, 2023.
[23] Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu
Soricut. Albert: A lite bert for self-supervised learning of language representations. In Inter-
national Conference on Learning Representations , 2019.
[24] Chankyu Lee, Rajarshi Roy, Mengyao Xu, Jonathan Raiman, Mohammad Shoeybi, Bryan
Catanzaro, and Wei Ping. Nv-embed: Improved techniques for training llms as generalist
embedding models. arXiv preprint arXiv:2405.17428 , 2024.
[25] Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed,
Omer Levy, Ves Stoyanov, and Luke Zettlemoyer. Bart: Denoising sequence-to-sequence
pre-training for natural language generation, translation, and comprehension. arXiv preprint
arXiv:1910.13461 , 2019.
[26] Yinheng Li, Shaofei Wang, Han Ding, and Hang Chen. Large language models in finance: A
survey. In Proceedings of the fourth ACM international conference on AI in finance , pages
374–382, 2023.
[27] Qikai Liu, Xiang Cheng, Sen Su, and Shuguang Zhu. Hierarchical complementary attention
network for predicting stock price movements with news. In Proceedings of the 27th ACM In-
ternational Conference on Information and Knowledge Management , pages 1603–1606, 2018.
[28] Shih-Yang Liu, Chien-Yi Wang, Hongxu Yin, Pavlo Molchanov, Yu-Chiang Frank Wang,
Kwang-Ting Cheng, and Min-Hung Chen. Dora: Weight-decomposed low-rank adaptation.
arXiv preprint arXiv:2402.09353 , 2024.
[29] Zhuang Liu, Degen Huang, Kaiyu Huang, Zhuang Li, and Jun Zhao. Finbert: A pre-trained
financial language representation model for financial text mining. In Proceedings of the twenty-
ninth international conference on international joint conferences on artificial intelligence ,
pages 4513–4519, 2021.
[30] Yu Qin and Yi Yang. What you say and how you say it matters: Predicting financial risk
using verbal and vocal cues. In 57th Annual Meeting of the Association for Computational
Linguistics (ACL 2019) , page 390, 2019.
[31] Alec Radford, Karthik Narasimhan, Tim Salimans, and Ilya Sutskever. Improving language
understanding by generative pre-training. 2018.
[32] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al.
Language models are unsupervised multitask learners. OpenAI blog , 1(8):9, 2019.
[33] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena,
Yanqi Zhou, Wei Li, and Peter J Liu. Exploring the limits of transfer learning with a unified
text-to-text transformer. Journal of machine learning research , 21(140):1–67, 2020.
[34] Jeff Rasley, Samyam Rajbhandari, Olatunji Ruwase, and Yuxiong He. Deepspeed: System
optimizations enable training deep learning models with over 100 billion parameters. In Pro-
ceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining , pages 3505–3506, 2020.
[35] Ramit Sawhney, Shivam Agarwal, Arnav Wadhwa, and Rajiv Shah. Deep attentive learning for
stock movement prediction from social media text and company correlations. In Proceedings
of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) ,
pages 8415–8426, 2020.
[36] Adam Hale Shapiro, Moritz Sudhof, and Daniel J Wilson. Measuring news sentiment. Journal
of econometrics , 228(2):221–243, 2022.
[37] Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei,
Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. Llama 2: Open
foundation and fine-tuned chat models. arXiv preprint arXiv:2307.09288 , 2023.
[38] Liang Wang, Nan Yang, Xiaolong Huang, Binxing Jiao, Linjun Yang, Daxin Jiang, Rangan
Majumder, and Furu Wei. Simlm: Pre-training with representation bottleneck for dense pas-
sage retrieval. In The 61st Annual Meeting Of The Association For Computational Linguistics ,
2023.
[39] Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang, Rangan Majumder, and Furu Wei.
Improving text embeddings with large language models. arXiv preprint arXiv:2401.00368 ,
2023.
11
[40] Meiyun Wang, Kiyoshi Izumi, and Hiroki Sakaji. Llmfactor: Extracting profitable factors
through prompts for explainable stock movement prediction. arXiv preprint arXiv:2406.10811 ,
2024.
[41] Yaowei Wang, Qing Li, Zhexue Huang, and Junjie Li. Ean: Event attention network for
stock price trend prediction based on sentimental embedding. In Proceedings of the 10th ACM
Conference on Web Science , pages 311–320, 2019.
[42] Jason Wei, Maarten Bosma, Vincent Y Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan
Du, Andrew M Dai, and Quoc V Le. Finetuned language models are zero-shot learners. arXiv
preprint arXiv:2109.01652 , 2021.
[43] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le,
Denny Zhou, et al. Chain-of-thought prompting elicits reasoning in large language models.
Advances in neural information processing systems , 35:24824–24837, 2022.
[44] Bin Weng, Lin Lu, Xing Wang, Fadel M Megahed, and Waldyn Martinez. Predicting short-
term stock prices using ensemble methods and online data sources. Expert Systems with Ap-
plications , 112:258–273, 2018.
[45] Yumo Xu and Shay B Cohen. Stock movement prediction from tweets and historical prices.
InProceedings of the 56th Annual Meeting of the Association for Computational Linguistics
(Volume 1: Long Papers) , pages 1970–1979, 2018.
[46] Linyi Yang, Ruihai Dong, Tin Lok James Ng, and Yang Xu. Leveraging bert to improve the
fears index for stock forecasting. In Proceedings of the First Workshop on Financial Technol-
ogy and Natural Language Processing , pages 54–60, 2019.
[47] Wayne Xin Zhao, Kun Zhou, Junyi Li, Tianyi Tang, Xiaolei Wang, Yupeng Hou, Yingqian
Min, Beichen Zhang, Junjie Zhang, Zican Dong, et al. A survey of large language models.
arXiv preprint arXiv:2303.18223 , 2023.
12
A | Appendix section.
Bottleneck Representations vs. Aggregated Representations: In Fig. 3, we compare the bottleneck
and aggregated representations for the three LLMs in the North American universes through the
decile RMSE, precision, and returns. Each column of Fig. 3 corresponds to a LLM. Meanwhile,
6
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnLlama, Decile Absolute Return
Bottleneck
AggregatedFigure 3: Decile Performance of Bottleneck and Aggregated Representations in the North American
Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom
Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 1: Statistics of Portfolios in the North American Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.76 0.68 − −
Sentiment FinVader 12.26 0.72 2.92 0.39
Sentiment FinBert 20.64 1.22 8.81 0.92
DeBERTa Bottleneck 17.47 0.96 10.83 0.94
DeBERTa Aggregated 25.15 1.20 12.87 1.07
Mistral Bottleneck 21.27 1.15 15.08 1.49
Mistral Aggregated 25.38 1.12 18.30 1.26
Llama Bottleneck 27.00 1.32 20.46 1.49
Llama Aggregated 18.86 1.00 14.29 1.30
Fig. 4 shows the cumulative return charts of portfolios and Table 1 reports the detailed performance
stats of portfolios.
In the bottom row of Fig. 3, the returns from the 0th decile to the 9th decile generally present an
upward trend, implying that overall the return predictions are aligned with actual future performance.
Moreover, we are particularly interested in the top 9th and bottom 0th deciles as they are the main
constituents of portfolios. For the top 9th decile, the aggregated representation model generates a
higher return and benefits the long portfolio, except for Llama. For the EU and EM universe, as
presented in the Appendix section, the aggregated representation model consistently outperforms
the bottleneck one.
Interestingly, the higher returns do not necessarily imply low RMSE in the 9th decile. For instance,
in Fig. 3, the aggregated representation model has a higher decile return, but a higher RMSE, in the
9th decile corresponding to the long-only portfolio for DeBERTa and Mistral. An explanation is that
the9th decile is regarding predicting high-value returns and less accurate predictions of these returns
might have high RMSE. But, if the return prediction still falls into the 9th decile as the true return,
the corresponding decile return is retained. In this case, the decile precision is more indicative of the
decile return, for instance, in Fig. 3 the outperforming representations mostly have a higher precision
in the 9th decile.
As for the bottom 0th decile, a lower return is preferred as the short side of a long-short portfolio
benefits from stocks with underperforming forward returns. In Fig. 3, the aggregated representation
model falls short of lowering the 0th decile’s return for DeBERta and Mistral, however, Table 1
7
shows that the return and Sharpe ratios of long-short portfolios are mostly improved with aggregated
representations compared to the bottleneck representations.
Meanwhile, in the 0th decile, there are complexities in how prediction errors translate to actual
returns. For instance, for DeBERTa, the aggregated representation has higher RMSE and precision
in the bottom 0th decile, implying that some stocks with higher true returns are misallocated to the
0th decile by the prediction. As a result, the 0th decile return of the aggregated representation is
higher. However, when the aggregated representation of Llama has the same pattern in the bottom
decile, the return is as low as expected. This might be because the high precision offsets the impact
of misallocated high returns.
Fig. 4 visualizes the cumulative return of the portfolios using the bottleneck and aggregated repre-
sentation models. The performance of long-only and long-short portfolios correspond to the top and
bottom deciles in Fig. 3. The return curves of the aggregated representation model are notably higher
except for Llama. As shown in the Appendix, the aggregated representation constantly outperforms
the bottleneck representation for the EU and EM universes.
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 4: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Rep-
resentation Models in the North American Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
Encoder-only LLMs vs. Decoder-only LLMs: Fig. 5 shows the comparison of encoder-only and
decoder-only LLMs with the suitable representations for the NA universe, i.e., the aggregated rep-
resentation for DeBERTa and Mistral, and the bottleneck representation for Llama. For the EU and
EM universes in the Appendix, the aggregated representation is favored for all three LLMs.
The decile return in Fig. 5 exhibits that decoder-only Mistral and LLama generate high returns in
the top 9th decile and lower returns in the bottom 0th decile, thereby leading to the outperforming
long-only and long-short portfolios as shown in the cumulative return charts. In particular, the
performances of long-only portfolios are comparable among encoder and decoder LLMs, however,
in long-short portfolios, the short side drags down the performance of the long side, especially for
the encoder-only DeBERTa. This highlights the importance of effective stock selection on both sides
of the portfolio. Meanwhile, all the prediction-based portfolios yield higher returns than the universe
average.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 5: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the North American Universe (best viewed in color).
Prediction-based vs. Sentiment-based Portfolios: In this part, we compare the prediction-based port-
folios with conventional sentiment-based portfolios. Fig. 6 shows the decile returns and the return
8
charts of portfolios, and the performance statistics are in Table 1. The prediction-based portfo-
lios are from the forecasting model with the suited representations, as in the above comparison of
encoder-only and decoder-only LLMs.
In Table 1, the prediction-based long-only and long-short portfolios outperform the sentiment-based
portfolios both in returns and Sharp ratios. In Fig. 6, the return charts of prediction-based portfolios
are above the sentiment-based portfolios. In particular, for the long-short portfolios, as shown in the
return chart, the short side of the sentiment-based method negatively offsets the long side, leading
to underperformance compared with the universe. In contrast, the prediction-based long-short port-
folios have smoother return curves than the long-only portfolios, because the short side mitigates
the overall portfolio’s volatility. The outperformance of prediction-based portfolios suggests that
the return prediction models capture more relevant information from text representations for future
stock performance, leading to effective stock picking.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 6: Comparison with Sentiment-based Portfolios in the North American Universe (best viewed
in color).
5 Conclusion
This paper focuses on return forecasting with financial newsflow for quantitative portfolio con-
struction. Unlike the conventional feature extraction-and-validation workflow, this paper explores
fine-tuning LLMs to directly model the relationship between text representations and stock forward
return. Considering that different LLMs generate token-level representations in distinct ways, we
compare the design choices on two aspects: the encoder-only versus decoder-only LLMs, and the
bottleneck versus aggregated representations.
Our experiments are conducted on real financial news, various investment universes, and differ-
ent portfolios. The results reveal the key findings: (1) aggregated representations from LLMs’
token-level embeddings generally produce the return predictions that enhance the performance of
long-only and long-short portfolios; (2) in the relatively large investment universe, the decoder
LLMs-based prediction model leads to stronger portfolios, whereas in the small universes, there
are no consistent winners. Among the three LLMs studied (DeBERTa, Mistral, Llama), Mistral
performs more robustly across different universes; (3) return predictions derived from LLMs’ text
representations are a strong signal for portfolio construction, outperforming conventional sentiment
scores.
Several open questions remain for future research. For instance, it is unclear whether the under-
performance of encoder-only DeBERTa in the large investment universe is due to the model size or
other factors, and why DeBERTa has varying performance in different small universes. Evaluating
recently proposed large encoder-only LLMs [39, 5] would be an interesting follow-up. Additionally,
within the decoder-only LLM family, compared with Mistral’s robust performance across investment
universes, the reasons behind Llama’s performance variation need further exploration.
References
[1] David E Allen, Michael McAleer, and Abhay K Singh. Daily market news sentiment and stock
prices. Applied Economics , 51(30):3212–3235, 2019.
[2] Andrew Ang. Asset management: A systematic approach to factor investing . Oxford University
Press, 2014.
[3] Dogu Araci. Finbert: Financial sentiment analysis with pre-trained language models. arXiv
preprint arXiv:1908.10063 , 2019.
9
[4] Federico Barbero, Andrea Banino, Steven Kapturowski, Dharshan Kumaran, Jo ˜ao GM Ara ´ujo,
Alex Vitvitskyi, Razvan Pascanu, and Petar Veli ˇckovi ´c. Transformers need glasses! informa-
tion over-squashing in language tasks. arXiv preprint arXiv:2406.04267 , 2024.
[5] Parishad BehnamGhader, Vaibhav Adlakha, Marius Mosbach, Dzmitry Bahdanau, Nicolas
Chapados, and Siva Reddy. Llm2vec: Large language models are secretly powerful text en-
coders. arXiv preprint arXiv:2404.05961 , 2024.
[6] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhari-
wal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language mod-
els are few-shot learners. Advances in neural information processing systems , 33:1877–1901,
2020.
[7] Deli Chen, Keiko Harimoto, Ruihan Bao, Qi Su, Xu Sun, et al. Group, extract and aggregate:
Summarizing a large amount of finance news for forex movement prediction. arXiv preprint
arXiv:1910.05032 , 2019.
[8] Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Yunxuan
Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, et al. Scaling instruction-finetuned
language models. Journal of Machine Learning Research , 25(70):1–53, 2024.
[9] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of
deep bidirectional transformers for language understanding. In Proceedings of the 2019 Con-
ference of the North American Chapter of the Association for Computational Linguistics: Hu-
man Language Technologies, Volume 1 (Long and Short Papers) , pages 4171–4186, 2019.
[10] Ning Ding, Yujia Qin, Guang Yang, Fuchao Wei, Zonghan Yang, Yusheng Su, Shengding Hu,
Yulin Chen, Chi-Min Chan, Weize Chen, et al. Parameter-efficient fine-tuning of large-scale
pre-trained language models. Nature Machine Intelligence , 5(3):220–235, 2023.
[11] Eugene F Fama and Kenneth R French. Multifactor explanations of asset pricing anomalies.
The journal of finance , 51(1):55–84, 1996.
[12] Beliz Gunel, Jingfei Du, Alexis Conneau, and Ves Stoyanov. Supervised contrastive learning
for pre-trained language model fine-tuning. arXiv preprint arXiv:2011.01403 , 2020.
[13] Tian Guo, Nicolas Jamet, Valentin Betrix, Louis-Alexandre Piquet, and Emmanuel Haupt-
mann. Esg2risk: A deep learning framework from esg news to stock volatility prediction.
arXiv preprint arXiv:2005.02527 , 2020.
[14] Pengcheng He, Jianfeng Gao, and Weizhu Chen. Debertav3: Improving deberta using
electra-style pre-training with gradient-disentangled embedding sharing. arXiv preprint
arXiv:2111.09543 , 2021.
[15] Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. Deberta: Decoding-enhanced
bert with disentangled attention. arXiv preprint arXiv:2006.03654 , 2020.
[16] Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang,
Lu Wang, and Weizhu Chen. Lora: Low-rank adaptation of large language models. arXiv
preprint arXiv:2106.09685 , 2021.
[17] Ziniu Hu, Weiqing Liu, Jiang Bian, Xuanzhe Liu, and Tie-Yan Liu. Listening to chaotic
whispers: A deep learning framework for news-oriented stock trend prediction. In Proceedings
of the eleventh ACM international conference on web search and data mining , pages 261–269,
2018.
[18] Clayton Hutto and Eric Gilbert. Vader: A parsimonious rule-based model for sentiment anal-
ysis of social media text. In Proceedings of the international AAAI conference on web and
social media , volume 8, pages 216–225, 2014.
[19] Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh
Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile
Saulnier, et al. Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[20] Alex Kim, Maximilian Muhn, and Valeri V Nikolaev. Financial statement analysis with large
language models. Chicago Booth Research Paper Forthcoming, Fama-Miller Working Paper ,
2024.
[21] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa.
Large language models are zero-shot reasoners. Advances in neural information processing
systems , 35:22199–22213, 2022.
10
[22] Petr Korab. Finvader: Financial sentiment analysis, 2023.
[23] Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu
Soricut. Albert: A lite bert for self-supervised learning of language representations. In Inter-
national Conference on Learning Representations , 2019.
[24] Chankyu Lee, Rajarshi Roy, Mengyao Xu, Jonathan Raiman, Mohammad Shoeybi, Bryan
Catanzaro, and Wei Ping. Nv-embed: Improved techniques for training llms as generalist
embedding models. arXiv preprint arXiv:2405.17428 , 2024.
[25] Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed,
Omer Levy, Ves Stoyanov, and Luke Zettlemoyer. Bart: Denoising sequence-to-sequence
pre-training for natural language generation, translation, and comprehension. arXiv preprint
arXiv:1910.13461 , 2019.
[26] Yinheng Li, Shaofei Wang, Han Ding, and Hang Chen. Large language models in finance: A
survey. In Proceedings of the fourth ACM international conference on AI in finance , pages
374–382, 2023.
[27] Qikai Liu, Xiang Cheng, Sen Su, and Shuguang Zhu. Hierarchical complementary attention
network for predicting stock price movements with news. In Proceedings of the 27th ACM In-
ternational Conference on Information and Knowledge Management , pages 1603–1606, 2018.
[28] Shih-Yang Liu, Chien-Yi Wang, Hongxu Yin, Pavlo Molchanov, Yu-Chiang Frank Wang,
Kwang-Ting Cheng, and Min-Hung Chen. Dora: Weight-decomposed low-rank adaptation.
arXiv preprint arXiv:2402.09353 , 2024.
[29] Zhuang Liu, Degen Huang, Kaiyu Huang, Zhuang Li, and Jun Zhao. Finbert: A pre-trained
financial language representation model for financial text mining. In Proceedings of the twenty-
ninth international conference on international joint conferences on artificial intelligence ,
pages 4513–4519, 2021.
[30] Yu Qin and Yi Yang. What you say and how you say it matters: Predicting financial risk
using verbal and vocal cues. In 57th Annual Meeting of the Association for Computational
Linguistics (ACL 2019) , page 390, 2019.
[31] Alec Radford, Karthik Narasimhan, Tim Salimans, and Ilya Sutskever. Improving language
understanding by generative pre-training. 2018.
[32] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al.
Language models are unsupervised multitask learners. OpenAI blog , 1(8):9, 2019.
[33] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena,
Yanqi Zhou, Wei Li, and Peter J Liu. Exploring the limits of transfer learning with a unified
text-to-text transformer. Journal of machine learning research , 21(140):1–67, 2020.
[34] Jeff Rasley, Samyam Rajbhandari, Olatunji Ruwase, and Yuxiong He. Deepspeed: System
optimizations enable training deep learning models with over 100 billion parameters. In Pro-
ceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining , pages 3505–3506, 2020.
[35] Ramit Sawhney, Shivam Agarwal, Arnav Wadhwa, and Rajiv Shah. Deep attentive learning for
stock movement prediction from social media text and company correlations. In Proceedings
of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) ,
pages 8415–8426, 2020.
[36] Adam Hale Shapiro, Moritz Sudhof, and Daniel J Wilson. Measuring news sentiment. Journal
of econometrics , 228(2):221–243, 2022.
[37] Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei,
Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. Llama 2: Open
foundation and fine-tuned chat models. arXiv preprint arXiv:2307.09288 , 2023.
[38] Liang Wang, Nan Yang, Xiaolong Huang, Binxing Jiao, Linjun Yang, Daxin Jiang, Rangan
Majumder, and Furu Wei. Simlm: Pre-training with representation bottleneck for dense pas-
sage retrieval. In The 61st Annual Meeting Of The Association For Computational Linguistics ,
2023.
[39] Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang, Rangan Majumder, and Furu Wei.
Improving text embeddings with large language models. arXiv preprint arXiv:2401.00368 ,
2023.
11
[40] Meiyun Wang, Kiyoshi Izumi, and Hiroki Sakaji. Llmfactor: Extracting profitable factors
through prompts for explainable stock movement prediction. arXiv preprint arXiv:2406.10811 ,
2024.
[41] Yaowei Wang, Qing Li, Zhexue Huang, and Junjie Li. Ean: Event attention network for
stock price trend prediction based on sentimental embedding. In Proceedings of the 10th ACM
Conference on Web Science , pages 311–320, 2019.
[42] Jason Wei, Maarten Bosma, Vincent Y Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan
Du, Andrew M Dai, and Quoc V Le. Finetuned language models are zero-shot learners. arXiv
preprint arXiv:2109.01652 , 2021.
[43] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le,
Denny Zhou, et al. Chain-of-thought prompting elicits reasoning in large language models.
Advances in neural information processing systems , 35:24824–24837, 2022.
[44] Bin Weng, Lin Lu, Xing Wang, Fadel M Megahed, and Waldyn Martinez. Predicting short-
term stock prices using ensemble methods and online data sources. Expert Systems with Ap-
plications , 112:258–273, 2018.
[45] Yumo Xu and Shay B Cohen. Stock movement prediction from tweets and historical prices.
InProceedings of the 56th Annual Meeting of the Association for Computational Linguistics
(Volume 1: Long Papers) , pages 1970–1979, 2018.
[46] Linyi Yang, Ruihai Dong, Tin Lok James Ng, and Yang Xu. Leveraging bert to improve the
fears index for stock forecasting. In Proceedings of the First Workshop on Financial Technol-
ogy and Natural Language Processing , pages 54–60, 2019.
[47] Wayne Xin Zhao, Kun Zhou, Junyi Li, Tianyi Tang, Xiaolei Wang, Yupeng Hou, Yingqian
Min, Beichen Zhang, Junjie Zhang, Zican Dong, et al. A survey of large language models.
arXiv preprint arXiv:2303.18223 , 2023.
12
A Appendix
Table 2: Statistics of Datasets.
Universe # of Stocks Average # of News per Instance # of Training Instances # of Validating Instances # of Testing Instances
North America 630 2.5 366011 10167 241367
Europe 350 1.9 100403 10041 121705
Emerging Markets 370 2.6 71610 10231 183608
A.1 Results of the European Universe
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnLlama, Decile Absolute Return
Bottleneck
Aggregated
Figure 7: Decile Performance of Bottleneck and Aggregated Representations in the European Uni-
verse (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom Row:
Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 3: Statistics of Portfolios in the European Universe. The Universe Equally-Weighted repre-
sents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.75 0.74 − −
Sentiment FinVader 10.25 0.70 3.40 0.45
Sentiment FinBert 8.17 0.57 -0.36 0.00
DeBERTa Bottleneck 11.04 0.81 2.11 0.31
DeBERTa Aggregated 11.11 0.81 3.84 0.52
Mistral Bottleneck 6.40 0.48 1.94 0.26
Mistral Aggregated 15.12 1.02 9.07 1.04
Llama Bottleneck 8.20 0.62 1.25 0.17
Llama Aggregated 12.76 0.90 11.47 1.27
13
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-WeightedFigure 8: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Repre-
sentation Models in the European Universe (best viewed in color). Top Row: Long-only Portfolios.
Bottom Row: Long-short Portfolios.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEurope, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 9: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the European Universe (best viewed in color).
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEurope, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 10: Comparison with Sentiment-based Portfolios in the European Universe (best viewed in
color).
14
A.2 Results of the Emerging Markets Universe
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnLlama, Decile Absolute Return
Bottleneck
Aggregated
Figure 11: Decile Performance of Bottleneck and Aggregated Representations in the Emerging
Markets Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision.
Bottom Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are
desirable.
Table 4: Statistics of Portfolios in the Emerging Markets Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 3.91 0.32 − −
Sentiment FinVader 6.18 0.43 -0.08 0.04
Sentiment FinBert 9.76 0.70 1.69 0.21
DeBERTa Bottleneck 7.32 0.50 -5.00 -0.36
DeBERTa Aggregated 9.88 0.64 10.96 0.97
Mistral Bottleneck 10.12 0.63 4.94 0.47
Mistral Aggregated 10.11 0.64 9.16 0.68
Llama Bottleneck 4.94 0.36 -3.99 -0.28
Llama Aggregated 8.82 0.58 1.83 0.19
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 12: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Repre-
sentation Models in the Emerging Markets Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
15
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEmerging Markets, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-WeightedFigure 13: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations
in the Emerging Markets Universe (best viewed in color).
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEmerging Markets, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 14: Comparison with Sentiment-based Portfolios in the Emerging Markets Universe (best
viewed in color).
16 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | statistical analysis or building forecasting models. This process might be time-consuming and
require additional data (e.g., labeled financial sentiment data) and continuous refinements.
LLMs generate numerical representations (or embeddings) of text that capture semantic relations,
and these representations can naturally serve as features for forecasting tasks. Given this intuition,
this paper explores direct news-to-return prediction through fine-tuning LLMs. Fig. 1 illustrates
the difference between the conventional feature extraction-and-validation process and our LLM-
based news-to-return process. Though some previous works attempted to use text embedding for
forecasting [27, 41, 30, 13], few works have explored the potential of fine-tuning LLMs for stock
return forecasting with newsflow. Moreover, this paper has the contribution as follows:
• We design an LLM-based return prediction model comprising the text representation and
the forecasting modules.
• We hypothesize that the text representations from encoder-only and decoder-only LLMs
will perform differently due to their distinct methods of encoding text sequences during
pre-training and fine-tuning; thus we propose to compare the encoder-only (DeBERTa)
and decoder-only LLMs (Mistral, Llama3) as the representation module of the prediction
model.
• Considering that LLM-generated text representations are at the token level, we present two
simple methods to integrate token representations into the forecasting module: bottleneck
representations and aggregated representations.
• We perform experiments on real financial news and various investment universes. In addi-
tion to evaluating prediction errors, we assess two types of portfolios built on return predic-
tions through backtesting in out-of-sample periods. The experimental comparison between
encoder-only and decoder-only LLMs, as well as between bottleneck and aggregated repre-
sentations, offers insights for identifying suitable text representations for different investing
strategies and markets.
2 Related Work
Numerous works have investigated using financial text data for forecasting tasks. Previous works
mostly used word-level embedding techniques lacking the ability of contextual modeling. [44, 45]
extracted the sentiment score from financial newsflow, social media, and tweets for stock price
predicting. [27, 17] explored learning numeric representations of financial news by attention mech-
anisms for modeling stock movements. [41] studied combining sentiment and text representations
for return prediction. [7] studied the embedding aggregate strategy of news for forex prediction.
2
The advent of LLMs and related techniques provides a new powerful way of using text data for fore-
casting tasks in quantitative investing [47, 26]. LLMs can be broadly categorized into three main
types. Encoder-only models such as BERT (Bidirectional Encoder Representations from Transform-
ers) [9] and DeBERTa (Decoding-enhanced BERT with disentangled attention) [15, 14], focus on
learning contextual embeddings for input text. Decoder-only models like GPT-3 (Generative Pre-
trained Transformer 3) [31] and Mistral [19] are trained to generate text by predicting the next token
in a sequence. Encoder-decoder models including T5 (Text-To-Text Transfer Transformer) [25] and
BART (Bidirectional and Auto-Regressive Transformers) [33] are a mix of both encoder and decoder
architectures and suitable for sequence-to-sequence tasks such as machine translation, summariza-
tion, and question-answering.
LLMs are pre-trained on vast amounts of text data to learn general language patterns. Following
pre-training, there are two main approaches to applying LLMs to downstream tasks. The prompt
technique is to design specific inputs to guide the pre-trained LLM to produce the desired output
without modifying the LLM’s parameters [32, 6, 21]. The second approach is to fine-tune LLMs by
adjusting the pre-trained LLM’s parameters to adapt to specific tasks [12, 42, 10, 8]. In particular,
parameter-efficient fine-tuning techniques have gained popularity [16, 10, 28]. For instance, LoRA
(Low-Rank Adaptation) [16] introduces low-rank adaptations to the pre-trained model parameters,
thereby reducing the computational and memory overhead of fine-tuning.
Some recent works use LLMs as feature extractors to obtain predictive signals from text. Authors
in [3, 29] explored the fine-tuning of pre-trained LLMs to provide more accurate financial sentiment
analysis. Instead of fine-tuning LLMs, [40] extracted factors from the financial news and price
history by prompts on generative LLMs. [20] used chain-of-thought prompts [43] on generative
LLMs to analyze financial statements.
Unlike existing works that extract features from text using LLMs, this paper focuses on fine-tuning
LLMs to directly model the relation between financial text and stocks’ future performance, i.e.,
newsflow and forward return. Meanwhile, we evaluate the text representations from different types
of LLMs to study their different effectiveness for the return forecasting task.
3 From Financial Newsflow to Stock Portfolios through LLMs
3.1 Problem Statement
Assume an investment universe consisting of a set of stocks denoted by U={s}S
s=1, where s
represents the stock index. In quantitative investing, the stock-picking process selects a subset of the
universe as the investing portfolio based on quantitative criteria. As market conditions and various
information change, the stock-picking process is repeatedly performed to update or rebalance the
portfolios at (regular) time intervals, e.g., weekly, monthly, etc.
LLM-based Return
Forecasting Model
Return
Forecasts
Ranking
high
low
Long-only
Portfolio
Long-short
Portfolio
aStocks with
Financial Newsflow
a
b
b
c
c
text
forecasting
module
text to vector
representation
through LLM
Figure 2: Illustration of the LLM-based return forecasting model for the stock-picking process.
Assume an investment universe of 3 stocks denoted by a, b, c . Each stock has an associated list of
news. Then, given the return forecasts and ranks, stocks can be selected into long-only or long-short
portfolios.
This paper is interested in predicting stock returns with news for stock picking. Specifically, let
rs,t+n∈Rbe the n-step forward return of stock sw.r.t. timestep t. The textual content of financial
news reported at time iand w.r.t. stock sis denoted by xs,i, a list of text tokens. At time t, the news
3
text available for predicting rs,t+ℓin a look-back time window Wis{xs,i}i∈Ts,<twhere Ts,<t
represents the set of timesteps of available news.
Considering the large sequence length that LLMs can process nowadays [47, 26], we concatenate
the set of news in the look-back window into one sequence denoted by Xs,<t=⊕{xs,i}i∈Ts,<t,
where ⊕denotes the concatenation operation. Next, we formulate the return forecasting model as a
composite structure of a text representation module and a forecasting module as defined in Eq. 1:
ˆrs,t+ℓ=f◦g(Xs,<t) (1)
We aim to explore realizing Eq. 1 by jointly fine-tuning a pre-trained LLM as g(·)and training a
dense layer as f(·). In particular, Eq. 1 is a sequence-level task requiring the text representation
module g:Xs,<t7→hs,<t to encode the sequence Xs,<t into a numerical vector hs,<t∈RD.
Then, the forecasting module f:hs,<t7→ˆrs,ttransforms hs,<t to the return forecast. We train
the model using a set of data instances pooled from individual stocks and associated news, i.e.,
{(rs,t+ℓ,Xs,<t)}s∈U,t∈Twhere Trepresents the timestamps in the training period.
At test time, besides evaluating prediction errors such as the root mean square error (RMSE), we
implement the return prediction-based stock picking to construct long-only and long-short portfolios
which are subsequently backtested. This process is illustrated in Fig. 2.
Long-Only Portfolios is intended to include stocks with the expectation of a price rise above the
universe average. In practice, it is built by ranking the stocks based on the return forecasts and
selecting the top-K stocks. Kis usually chosen according to the decile or quantile of the universe,
e.g.,10% of the total number of stocks.
Long-Short Portfolios includes both the stocks with the expectation of a price rise and drop. For the
stocks with a price drop expectation, the portfolio can profit by selling them at the present price and
repurchasing them at a lower price in the future. In this paper, the long-short portfolio is built by
including the top-K and bottom-K stocks based on the forecast ranks.
3.2 Methodology
Transformer-based LLMs can be categorized into three main types: encoder-only, decoder-only,
and the hybrid encoder-decoder. All these LLMs transform text into high-dimensional vector repre-
sentations, however, their different pre-training objectives lead to text representations with varying
implications.
In the following, we describe the text representation difference in encoder-only and decoder-only
LLMs. Then, we present two simple methods of integrating the token-level representations from
LLMs into the forecasting module. These methods introduce no additional parameters to learn and
provide a clear comparison of the native representations of different LLMs for return forecasting.
Encoder-only LLMs vs. Decoder-only LLMs. Given a sequence of text tokens X=
{x1,···, xL}, LLMs output a sequence of vector representations {h1,···,hL}corresponding to
the input tokens. However, as presented below, the vector representations from encoder-only and
decoder-only LLMs encode the different parts of the input sequence.
Pre-training an encoder LLM is mostly based on masked-language modeling [9, 23, 15]. Con-
cretely, it prepares a training text sequence Xby randomly masking some tokens, leading to
ˆX={xmaskifi∈ M elsexi∀i= 1,···, L}.M ⊂ { 1,···, L}represents the indices of to-
kens to mask. The mask token xmaskis a special token without concrete meaning and plays as the
placeholder. Then, the pre-training objective is to predict the masked tokens, i.e., maximizing the
likelihood of masked tokens as:
logp
{xm}m∈M|ˆX
=X
m∈Mlogp(xm|X<m, xmask,X>m)≈X
m∈Mlogp(xm|hm)(2)
In Eq. 2, X<m={x1,···, xm−1}andX>m={xm,···, xL}represent the tokens before and
afterxm. Maximizing Eq. 2 encourages the representation hmto incorporate both the left and
right contexts, i.e., X>mandX<m, for predicting the masked token. Particularly, in the attention
mechanism of Transformers, hmis derived based on the similarities between the mask token xmask
and the context tokens X>mandX<m.
4
On the other hand, a decoder-only LLM models an input sequence autoregressively using the next-
token prediction task [31, 37]. The pre-training objective function is defined in Eq. 3:
logp(x1,···, xL|ˇX) =X
i=1,···,Llogp(xi|X<i)≈X
ilogp(xi|hi−1) (3)
For modeling the first token, the practical way is to add a Beginning-of-Sequence (BOS) token,
i.e.,ˇX=xbos⊕X. Similar to the mask token, the BOS token has no concrete meaning. The
representation hi−1encodes the information from already seen tokens and is derived based on the
relation between xi−1andX<i−1={x1,···, xi−2}.
Bottleneck Representations vs. Aggregated Representations. As LLMs output the token-level
vector representations, to obtain a representation encoding the sequence, the idea of bottleneck rep-
resentation is to push LLMs to compress the sequence information into a single vector representation
during fine-tuning [46, 38, 39].
In practice, this is achieved by appending an End-of-Sequence (EOS) xEOSto the input sequence,
e.g.,Xs,<t⊕xEOS. AsxEOSis constant across sequences, its vector representation hEOSdepends on
the real tokens of the sequence. During fine-tuning, hEOSis fed into the forecasting module as shown
in Eq. 4. The backpropagation process propels hEOSto summarize real tokens’s representations
through the forecasting module.
ˆrs,t+ℓ=f(hEOS) (4)
The bottleneck representation has different implications for encoder-only and decoder-only LLMs.
In encoder-only LLMs, the vector used for predicting is obtained based on the mask token and the
real context tokens during the pre-training, as explained in Eq. 2. As a result, appending an EOS
token (identical to the mask token used in pre-training) aligns the fine-tuning with the pre-training.
This consistency might facilitate the EOS token representation to summarize sequence-level features
effectively. In decoder-only LLMs, the vector representation of each token is conditioned on the
already-seen tokens; thus, the last token of a sequence naturally summarizes the whole sequence,
making an additional EOS token redundant.
In experiments, we observed that appending the EOS token is more helpful for encoder-only LLMs.
For a comparison on the same ground, we append EOS tokens for both encoder-only and decoder-
only LLMs and leave the study on the different impacts of appending tokens to future work.
Meanwhile, considering the recent works on the representation collapse issue of the last token in
certain conditions [4], we present a simple alternative to bottleneck representation, i.e., allowing the
forecasting module to aggregate the representations of all tokens. This can be done using various
methods like averaging, or sophisticated ones like attention mechanisms [24]. In this paper, we
choose the simple averaging method, since it introduces no additional parameters to train and enables
a clear comparison with the bottleneck representation.
ˆrs,t+ℓ=f
1
LX
lhl!
(5)
For encoder-only LLMs, the pre-training and fine-tuning discrepancy arises when using aggregated
representations, because each token’s representation is based on context and itself, instead of the
mask token in pre-training. For decoder-only LLMs, averaging all representations might lead to bias
towards the early tokens of the input sequence. This is because, in the autoregressive setting, the
early tokens are repeatedly incorporated into the representations of all subsequent ones.
Implementations. The text representation module and the forecasting module are respectively ini-
tialized by a pre-trained LLM and a dense layer. Then, the training process jointly fine-tunes the
LLM and learns the forecasting module to minimize the mean squared error (MSE) between the
forecasts and true values. We applied Low-Rank Adaptation (LoRA) to fine-tune LLMs [16]. Other
techniques including gradient checkpointing, mixed precision training, and DeepSpeed are used to
reduce GPU memory [34].
We experiment with one encoder-only LLM, i.e., DeBERTa [14], and two different decoder-only
LLMs, i.e., Mistral-7B and Llama3-8B base models [37, 19]. DeBERTa is a recent encoder-only
LLM that improves upon the BERT model with disentangled content and position embeddings.
5
Mistral-7B is a 7-billion-parameter decoder-only LLM that uses grouped query and sliding win-
dow attention to improve performance. Llama3-8B is an 8-billion-parameter decoder-only LLM
pre-trained on data mixed from different sources, e.g., multilingual, codes, etc., to improve the gen-
eralization ability.
4 Experiments
Data. We use company-level financial newsflow data from 2003 to 2019 provided by a financial data
vendor. Each piece of news has an attribute including the company identifier(s) the news is primarily
about. Meanwhile, we have two investment universe datasets of the North American (NA), European
(EU), and Emerging (EM) markets, which consist of dates, stock identifiers, and the true monthly
forward returns of corresponding stocks and dates. The training and validation data is from 2003 to
2014 for each universe, while the rest is for the out-of-sample testing data. Each instance is built
by linking an entry in the universe data to related news through the stock identifier and a look-back
time window (e.g., one week). Table 2 shows the data stats.
Setup. We train the model only once and then apply the model to obtain the return predictions in the
testing period. We conduct the model training using a batch size of 32, a learning rate of 1e-5, and
a warmup phase of 100steps followed by a linear decay. To fine-tune LLMs, we applied Low-Rank
Adaptation (LoRA) with rank 4to all linear layers. We employ a maximum context length of 4k for
all LLMs used in experiments. All models are trained for 10epochs on 2A100GPUs.
The long-only portfolio is built by taking the stocks with the return predictions falling in the top
(9th) decile of prediction rankings. The long-short portfolios take the stocks in the top ( 9th) and
bottom ( 0th) deciles. The stocks in all portfolios are equally weighted.
We perform backtesting to evaluate the portfolios in monthly rebalancing. It stimulates the trading
of monthly constructed portfolios and reports the cumulative return chart and performance statistics
like annualized returns and Sharpe ratios in the testing period. When backtesting the long-only and
long-short portfolios, besides comparing the portfolios built on return predictions by different LLMs,
we also compare them with the sentiment-based portfolio construction. Specifically, FinBERT is a
fine-tuned BERT (Bidirectional Encoder Representations from Transformers) for financial sentiment
analysis [3]. FinVader is a dictionary-based method with a financial sentiment lexicon [18, 22]. The
sentiment-based portfolios are built using the same method but with sentiment values as the ranking
criteria.
Metrics. As mentioned in the problem statement of Sec. 3.1, the downstream stock picking for
building portfolios is based on the deciles of forecasts; thus we report three decile-wise metrics to
align with downstream scenarios, i.e., decile RMSE, decile precision, and decile return. The decile
return is the actual return of stocks allocated to the decile based on predictions and is directly related
to the portfolio performance. Analyzing the decile return along with the decile RMSE and precision
provides insights into the relation between portfolio performance and prediction accuracy.
Specifically, at each date in the testing data, we group the predictions with the true returns into
deciles based on the ranking of predictions (i.e., the highest predictions are in the top 9th decile and
the lowest ones are in the bottom 0th decile). Then, with the true and predicted returns in each decile
across dates, we calculate the decile RMSE, decile precision, and decile return. The decile precision
is the percentage of the true returns whose decile based on the ranking of true values is equal to the
current decile. It is related to the portfolio performance, because, for instance, a high precision of
the top decile implies that a high proportion of stocks in this decile has a high true forward return,
thereby benefiting the portfolio including stocks from the top decile.
For portfolio backtesting, we report the cumulative return charts and performance statistics like
annualized returns and Sharpe ratios in the testing period.
Results. In the following, we present and discuss mainly the results of the NA universe. The results
of the EU and EM universe are in the Appendix section.
Bottleneck Representations vs. Aggregated Representations: In Fig. 3, we compare the bottleneck
and aggregated representations for the three LLMs in the North American universes through the
decile RMSE, precision, and returns. Each column of Fig. 3 corresponds to a LLM. Meanwhile,
6
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile051015202530Absolute ReturnLlama, Decile Absolute Return
Bottleneck
AggregatedFigure 3: Decile Performance of Bottleneck and Aggregated Representations in the North American
Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom
Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 1: Statistics of Portfolios in the North American Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.76 0.68 − −
Sentiment FinVader 12.26 0.72 2.92 0.39
Sentiment FinBert 20.64 1.22 8.81 0.92
DeBERTa Bottleneck 17.47 0.96 10.83 0.94
DeBERTa Aggregated 25.15 1.20 12.87 1.07
Mistral Bottleneck 21.27 1.15 15.08 1.49
Mistral Aggregated 25.38 1.12 18.30 1.26
Llama Bottleneck 27.00 1.32 20.46 1.49
Llama Aggregated 18.86 1.00 14.29 1.30
Fig. 4 shows the cumulative return charts of portfolios and Table 1 reports the detailed performance
stats of portfolios.
In the bottom row of Fig. 3, the returns from the 0th decile to the 9th decile generally present an
upward trend, implying that overall the return predictions are aligned with actual future performance.
Moreover, we are particularly interested in the top 9th and bottom 0th deciles as they are the main
constituents of portfolios. For the top 9th decile, the aggregated representation model generates a
higher return and benefits the long portfolio, except for Llama. For the EU and EM universe, as
presented in the Appendix section, the aggregated representation model consistently outperforms
the bottleneck one.
Interestingly, the higher returns do not necessarily imply low RMSE in the 9th decile. For instance,
in Fig. 3, the aggregated representation model has a higher decile return, but a higher RMSE, in the
9th decile corresponding to the long-only portfolio for DeBERTa and Mistral. An explanation is that
the9th decile is regarding predicting high-value returns and less accurate predictions of these returns
might have high RMSE. But, if the return prediction still falls into the 9th decile as the true return,
the corresponding decile return is retained. In this case, the decile precision is more indicative of the
decile return, for instance, in Fig. 3 the outperforming representations mostly have a higher precision
in the 9th decile.
As for the bottom 0th decile, a lower return is preferred as the short side of a long-short portfolio
benefits from stocks with underperforming forward returns. In Fig. 3, the aggregated representation
model falls short of lowering the 0th decile’s return for DeBERta and Mistral, however, Table 1
7
shows that the return and Sharpe ratios of long-short portfolios are mostly improved with aggregated
representations compared to the bottleneck representations.
Meanwhile, in the 0th decile, there are complexities in how prediction errors translate to actual
returns. For instance, for DeBERTa, the aggregated representation has higher RMSE and precision
in the bottom 0th decile, implying that some stocks with higher true returns are misallocated to the
0th decile by the prediction. As a result, the 0th decile return of the aggregated representation is
higher. However, when the aggregated representation of Llama has the same pattern in the bottom
decile, the return is as low as expected. This might be because the high precision offsets the impact
of misallocated high returns.
Fig. 4 visualizes the cumulative return of the portfolios using the bottleneck and aggregated repre-
sentation models. The performance of long-only and long-short portfolios correspond to the top and
bottom deciles in Fig. 3. The return curves of the aggregated representation model are notably higher
except for Llama. As shown in the Appendix, the aggregated representation constantly outperforms
the bottleneck representation for the EU and EM universes.
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20201.01.52.02.53.03.5Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 4: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Rep-
resentation Models in the North American Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
Encoder-only LLMs vs. Decoder-only LLMs: Fig. 5 shows the comparison of encoder-only and
decoder-only LLMs with the suitable representations for the NA universe, i.e., the aggregated rep-
resentation for DeBERTa and Mistral, and the bottleneck representation for Llama. For the EU and
EM universes in the Appendix, the aggregated representation is favored for all three LLMs.
The decile return in Fig. 5 exhibits that decoder-only Mistral and LLama generate high returns in
the top 9th decile and lower returns in the bottom 0th decile, thereby leading to the outperforming
long-only and long-short portfolios as shown in the cumulative return charts. In particular, the
performances of long-only portfolios are comparable among encoder and decoder LLMs, however,
in long-short portfolios, the short side drags down the performance of the long side, especially for
the encoder-only DeBERTa. This highlights the importance of effective stock selection on both sides
of the portfolio. Meanwhile, all the prediction-based portfolios yield higher returns than the universe
average.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 5: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the North American Universe (best viewed in color).
Prediction-based vs. Sentiment-based Portfolios: In this part, we compare the prediction-based port-
folios with conventional sentiment-based portfolios. Fig. 6 shows the decile returns and the return
8
charts of portfolios, and the performance statistics are in Table 1. The prediction-based portfo-
lios are from the forecasting model with the suited representations, as in the above comparison of
encoder-only and decoder-only LLMs.
In Table 1, the prediction-based long-only and long-short portfolios outperform the sentiment-based
portfolios both in returns and Sharp ratios. In Fig. 6, the return charts of prediction-based portfolios
are above the sentiment-based portfolios. In particular, for the long-short portfolios, as shown in the
return chart, the short side of the sentiment-based method negatively offsets the long side, leading
to underperformance compared with the universe. In contrast, the prediction-based long-short port-
folios have smoother return curves than the long-only portfolios, because the short side mitigates
the overall portfolio’s volatility. The outperformance of prediction-based portfolios suggests that
the return prediction models capture more relevant information from text representations for future
stock performance, leading to effective stock picking.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnNorth America, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.03.5Cumulative Return
North America, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 6: Comparison with Sentiment-based Portfolios in the North American Universe (best viewed
in color).
5 Conclusion
This paper focuses on return forecasting with financial newsflow for quantitative portfolio con-
struction. Unlike the conventional feature extraction-and-validation workflow, this paper explores
fine-tuning LLMs to directly model the relationship between text representations and stock forward
return. Considering that different LLMs generate token-level representations in distinct ways, we
compare the design choices on two aspects: the encoder-only versus decoder-only LLMs, and the
bottleneck versus aggregated representations.
Our experiments are conducted on real financial news, various investment universes, and differ-
ent portfolios. The results reveal the key findings: (1) aggregated representations from LLMs’
token-level embeddings generally produce the return predictions that enhance the performance of
long-only and long-short portfolios; (2) in the relatively large investment universe, the decoder
LLMs-based prediction model leads to stronger portfolios, whereas in the small universes, there
are no consistent winners. Among the three LLMs studied (DeBERTa, Mistral, Llama), Mistral
performs more robustly across different universes; (3) return predictions derived from LLMs’ text
representations are a strong signal for portfolio construction, outperforming conventional sentiment
scores.
Several open questions remain for future research. For instance, it is unclear whether the under-
performance of encoder-only DeBERTa in the large investment universe is due to the model size or
other factors, and why DeBERTa has varying performance in different small universes. Evaluating
recently proposed large encoder-only LLMs [39, 5] would be an interesting follow-up. Additionally,
within the decoder-only LLM family, compared with Mistral’s robust performance across investment
universes, the reasons behind Llama’s performance variation need further exploration.
References
[1] David E Allen, Michael McAleer, and Abhay K Singh. Daily market news sentiment and stock
prices. Applied Economics , 51(30):3212–3235, 2019.
[2] Andrew Ang. Asset management: A systematic approach to factor investing . Oxford University
Press, 2014.
[3] Dogu Araci. Finbert: Financial sentiment analysis with pre-trained language models. arXiv
preprint arXiv:1908.10063 , 2019.
9
[4] Federico Barbero, Andrea Banino, Steven Kapturowski, Dharshan Kumaran, Jo ˜ao GM Ara ´ujo,
Alex Vitvitskyi, Razvan Pascanu, and Petar Veli ˇckovi ´c. Transformers need glasses! informa-
tion over-squashing in language tasks. arXiv preprint arXiv:2406.04267 , 2024.
[5] Parishad BehnamGhader, Vaibhav Adlakha, Marius Mosbach, Dzmitry Bahdanau, Nicolas
Chapados, and Siva Reddy. Llm2vec: Large language models are secretly powerful text en-
coders. arXiv preprint arXiv:2404.05961 , 2024.
[6] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhari-
wal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language mod-
els are few-shot learners. Advances in neural information processing systems , 33:1877–1901,
2020.
[7] Deli Chen, Keiko Harimoto, Ruihan Bao, Qi Su, Xu Sun, et al. Group, extract and aggregate:
Summarizing a large amount of finance news for forex movement prediction. arXiv preprint
arXiv:1910.05032 , 2019.
[8] Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Yunxuan
Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, et al. Scaling instruction-finetuned
language models. Journal of Machine Learning Research , 25(70):1–53, 2024.
[9] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of
deep bidirectional transformers for language understanding. In Proceedings of the 2019 Con-
ference of the North American Chapter of the Association for Computational Linguistics: Hu-
man Language Technologies, Volume 1 (Long and Short Papers) , pages 4171–4186, 2019.
[10] Ning Ding, Yujia Qin, Guang Yang, Fuchao Wei, Zonghan Yang, Yusheng Su, Shengding Hu,
Yulin Chen, Chi-Min Chan, Weize Chen, et al. Parameter-efficient fine-tuning of large-scale
pre-trained language models. Nature Machine Intelligence , 5(3):220–235, 2023.
[11] Eugene F Fama and Kenneth R French. Multifactor explanations of asset pricing anomalies.
The journal of finance , 51(1):55–84, 1996.
[12] Beliz Gunel, Jingfei Du, Alexis Conneau, and Ves Stoyanov. Supervised contrastive learning
for pre-trained language model fine-tuning. arXiv preprint arXiv:2011.01403 , 2020.
[13] Tian Guo, Nicolas Jamet, Valentin Betrix, Louis-Alexandre Piquet, and Emmanuel Haupt-
mann. Esg2risk: A deep learning framework from esg news to stock volatility prediction.
arXiv preprint arXiv:2005.02527 , 2020.
[14] Pengcheng He, Jianfeng Gao, and Weizhu Chen. Debertav3: Improving deberta using
electra-style pre-training with gradient-disentangled embedding sharing. arXiv preprint
arXiv:2111.09543 , 2021.
[15] Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. Deberta: Decoding-enhanced
bert with disentangled attention. arXiv preprint arXiv:2006.03654 , 2020.
[16] Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang,
Lu Wang, and Weizhu Chen. Lora: Low-rank adaptation of large language models. arXiv
preprint arXiv:2106.09685 , 2021.
[17] Ziniu Hu, Weiqing Liu, Jiang Bian, Xuanzhe Liu, and Tie-Yan Liu. Listening to chaotic
whispers: A deep learning framework for news-oriented stock trend prediction. In Proceedings
of the eleventh ACM international conference on web search and data mining , pages 261–269,
2018.
[18] Clayton Hutto and Eric Gilbert. Vader: A parsimonious rule-based model for sentiment anal-
ysis of social media text. In Proceedings of the international AAAI conference on web and
social media , volume 8, pages 216–225, 2014.
[19] Albert Q Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh
Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile
Saulnier, et al. Mistral 7b. arXiv preprint arXiv:2310.06825 , 2023.
[20] Alex Kim, Maximilian Muhn, and Valeri V Nikolaev. Financial statement analysis with large
language models. Chicago Booth Research Paper Forthcoming, Fama-Miller Working Paper ,
2024.
[21] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa.
Large language models are zero-shot reasoners. Advances in neural information processing
systems , 35:22199–22213, 2022.
10
[22] Petr Korab. Finvader: Financial sentiment analysis, 2023.
[23] Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu
Soricut. Albert: A lite bert for self-supervised learning of language representations. In Inter-
national Conference on Learning Representations , 2019.
[24] Chankyu Lee, Rajarshi Roy, Mengyao Xu, Jonathan Raiman, Mohammad Shoeybi, Bryan
Catanzaro, and Wei Ping. Nv-embed: Improved techniques for training llms as generalist
embedding models. arXiv preprint arXiv:2405.17428 , 2024.
[25] Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed,
Omer Levy, Ves Stoyanov, and Luke Zettlemoyer. Bart: Denoising sequence-to-sequence
pre-training for natural language generation, translation, and comprehension. arXiv preprint
arXiv:1910.13461 , 2019.
[26] Yinheng Li, Shaofei Wang, Han Ding, and Hang Chen. Large language models in finance: A
survey. In Proceedings of the fourth ACM international conference on AI in finance , pages
374–382, 2023.
[27] Qikai Liu, Xiang Cheng, Sen Su, and Shuguang Zhu. Hierarchical complementary attention
network for predicting stock price movements with news. In Proceedings of the 27th ACM In-
ternational Conference on Information and Knowledge Management , pages 1603–1606, 2018.
[28] Shih-Yang Liu, Chien-Yi Wang, Hongxu Yin, Pavlo Molchanov, Yu-Chiang Frank Wang,
Kwang-Ting Cheng, and Min-Hung Chen. Dora: Weight-decomposed low-rank adaptation.
arXiv preprint arXiv:2402.09353 , 2024.
[29] Zhuang Liu, Degen Huang, Kaiyu Huang, Zhuang Li, and Jun Zhao. Finbert: A pre-trained
financial language representation model for financial text mining. In Proceedings of the twenty-
ninth international conference on international joint conferences on artificial intelligence ,
pages 4513–4519, 2021.
[30] Yu Qin and Yi Yang. What you say and how you say it matters: Predicting financial risk
using verbal and vocal cues. In 57th Annual Meeting of the Association for Computational
Linguistics (ACL 2019) , page 390, 2019.
[31] Alec Radford, Karthik Narasimhan, Tim Salimans, and Ilya Sutskever. Improving language
understanding by generative pre-training. 2018.
[32] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al.
Language models are unsupervised multitask learners. OpenAI blog , 1(8):9, 2019.
[33] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena,
Yanqi Zhou, Wei Li, and Peter J Liu. Exploring the limits of transfer learning with a unified
text-to-text transformer. Journal of machine learning research , 21(140):1–67, 2020.
[34] Jeff Rasley, Samyam Rajbhandari, Olatunji Ruwase, and Yuxiong He. Deepspeed: System
optimizations enable training deep learning models with over 100 billion parameters. In Pro-
ceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data
Mining , pages 3505–3506, 2020.
[35] Ramit Sawhney, Shivam Agarwal, Arnav Wadhwa, and Rajiv Shah. Deep attentive learning for
stock movement prediction from social media text and company correlations. In Proceedings
of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP) ,
pages 8415–8426, 2020.
[36] Adam Hale Shapiro, Moritz Sudhof, and Daniel J Wilson. Measuring news sentiment. Journal
of econometrics , 228(2):221–243, 2022.
[37] Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei,
Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. Llama 2: Open
foundation and fine-tuned chat models. arXiv preprint arXiv:2307.09288 , 2023.
[38] Liang Wang, Nan Yang, Xiaolong Huang, Binxing Jiao, Linjun Yang, Daxin Jiang, Rangan
Majumder, and Furu Wei. Simlm: Pre-training with representation bottleneck for dense pas-
sage retrieval. In The 61st Annual Meeting Of The Association For Computational Linguistics ,
2023.
[39] Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang, Rangan Majumder, and Furu Wei.
Improving text embeddings with large language models. arXiv preprint arXiv:2401.00368 ,
2023.
11
[40] Meiyun Wang, Kiyoshi Izumi, and Hiroki Sakaji. Llmfactor: Extracting profitable factors
through prompts for explainable stock movement prediction. arXiv preprint arXiv:2406.10811 ,
2024.
[41] Yaowei Wang, Qing Li, Zhexue Huang, and Junjie Li. Ean: Event attention network for
stock price trend prediction based on sentimental embedding. In Proceedings of the 10th ACM
Conference on Web Science , pages 311–320, 2019.
[42] Jason Wei, Maarten Bosma, Vincent Y Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan
Du, Andrew M Dai, and Quoc V Le. Finetuned language models are zero-shot learners. arXiv
preprint arXiv:2109.01652 , 2021.
[43] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le,
Denny Zhou, et al. Chain-of-thought prompting elicits reasoning in large language models.
Advances in neural information processing systems , 35:24824–24837, 2022.
[44] Bin Weng, Lin Lu, Xing Wang, Fadel M Megahed, and Waldyn Martinez. Predicting short-
term stock prices using ensemble methods and online data sources. Expert Systems with Ap-
plications , 112:258–273, 2018.
[45] Yumo Xu and Shay B Cohen. Stock movement prediction from tweets and historical prices.
InProceedings of the 56th Annual Meeting of the Association for Computational Linguistics
(Volume 1: Long Papers) , pages 1970–1979, 2018.
[46] Linyi Yang, Ruihai Dong, Tin Lok James Ng, and Yang Xu. Leveraging bert to improve the
fears index for stock forecasting. In Proceedings of the First Workshop on Financial Technol-
ogy and Natural Language Processing , pages 54–60, 2019.
[47] Wayne Xin Zhao, Kun Zhou, Junyi Li, Tianyi Tang, Xiaolei Wang, Yupeng Hou, Yingqian
Min, Beichen Zhang, Junjie Zhang, Zican Dong, et al. A survey of large language models.
arXiv preprint arXiv:2303.18223 , 2023.
12
A Appendix
Table 2: Statistics of Datasets.
Universe # of Stocks Average # of News per Instance # of Training Instances # of Validating Instances # of Testing Instances
North America 630 2.5 366011 10167 241367
Europe 350 1.9 100403 10041 121705
Emerging Markets 370 2.6 71610 10231 183608
A.1 Results of the European Universe
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnLlama, Decile Absolute Return
Bottleneck
Aggregated
Figure 7: Decile Performance of Bottleneck and Aggregated Representations in the European Uni-
verse (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision. Bottom Row:
Decile Return. The up (or down) arrow indicates the higher (or lower) values are desirable.
Table 3: Statistics of Portfolios in the European Universe. The Universe Equally-Weighted repre-
sents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 9.75 0.74 − −
Sentiment FinVader 10.25 0.70 3.40 0.45
Sentiment FinBert 8.17 0.57 -0.36 0.00
DeBERTa Bottleneck 11.04 0.81 2.11 0.31
DeBERTa Aggregated 11.11 0.81 3.84 0.52
Mistral Bottleneck 6.40 0.48 1.94 0.26
Mistral Aggregated 15.12 1.02 9.07 1.04
Llama Bottleneck 8.20 0.62 1.25 0.17
Llama Aggregated 12.76 0.90 11.47 1.27
13
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-WeightedFigure 8: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Repre-
sentation Models in the European Universe (best viewed in color). Top Row: Long-only Portfolios.
Bottom Row: Long-short Portfolios.
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEurope, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Figure 9: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations in
the European Universe (best viewed in color).
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEurope, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Europe, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 10: Comparison with Sentiment-based Portfolios in the European Universe (best viewed in
color).
14
A.2 Results of the Emerging Markets Universe
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEDeBERT a, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSEMistral, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.02.55.07.510.012.515.017.520.0RMSELlama, Decile RMSE ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)DeBERT a, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Mistral, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 90.0000.0250.0500.0750.1000.1250.1500.1750.200Precision (%)Llama, Decile Precision ( )
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnDeBERT a, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnMistral, Decile Absolute Return
Bottleneck
Aggregated
0 1 2 3 4 5 6 7 8 9
Decile0510152025Absolute ReturnLlama, Decile Absolute Return
Bottleneck
Aggregated
Figure 11: Decile Performance of Bottleneck and Aggregated Representations in the Emerging
Markets Universe (best viewed in color). Top Row: Decile RMSE. Middle Row: Decile Precision.
Bottom Row: Decile Return. The up (or down) arrow indicates the higher (or lower) values are
desirable.
Table 4: Statistics of Portfolios in the Emerging Markets Universe. The Universe Equally-Weighted
represents the universe performance reported under the Long-only Portfolio column.
Long-only Portfolio Long-short Portfolio
Ann. Return % ( ↑)Sharpe Ratio ( ↑)Ann. Return % ( ↑)Sharpe Ratio ( ↑)
Universe Equally-Weighted 3.91 0.32 − −
Sentiment FinVader 6.18 0.43 -0.08 0.04
Sentiment FinBert 9.76 0.70 1.69 0.21
DeBERTa Bottleneck 7.32 0.50 -5.00 -0.36
DeBERTa Aggregated 9.88 0.64 10.96 0.97
Mistral Bottleneck 10.12 0.63 4.94 0.47
Mistral Aggregated 10.11 0.64 9.16 0.68
Llama Bottleneck 4.94 0.36 -3.99 -0.28
Llama Aggregated 8.82 0.58 1.83 0.19
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Only Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Only Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 20200.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Only Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
DeBERT a, Long-Short Portfolio ( )
DeBERT a_Bottleneck
DeBERT a_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Mistral, Long-Short Portfolio ( )
Mistral_Bottleneck
Mistral_Aggregated
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time0.81.01.21.41.61.82.02.22.4Cumulative Return
Llama, Long-Short Portfolio ( )
Llama_Bottleneck
Llama_Aggregated
Universe Equally-Weighted
Figure 12: Cumulative Return Charts of the Portfolios based on Bottleneck and Aggregated Repre-
sentation Models in the Emerging Markets Universe (best viewed in color). Top Row: Long-only
Portfolios. Bottom Row: Long-short Portfolios.
15
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEmerging Markets, Decile Return
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-WeightedFigure 13: Comparison of Encoder-only and Decoder-only LLMs with the Suited Representations
in the Emerging Markets Universe (best viewed in color).
0 1 2 3 4 5 6 7 8 9
Decile051015202530Average Absolute ReturnEmerging Markets, Decile Return
FinVader
FinBert
DeBERT a
Mistral
Llama
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Only Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
2015 2016 2017 2018 2019 2020
Time1.01.52.02.53.0Cumulative Return
Emerging Markets, Long-Short Portfolio
DeBERT a
Mistral
Llama
Universe Equally-Weighted
Sentiment_FinVader
Sentiment_FinBert
Figure 14: Comparison with Sentiment-based Portfolios in the Emerging Markets Universe (best
viewed in color).
16 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18074v1 | http://arxiv.org/pdf/2407.18074v1 | Principal-Agent Reinforcement Learning | Dima Ivanov, Paul Dütting, Inbal Talgam-Cohen, Tonghan Wang, David C. Parkes | 2024-07-25 | Abstract
Contracts are the economic framework which allows a principal to delegate a task
to an agent—despite misaligned interests, and even without directly observing the
agent’s actions. In many modern reinforcement learning settings, self-interested
agents learn to perform a multi-stage task delegated to them by a principal. We
explore the significant potential of utilizing contracts to incentivize the agents.
We model the delegated task as an MDP, and study a stochastic game between
the principal and agent where the principal learns what contracts to use, and the
agent learns an MDP policy in response. We present a learning-based algorithm
for optimizing the principal’s contracts, which provably converges to the subgame-
perfect equilibrium of the principal-agent game. A deep RL implementation allows
us to apply our method to very large MDPs with unknown transition dynamics. We
extend our approach to multiple agents, and demonstrate its relevance to resolving
a canonical sequential social dilemma with minimal intervention to agent rewards.
1 | Introduction
A somewhat implicit yet fundamental assumption in both the single-agent [ 75] and multi-agent [ 47]
RL literature is that the same entity that learns and executes the action policy in an MDP (Markov
Decision Process) is the entity that fully enjoys the benefits from its execution. However, in many
real-life scenarios, this basic assumption is violated. For example, drivers exploring new routes
benefit their navigation app [ 3]; users consuming and rating online content benefit the website [ 84];
and students taking an online course fulfill the goals of the course instructor [ 89,40]. In all of these
applications, the principal benefiting from the agent’s actions cannot directly control them, but is able
to shape the incentives by designing e.g. a grading scheme or a badge system.
The theoretical framework that applies to such scenarios is known in economics as principal-agent
theory (e.g., [ 32,26,66,71]). In the aforementioned applications, it distinguishes between the agents,
who directly interact with the MDP while incurring costs for their actions, and the principal, who
receives rewards from the interaction. One of the most important tools in economics for shaping
incentives is contracts . A contract defines payments from the principal to the agent (monetary or
other) based on the observable outcomes (i.e., rewards) of the actions chosen by the agent(s). The
mapping from actions to rewards is often (but not necessarily) modeled as being stochastic, in which
case it may be impossible to infer the chosen actions from the observed outcomes. A standard
assumption in economics, known as limited liability , is that the payments must be non-negative. The
agent(s), in turn, choose an action policy that maximizes their utility, given by payments minus costs.
We are thus looking at a stochastic game, in which principal and agent(s) best respond to each other.
The celebrated theory of contracts was awarded the Nobel Prize in Economics in 2016. While it has
seen a surge of interest from the computer science and learning communities recently (e.g., [ 30,19,
∗Israel Institute of Technology, Haifa, Israel. Email: [email protected]
†Google, Zurich, Switzerland. Email: [email protected]
‡Israel Institute of Technology, Haifa, Israel. Email: [email protected]
§Harvard University, Cambridge, USA. Email: [email protected]
¶Harvard University, Cambridge, USA. Email: [email protected]
Preprint. Under review.arXiv:2407.18074v1 [cs.GT] 25 Jul 2024
20,91,79]) it has received relatively little attention from the RL perspective. In this work we bridge
this gap by providing theory-inspired, practical algorithms for solving RL problems with misaligned
incentives (with standard RL pipelines, achieving scale with deep RL).
Why is principal-agent RL challenging? Principal-agent RL is challenging for several reasons:
(1)Complexity of the setting. MDPs are inherently combinatorial due to their temporal nature, even
more so when multiple parties are involved. Contracts are continuous, making the set of all possible
contracts (even for single-period problems) infinite. (2) Misaligned preferences and strategic behavior.
Principal and agent have misaligned preferences, each learning to maximize their own utility in the
presence of the other. Private information (such as hidden actions) further complicates the problem.
(3)Approximation and learning. In practice, learning inherently comes with approximation errors.
Even slight errors may have devastating effects due to discontinuity of the principal’s utility function.
1.1 Our Contribution
We formulate and study a principal-agent game in which the agent learns a policy for an MDP on
behalf of the principal, and the principal learns to guide the agent via a series of contracts. After
defining this setup formally (Section 2), we first discuss the purely economic setting (Section 3) with
full access to the MDP model and no learning required. We focus on the standard solution concept
for extensive-form games, namely subgame-perfect equilibrium (SPE)—see Section 3.1.
A key observation is that fixing one player’s policy defines a standard MDP for another player. Based
on this, we formulate a simple meta-algorithm (Algorithm 1) that finds SPE in a finite-horizon game
in at most T+ 1iterations, where Tis the horizon of the MDP (Theorem 3.3). The meta-algorithm
iteratively optimizes the principal’s and agent’s policies in their respective MDPs, but does not specify
the optimization steps. We also give the meta-algorithm a clean mathematical interpretation as an
iterative application of a contraction operator to the principal’s Q-function (Theorem 3.4).
Next, we turn to the standard model-free RL setting where the MDP is a black box, and the policies
are learned by sampling stochastic transitions and rewards through interacting with the MDP. We
instantiate the meta-algorithm by solving both principal’s and agent’s MDPs with (deep) Q-learning
and apply it in a two-phase setup. First, we train the policies assuming the principal has access
to the agent’s optimization problem (of maximizing its Q-function estimate given a contract in a
state). Such an access is a standard assumption in economics, and does not trivialize the problem.
Then, we relax the assumption and validate the learned principal’s policy against black-box agents
trained from scratch, mimicking its execution in the real world. Alternatively, it is possible to lift
this assumption completely by applying any learning algorithm for the one-shot contracting problem,
such as the deep-learning approach of Wang et al. [79]. Through this setup, we verify empirically
that our method approximates SPE well despite early termination and approximation errors.
In Section 5, we extend our approach to multi-agent RL and sequential social dilemmas (SSDs) [42],
a generalization of prisoner’s-dilemma-style single-shot games to multiple time periods and complex
state spaces. A common approach to SSDs is through shaping the agents’ rewards, with a focus on
cooperation and social welfare maximization. However, the extent to which the rewards are modified
is typically ignored, and despite the vast literature on the topic, there is no general procedure for
finding a minimal intervention into agents’ rewards that drives cooperation. We address this gap using
our developed principal-agent machinery. We empirically validate our approach on a prominent SSD
known as the Coin Game [23]. We compare to an alternative, simpler approach with hand-coded
payment schemes inspired by a reward-redistribution method of Christoffersen et al. [8], and observe
that with the same amount of subsidy, this less-targeted intervention achieves a significantly lower
welfare level.
1.2 | Section not found | Related Work
Our work fits into the wider literature on automated mechanism design [ 10], in particular approaches
based on deep learning [ 18,79] also known as differentiable economics [ 21]. Most closely related
from this line of work, Wang et al. [79] consider stateless one-shot contracting problems and provide
a network architecture for capturing the discontinuities in the principal’s utility function. We differ
from this work in our focus on sequential contracting problems and the entailing unique challenges.
2
There is a number of algorithmic works that focus on repeated principal-agent interactions on MDPs,
including work on environment design andpolicy teaching [87,89,85,3]. Our approach differs from
these earlier works in several ways, including that we actively search for the best (unconstrained)
equilibrium in the game between the principal and the agent through reinforcement learning. A
closely related line of work, including [ 24], is concerned with learning Stackelberg equilibria in
general leader-follower games, including games on MDPs. Our work differs in its focus on SPE,
which is the more standard equilibrium concept in dynamic contract design problems. Several
works have studied repeated contract design problems from a no-regret online-learning perspective
[30,91,29,70]. However, these works are typically limited to stateless and/or non-sequential
interactions. A prominent exception is a contemporaneous study by Wu et al. [82] that introduces a
model of principal-agent MDPs nearly identical to ours, barring an important notational distinction
of encoding outcomes as next states. However, their and our studies pursue orthogonal algorithmic
developments: whereas they treat contract policies as arms of a bandit and minimize regret, we rely
on deep RL to scale to large MDPs and multiple agents.
Starting with the work of Leibo et al. [42], there is a huge literature on SSDs. Most closely related in
this direction is the work by Christoffersen et al. [8]on multi-agent RL and applications to SSDs.
This work pursues an approach in which one of the agents (rather than the principal) proposes a
contract (an outcome-contingent, zero-sum reward redistribution scheme), and the other agents can
either accept or veto. They consider several SSDs and show how hand-crafted contract spaces strike a
balance between generality and tractability, and can be an effective tool in mitigating social dilemmas.
An important distinction of our work is that we distinguish between principal and agent(s), and insist
on the standard limited liability requirement from economics. Furthermore, in our approach the
principal learns the conditions for payments, allowing it to utilize contracts in their full generality.
Also, our method has an interpretation as learning k-implementation [52].
We provide additional details on the related literature in Appendix A.
2 Problem Setup
In this section, we first introduce the classic (limited liability) contract design model of Holmström
[32] and Grossman and Hart [26], and then propose its extension to MDPs. We defer further extension
to multi-agent MDPs to Section 5.1.
2.1 Static Hidden-Action Principal-Agent Problem
In a principal-agent problem, the principal wants the agent to perform a task. The agent has a choice
between several actions a∈Awith different costs c(a), interpreted as effort levels. Each action
stochastically maps to outcomes o∈Oaccording to a distribution O(a), with higher effort levels
more likely to result in good outcomes, as measured by the associated principal’s reward rp(o). By
default, a rational agent would choose the cost-minimizing action. To incentivize the agent to invest
an effort, the principal may offer a contract bprior to the action choice. Crucially, the principal may
be unable (or unwilling) to directly monitor the agent’s action, so the contractual payments b(o)≥0
are defined per outcome o∈O. The principal seeks an optimal contract: a payment scheme that
maximizes the principal’s utility, max bEo∼O(a)[rp(o)−b(o)], given that the agent best-responds
withmax aEo∼O(a)[b(o)]−c(a).
If costs and outcome distributions are known, the optimal contract can be precisely found using
Linear Programming (LP): for each action a∈A, find the contract that implements it (makes the
agent at least indifferent between this and other actions) through a minimal expected payment, and
then choose the best action to implement. Otherwise or if the LPs are infeasible, an approximation
can be obtained by training a neural network on a sample of past interactions with the agent [79].
2.2 Hidden-Action Principal-Agent MDPs
In order to extend contract design to MDPs, we assume a principal-agent problem in each state of
the MDP, and let the outcomes additionally define its (stochastic) transitioning to the next state. A
hidden-action principal-agent MDP is a tuple M= (S, s 0, A, B, O, O,R,Rp,T, γ). As usual in
MDPs, Sis a set of states, s0∈Sis the initial state, and Ais a set of nagent’s actions a∈A.
Additionally, Ois a set of moutcomes o∈O,B⊂Rm
≥0is a set of principal’s actions (contracts)
3
Figure 1: Example of a principal-agent MDP with three states S={s0, sL, sR}.In each state, the
agent can take one of two actions: noisy-left ( aL), which is costly and leads to outcomes LandRwith
probabilities 0.9and0.1, and noisy-right (aR), which is free and has the roles of LandRreversed.
The principal’s rewards in any state s∈Sfor outcomes L, R arerp(s, L) =14
9, rp(s, R) = 0 ,
resp., while those of the agent for the actions are r(s, aL) =−4
5, r(s, aR) = 0 . For analysis, see
Appendix B.1.
b∈B, andb(o)is the o-th coordinate of a contract (payment). In each state, the outcome is sampled
based on the agent’s action from a distribution O(s, a), where O:S×A→∆(O)is the outcome
function. Then, the agent’s reward is determined by the reward function R(s, a, b, o ) =r(s, a)+b(o)
for some r(s, a). Likewise, the principal’s reward is determined by Rp(s, b, o ) =rp(s, o)−b(o)for
some rp(s, o); note that the agent’s action is private and thus Rpdoes not explicitly depend on it.
Based on the outcome, the MDP transitions to the next state s′∼ T(s, o), where T:S×O→∆(S)
is the transition function. Finally, γ∈[0,1]is the discount factor. For an example of a principal-agent
MDP, see Figure 1. In the main text, we focus on MDPs with a finite time horizon T. We assume
w.l.o.g. that each state is uniquely associated with a time step (see Appendix B.4).
We analyze the principal-agent MDP as a stochastic game G(can be seen as extensive-form when
the horizon is finite), where two players maximize their long-term payoffs. The game progresses
as follows. At each timestep t, the principal observes the state stof the MDP and constructs a
contract bt∈Baccording to its policy ρ:S→∆(B). Then, the agent observes the pair (st, bt)
and chooses an action at∈Aaccording to its policy π:S×B→∆(A). After this, the MDP
transitions, and the interaction repeats. Both players maximize their value functions: the principal’s
value function, Vρ(π), of a policy ρgiven the agent’s policy πis defined in a state sbyVρ(s|π) =
E[P
tγtRp(st, bt, ot)|s0=s]; likewise, the agent’s value function Vπ(ρ)is defined in a state sand
given a contract bbyVπ(s, b|ρ) =E[P
tγtR(st, at, bt, ot)|s0=s, b0=b]. Players’ utilities in
the game are their values in the initial state. Additionally, define the players’ Q-value functions Qρ(π)
andQπ(ρ)byQρ(s, b|π) =Vρ(s|b0=b, π)andQπ((s, b), a|ρ) =Vπ(s, b|a0=a, ρ).
A special case of the principal-agent MDP trivializes hidden actions by making the outcome function
deterministic and bijective; the resulting observed-action model is similar to Ben-Porat et al. [3]. For
an explicit comparison of the two models with each other and with standard MDPs, see Appendix B.
3 Purely Economic Setting
In this section, we define our solution concept for principal-agent stochastic games (Section 3.1) and
introduce a meta-algorithm that finds this solution (Section 3.2). We assume full access to the MDP
model (including transition and reward functions) and address the learning setting in the next section.
3.1 Subgame-Perfect Equilibrium (SPE)
In what follows let Gbe a principal-agent stochastic game. Let a subgame ofGin state s∈Sbe a
gameG′defined by replacing s0withs, and Swith a subset of states that can be reached from s.
Observation 3.1. Fixing one player’s policy in Gdefines a (standard) MDP for another player. In
particular, a principal’s policy defines the agent’s MDP by modifying the reward function through
contracts; likewise, an agent’s policy defines the principal’s MDP by modifying the transition and
4
Algorithm 1 Meta-algorithm for finding SPE
1:Initialize the principal’s policy ρarbitrarily ▷e.g.,∀s∈S:ρ(s) =0
2:while ρnot converged do ▷Inner-outer optimization loop
3: Solve the agent’s MDP: find π:=π∗(ρ) ▷Inner optimization level
4: Solve the principal’s MDP: find ρ:=ρ∗(π) ▷Outer optimization level
5:return (ρ, π)
reward functions through the agent’s responses to contracts. For exact formulations of these MDPs,
see Appendix B.2. The optimal policies in both MDPs can be assumed w.l.o.g. to be deterministic (in
single-agent setting), and can be found with any suitable dynamic programming or RL algorithm [ 75].
Agent’s perspective. In the agent’s MDP defined by ρ, refer to the optimal policy as best-responding
toρ(where ties are broken in favor of the principal, as is standard in contract design). Define
a function π∗that maps a principal’s policy ρto the best-responding policy π∗(ρ). Denote the
action prescribed by π∗(ρ)in state sgiven contract bbyπ∗(s, b|ρ)≡π∗(ρ)(s, b). Note that the
best-responding policy is defined in sfor any b∈Band is not limited to the principal’s action ρ(s).
Principal’s perspective. Similarly, in the principal’s MDP defined by π, refer to the optimal policy as
subgame-perfect against π. Define a function ρ∗that maps an agent’s policy πto the subgame-perfect
policy ρ∗(π). Denote the contract prescribed by ρ∗(π)in state sbyρ∗(s|π)≡ρ∗(π)(s). In all
states, this policy satisfies: ρ∗(s|π)∈arg maxbQ∗(s, b|π), where Q∗(s, b|π)≡Qρ∗(π)(s, b|π)
– that is, in each subgame, the principal takes the optimal action.
Definition 3.2. Asubgame-perfect equilibrium (SPE) ofGis a pair of policies (ρ, π), where the
principal’s policy ρ≡ρ∗(π)is subgame-perfect against an agent that best-responds with π≡π∗(ρ).
SPE is a standard solution concept for extensive-form games [ 55]. It always exists and is essentially
unique (see Lemma B.11 for completeness). Compared to non-subgame-perfect solutions like the
well–studied Stackelberg equilibrium, SPE can lose utility for the principal. However, it disallows
threats that are non-credible , i.e., require playing a suboptimal contract in a subgame. We demonstrate
the difference on our example in Appendix B.1. Furthermore, Gerstgrasser and Parkes [24] show
that learning a Stackelberg equilibrium necessitates the principal to go through long episodes with
observations of the learning dynamics of the followers, and with only sparse rewards (see also Brero
et al. [5]). SPE, in contrast, naturally fits RL, as both players’ policies solve the respective MDPs.
3.2 Meta-Algorithm for Finding SPE
Algorithm 1 presents a general pipeline for finding SPE in a principal-agent stochastic game. It can be
seen as an inner-outer (bilevel) optimization loop, with agent and principal optimization respectively
constituting the inner and outer levels. We refer to this as a meta-algorithm, as we do not yet specify
how to perform the optimization (in Lines 3 and 4). Superficially, this approach resembles the use of
bilevel optimization for learning optimal reward shaping [ 72,33,7,78,6,49]. The crucial difference
of that setting is that the two levels optimize the same downstream task rather than distinct and
possibly conflicting | Section not found | Section not found | Section not found | objectives of principal and agent.
It is well-known that SPE of an extensive-form game can be found with backward induction (e.g., see
Section 5.6 of Osborne [55]). Theorem 3.3 states that the proposed meta-algorithm also finds SPE.
The proof, provided in Appendix B.4, essentially shows that it performs backward induction implicitly.
That is, each iteration of the meta-algorithm, the players’ policies reach SPE in an expanding set of
subgames, starting from terminal states and ending with the initial state. The proof does not rely on
the specifics of our model and applies to any game where players move sequentially, and the agent
observes and can respond to anyprincipal’s action in a state.
Theorem 3.3. Given a principal-agent stochastic game Gwith a finite horizon T, the meta-algorithm
finds SPE in at most T+ 1iterations.
The meta-algorithm has several unique advantages. First, as we discuss in Section 4, both inner and
outer optimization tasks can be instantiated with Q-learning. This removes the need to know the
model of the MDP and allows handling of large-scale MDPs by utilizing deep learning. Second, it
can also be seen as iteratively applying a contraction operator, which we formulate as a theorem:
5
Table 1: Correctness of the meta-algorithm in different scenarios
finite horizon T infinite horizon
hidden action finds SPE in T+ 1iterations (Theorem 3.3) may diverge (Appendix B.6)
observed action finds SPE that is also Stackelberg in 1 iteration (Appendix B.7)
Theorem 3.4. Given a principal-agent finite-horizon stochastic game G, each iteration of the meta-
algorithm applies to the principal’s Q-function an operator that is a contraction in the sup-norm.
The proof is provided in Appendix B.5. This property implies that each iteration of the meta-algorithm
monotonically improves the principal’s policy in terms of its Q-function converging. This has a
practical advantage: if meta-algorithm is terminated early, the policies still partially converge to SPE.
As an independent observation, Theorem 3.3 complements the theoretical results of Gerstgrasser
and Parkes [24]. Specifically, their Theorem 2 presents an example where RL fails to converge to a
Stackelberg equilibrium if the agent ‘immediately’ best responds. This procedure is our Algorithm 1,
with agent optimization solved by an oracle and principal optimization performed with RL. Our
Theorem 3.3 complements their negative result by showing that such a procedure converges to SPE.
Finally, while we focus on finite-horizon hidden-action MDPs in the main text, we also analyze the
other scenarios in the Appendix. Our findings are summarized in Table 1.
4 Learning Setting
In this section, we develop an RL approach to principal-agent MDPs by solving both inner and
outer optimization tasks of the meta-algorithm with Q-learning. These tasks correspond to finding
optimal policies in the respective agent’s and principal’s MDPs defined in Observation 3.1. We
operate in a standard model-free RL setting, where learning is performed through interactions with a
black-box MDP. For both principal and agent, we introduce modified Q-functions, which we formally
derive as fixed points of contraction operators in Appendix B.3. We detail deep implementations in
Appendix D. Our approach consists of the following two-phase setup:
1.Training: Principal’s policy is trained ‘for free’ in simulated interactions with agent and
MDP. Principal has access to the learning agent and essentially controls it.
2.Execution / Validation: Trained principal’s policy can be executed or validated against a
black-box (possibly learning) agent.
This is in contrast with the online setup where the principal interacts with an actual black-box agent
during learning, incurring losses from payments in the process [ 31,92]. On the other hand, this setup
is one step ahead of the MARL literature adjacent to our application in Section 5, where the analysis
is typically limited to the training phase.
Agent’s perspective. Consider the agent’s MDP defined by principal’s policy ρ. The best-responding
agent’s Q-function in a state s,Q∗((s, b), a|ρ), depends on the observed contract b– particularly on
the expected payment. This effect can be isolated by applying Bellman optimality operator:
Q∗((s, b), a|ρ) =Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ), (1)
where Q∗(s, a|ρ) = [r(s, a)+γEmax a′Q∗((s′, ρ(s′)), a′|ρ)]is the truncated optimal Q-function,
which represents agent’s expected long-term utility barring the immediate payment. Our approach to
training the agent (solving inner optimization) is to learn the truncated Q-function and compute the
Q-function through (1). This way, the Q-function is defined for any b∈Bins, under an assumption
that the principal plays according to ρin future (e.g., ρ(s′)in the next state). From the agent’s
perspective, this is justified in SPE, where ρis optimal for the principal in all future subgames. Note
that computing the expected payment requires the outcome distribution – if unknown, it can be
approximated as a probabilistic classifier (more on this in Appendix D.1).
Principal’s perspective. Consider the principal’s MDP defined by a best-responding agent π∗(ρ)for
an arbitrary ρ. The basic idea is to divide the principal’s learning problem into two parts: 1) learn the
6
agent’s policy that the principal wants to implement ( recommends to the agent), and 2) compute the
optimal contracts that implement it (the minimal implementation ) using Linear Programming (LP).
Essentially, this extends the classic LP approach from static contract design described in Section 2.1.
To approach the first subproblem, we need an analogue of the principal’s Q-function that is a function
of an agent’s action. To this end, we define the contractual Q-function q∗(π∗(ρ)) :S×A→Rby
q∗(s, ap|π∗(ρ)) = max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)), (2)
which can be interpreted in sas the maximal principal’s Q-value that can be achieved by implementing
ap∈A. To compute the optimal contract arg maxbQ∗(s, b|ρ)using q∗(π∗(ρ)), we can select
the optimal action to implement as arg maxapq∗(s, ap|π∗(ρ)), and then find the corresponding
contract as solution to the conditional maximization in (2). This conditional maximization is the
second subproblem defined above. We solve it as LP (for details, see Appendix B.8):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(3)
Solving this LP requires access to the agent’s truncated Q-function Q∗. Although this requirement
is in line with the training phase of our setup, it can be alleviated, e.g., by approximating optimal
contracts with deep learning [ 79]. We do not explore this direction, so as to not conflate the distinct
learning problems originating from our MDP formulation and the agent being black-box.
Practical concerns. The above instantiation of the meta-algorithm assumes that Q-learning is
run until convergence to precisely solve both inner and outer optimization tasks. In practice, one
has to terminate early and approximate; in case of using deep RL, function approximation also
contributes to the error. In our model, even a small error can have a devastating effect because the
principal’s Q-function is discontinuous : a misestimation of the optimal contract (however slight) may
change the agent’s action, resulting in a worse outcome (see also [ 79]). We empirically validate the
robustness of our implementation to this effect: In Appendix D.1, we apply it to solve toy tree MDPs
(generalizations of Figure 1). Furthermore, our multi-agent experiments in Section 5.3 are validated
in a complex and highly combinatorial sequential social dilemma. We report additional multi-agent
experiments in Appendix D.2, where we apply a form of nudging the agents to desirable behaviour
through extra payments, which helps counteract the degrading effect of approximation errors.
5 Extension to Multi-Agent RL
In this section, we explore an extension to multiple agents. We state the formal model in Section 5.1.
We introduce sequential social dilemmas (SSDs) and the Coin Game (in Section 5.2). We present
experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this appendix, we provide formal proofs and derivations for the results in Sections 3 and 4.
Appendix B.1 provides additional intuition on the differences between the solution concepts of
Stackelberg and Subgame-Perfect Equilibria. Appendix B.2 supplements Observation 3.1 and defines
the principal’s and agent’s MDPs. Appendix B.3 defines contraction operators useful for succeeding
proofs and connects these operators to the modified Q-functions defined in Section 4. Appendices
B.4 and B.5 present the respective proofs of Theorems 3.3 and 3.4. While the theory in the main
text focuses on the finite-horizon hidden-action scenario, we also discuss the infinite-horizon and
observed-action scenarios in appendices B.6 and B.7, respectively. Finally, the linear program
formulated in Section 4 is derived and described in more detail in Appendix B.8.
Table 2 summarizes the differences between standard MDPs and Principal-Agent MDPs with and
without hidden actions.
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited)
First, consider the SPE notion: At the left subgame, the principal incentivizes the agent to take
noisy-left by choosing a contract that pays 1for outcome Land0otherwise. This way, both actions
yield the same value for the agent, 0.9·1 + 0 .1·0−0.8 = 0 .1·1 + 0 .9·0 = 0 .1, and the
agent chooses aLby tie-breaking in favour of the principal. So the principal’s value in state sLis
0.9(rp(sL, L)−1) = 0 .9(14
9−1) = 0 .5. By the same logic, the principal offers the same contract
insRand its value equals 0.5(and the agent’s value equals 0.1). Then, in s0, the agent is indifferent
between transitioning to sLandsR, so the principal has to offer the same contract again. The
principal’s value in s0(given that the agent chooses aL) is0.5 + 0 .9·0.5 + 0 .1·0.5 = 1 , and the
agent’s value is 0.1 + 0 .9·0.1 + 0 .1·0.1 = 0 .2. These are estimated by considering utilities in sL
andsRwithout discounting (using γ= 1). Note that in this analysis, we found SPE using backward
induction: we first analyzed the terminal states, then the root state.
18
Compare this with Stackelberg: If non-credible threats were allowed, the principal could threaten to
act suboptimally in the right subgame by always paying the agent 0. Both principal and agent then
value sRat0. InsL, the contract is the same as in SPE. Knowing this, the agent values sLoversR
(0.1>0), which would drive it to choose the noisy-left action at the root state even if the principal
pays only 1−0.1 = 0 .9for outcome L. By paying less, the principal’s utility (value in s0) would be
higher compared to SPE, (14
9−0.9 + 0 .5)·0.9 = 1 .04>1.
This illustrates how Stackelberg equilibrium may produce more utility for the principal, but the
surplus comes at the cost of the inability to engage in mutually beneficial contractual agreements
in certain subgames, even if these subgames are reached by pure chance and despite the agent’s
best efforts. On the one hand, Stackelberg requires more commitment power from the principal.
Whereas in SPE the agent can be certain that the principal sticks to its policy in future states because
it is optimal in any subgame, in Stackelberg, the principal has to preemptively commit to inefficient
contracts and ignore potential beneficial deviations. On the other hand, Stackelberg is not robust to
mistakes: if the agent mistakenly chooses the wrong action, it might be punished by the principal,
losing utility for both players. This is especially concerning in the context of learning, where mistakes
can happen due to approximation errors, or even due to the agent exploring (in online setups). SPE is
hence a more practical solution concept.
B.2 Principal’s and Agent’s MDPs (Observation 3.1)
A (standard) MDP is a tuple (S, S 0, A,R,T, γ), where Sis a set of states, S0∈Sis a set of
possible initial states, Ais a set of actions, T:S×A→∆(S)is a stochastic transition function,
R:S×A×S→ P(R)is a stochastic reward function ( R(s, a, s′)is a distribution and may depend
on the next state s′),γis an (optional) discounting factor. Assume finite horizon (as in Section 2).
Consider a hidden-action principal-agent MDP M= (S, s 0, A, B, O, O,R,Rp,T, γ)as defined in
Section 2. First, consider the agent’s perspective. Let the principal’s policy be some ρ. This defines
a standard MDP (Sa, Sa
0, A,Ra,Ta, γ)that we call the agent’s MDP, where: The set of states is
Sa=S×B(infinite unless Bis discretized). The set of initial states is S0={s0} ×B. The set of
actions is A.
The transition function Ta:Sa×A→∆(Sa)defines distributions over next state-contract pairs
(s′, ρ(s′)), where s′∼ T(s, o∼ O(s, a)). Note that the next state s′is sampled from a distribution
that is a function of state-action pairs (s, a)marginalized over outcomes, and the next contract ρ(s′)
is given by the principal’s policy. Informally, the agent expects the principal to stick to its policy
in any future state. At the same time, since the state space Sais defined over the set of contracts
B, the agent may adapt its policy to any immediate contract in the current state, and thus its policy
π:Sa→∆(A)is defined by π(s, b)for any b∈B.
The reward function is a bit cumbersome to formalize because it should not depend on outcomes,
while both OandTcan be stochastic. Specifically, the new reward function has to be stochastic
w.r.t. outcomes: Ra((s, b), a, s′) = [ r(s, a) +b(o)|o∼P(o|s, a, s′)], where the conditional
distribution of outcomes is given by P(o|s, a, s′) =P(O(s,a)=o)P(T(s,o)=s′)P
o∗P(O(s,a)=o∗)P(T(s,o∗)=s′).
Next, consider the principal’s perspective. Let the agent’s policy be some π. This defines a standard
MDP (S,{s0}, B,Rp,Tp, γ)that we call the principal’s MDP, where: the set of states is S; the set
of initial states is {s0}; the set of actions is B(infinite unless discretized); the transition function is
defined by Tp(s, b) =T(s, o∼ O(s, a∼π(s, b))); the reward function is defined similarly to the
agent’s MDP by Rp(s, b, s′) = [r(s, o)−b(o)|o∼P(o|s, a, s′)].
Thus, the optimization task of the principal (agent) given a fixed policy of the agent (principal) can be
cast as a standard single-agent MDP. In both players’ MDPs, the other player’s presence is implicit,
embedded into transition and reward functions. Note that our definition of standard MDP allows for
stochastic reward functions that depend on the next state, as well as a set of initial states that is not
a singleton. The same generalizations can be made in our Principal-Agent MDP definition, and in
particular, the above derivations would still hold, but we decided to slightly specify our model for
brevity.
19
B.3 Contraction Operators and their Fixed Points
Our meta-algorithm iteratively solves a sequence of principal’s and agent’s MDPs as defined in
Appendix B.2. Both tasks can be performed with Q-learning and interpreted as finding fixed points
of the Bellman optimality operator in the respective MDPs. Furthermore, our learning approach in
Section 4 makes use of modified Q-functions, which are also fixed points of contraction operators.
For convenience, we define all four operators below. Where necessary, we prove the operators being
contractions and define their fixed points.
B.3.1 Optimality operators in the agent’s MDP
Here we assume some fixed principal’s policy ρthat defines an agent’s MDP.
Bellman optimality operator. Consider the agent’s optimization task (line 3 of the meta-algorithm).
Solving it implies finding a fixed point of an operator Sρ, which is the Bellman optimality operator in
the agent’s MDP defined by a principal’s policy ρ.
Definition B.1. Given an agent’s MDP defined by a principal’s policy ρ, the Bellman optimality
operator Sρis defined by
(SρQ)((s, b), a) =Eo∼O(s,a),s′∼T(s,o)h
R(s, a, b, o ) +γmax
a′Q((s′, ρ(s′)), a′)i
, (6)
whereR(s, a, b, o ) =r(s, a) +b(o),Qis an element of a vector space QSBA={S×B×A→R},
and subscript ρdenotes conditioning on the principal’s policy ρ.
This operator is a contraction and admits a unique fixed point Q∗(ρ)that satisfies:
V∗(s, b|ρ) = max
aQ∗((s, b), a|ρ), (7)
Q∗((s, b), a|ρ) =Eh
R(s, a, b, o ) +γmax
a′Q∗((s′, ρ(s′)), a′|ρ)i
. (8)
The policy corresponding to the fixed point is called the best-responding policy π∗(ρ):
∀s∈S, b∈B:π∗(s, b|ρ) = arg max
aQ∗((s, b), a|ρ),
where ties are broken in favour of the principal.
Truncated Bellman optimality operator. Here we show that the truncated Q-function Q∗(ρ)
defined in the main text (1)is a fixed point of a contraction operator and thus can be found with
Q-learning.
Definition B.2. Given an agent’s MDP defined by principal’s policy ρ, the truncated Bellman
optimality operator Sρis defined by
(SρQ)(s, a) =r(s, a) +γEo∼O(s,a),s′∼T(s,o)max
a′
Eo′∼O(s′,a′)ρ(s′)(o′) +Q(s′, a′)
,(9)
where Qis an element of a vector space QSA={S×A→R}.
Lemma B.3. Operator Sρis a contraction in the sup-norm.7
Proof. LetQ1,Q2∈ QSA,γ∈[0,1). The operator Sρis a contraction in the sup-norm if it satisfies
∥SρQ1−SρQ2∥∞≤γ∥Q1−Q2∥∞. This inequality holds because:
7In lemmas B.3 and B.6, we show for a case that includes finite- and infinite-horizon MDPs, but requires
γ < 1. For γ= 1and finite-horizon MDPs, per-timestep operators can be shown to be contractions, similar to
the Bellman operator in chapter 4.3 of Puterman [60].
20
∥SρQ1−SρQ2∥∞= max
s,aγEo,s′
max
a′(Eo′ρ(s′)(o′) +Q1(s′, a′))−
max
a′(Eo′ρ(s′)(o′) +Q2(s′, a′))
+r(s, a)−r(s, a)≤
max
s,aγEo,s′max
a′Eo′
ρ(s′)(o′) +Q1(s′, a′)−ρ(s′)(o′)−Q2(s′, a′)=
max
s,aγEo,s′max
a′
Q1(s′, a′)−Q2(s′, a′)≤
max
s,aγmax
s′,a′Q1(s′, a′)−Q2(s′, a′)=γ∥Q1−Q2∥∞.
Because Sρis a contraction as shown in Lemma B.3, by the Banach theorem, it admits a unique fixed
point Q∗
ρs.t.∀s, a:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a). We now show that this fixed point is the truncated
Q-function. Define Qρ((s, b), a) =Eo∼O(s,a)b(o) +Q∗
ρ(s, a). Notice that the fixed point satisfies:
∀s∈S, a∈A:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a)(Eq. 9)=
r(s, a) +γEo,s′max
a′
Eo′ρ(s′)(o′) +Q∗
ρ(s′, a′)
=
r(s, a) +γEo,s′max
a′Qρ((s′, ρ(s′)), a′).
At the same time, by definition:
∀s∈S, a∈A:Q∗
ρ(s, a) =Qρ((s, b), a)−Eo∼O(s,a)b(o).
Combining the above two equations and swapping terms:
∀s∈S, a∈A:Qρ((s, b), a) =r(s, a) +Eo,s′[b(o) +γmax
a′Qρ((s′, ρ(s′)), a′)].
Notice that the last equation shows that Qρis the fixed point of the Bellman optimality operator
Sρ(6), i.e., Qρ=Q∗(ρ), as it satisfies the optimality equations (8). It follows that Q∗((s, b), a|
ρ) =Eob(o) +Q∗
ρ(s, a), and thus Q∗
ρsatisfies the definition of the truncated Q-function (1), i.e.,
Q∗
ρ=Q∗(ρ). The truncated Q-function is then a fixed point of a contraction operator and can be
found with Q-learning. It can also be used to compute the best-responding policy: π∗(s, b|ρ) =
arg maxa[Eob(o) +Q∗(s, a|ρ)].
B.3.2 Optimality operators in the principal’s MDP
Here we assume some fixed best-responding agent’s policy π∗(ρ)that defines a principal’s MDP.
While we could instead assume an arbitrary policy π, we are only interested in solving the principal’s
MDP as the outer level of the meta-algorithm, which always follows the inner level that outputs an
agent’s policy π∗(ρ)best-responding to some ρ.
Bellman optimality operator. Consider the principal’s optimization level (line 4 of the meta-
algorithm). Solving it implies finding a fixed point of an operator Bρ, which is the Bellman optimality
operator in the principal’s MDP defined by the agent’s policy π∗(ρ)is best-responding to some ρ.
Definition B.4. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the Bellman optimality operator Bρis defined by
(BρQ)(s, b) =Eo∼O(s,a),s′∼T(s,o)h
Rp(s, b, o ) +γmax
b′Q(s′, b′)
|a=π∗(s, b|ρ)i
,(10)
where Rp(s, b, o ) =rp(s, o)−b(o),Qis an element of a vector space QSB={S×B→R}, and
subscript ρdenotes conditioning on the agent’s best-responding policy π∗(ρ).
21
This operator is a contraction and admits a unique fixed point Q∗(π∗(ρ))that satisfies optimality
equations:
V∗(s|π∗(ρ)) = max
bQ∗(s, b|π∗(ρ)), (11)
Q∗(s, b|π∗(ρ)) =Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))
|a=π∗(s, b|ρ)i
.(12)
The policy corresponding to the fixed point is called the subgame-perfect policy ρ∗(π∗(ρ)):
∀s∈S:ρ∗(s|π∗(ρ)) = arg max
bQ∗(s, b|π∗(ρ)).
Contractual Bellman optimality operator. Here we show that the contractual Q-function
q∗(π∗(ρ))defined in the main text (2)is a fixed point of a contraction operator and thus can be found
with Q-learning.
Definition B.5. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the contractual Bellman optimality operator Hρis defined by
(Hρq)(s, ap) = max
{b|π∗(s,b|ρ)=ap}Eo∼O(s,ap),s′∼T(s,o)h
Rp(s, b, o ) +γmax
a′q(s′, a′)i
, (13)
where qis an element of a vector space QSA={S×A→R}, and ap∈Adenotes the principal’s
recommended action.
Lemma B.6. Operator Hρis a contraction in the sup-norm.
Proof. Letq1, q2∈ QSA,γ∈[0,1). The operator Hρis a contraction in the sup-norm if it satisfies
∥Hρq1− H ρq2∥∞≤γ∥q1−q2∥∞. This inequality holds because:
∥Hρq1− H ρq2∥∞= max
s,a max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q1(s′, a′)
−
max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q2(s′, a′)=
max
s,aγE[max
a′q1(s′, a′)−max
a′q2(s′, a′)]≤
max
s,aγEmax
a′q1(s′, a′)−max
a′q2(s′, a′)≤
max
s,aγEmax
a′|q1(s′, a′)−q2(s′, a′)| ≤
max
s,aγmax
s′,a′|q1(s′, a′)−q2(s′, a′)|=γ∥q1−q2∥∞.
Because Hρis a contraction as shown in Lemma B.6, by the Banach theorem, it admits a unique fixed
point q∗
ρs.t.∀s, ap:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap). We now show that this fixed point is the contractual
Q-function. Notice that the fixed point satisfies:
∀s∈S: max
apq∗
ρ(s, ap) = max
ap(Hρq∗
ρ)(s, ap)(Eq. 13)=
max
b(Hρq∗
ρ)(s, π∗(s, b|ρ)) = max
b(Hρ(Hρq∗
ρ))(s, π∗(s, b|ρ)) =···=
max
bEX
th
γtRp(st, bt, ot)|s0=s, b0=b, π∗(ρ)i
= max
bQ∗(s, b|π∗(ρ)),(14)
22
and:
∀s∈S, ap∈A:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap)(Eq. 13)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
a′q∗
ρ(s′, a′)i(Eq. 14)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))i(Eq. 12)=
max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)).(15)
Thus, q∗
ρsatisfies the definition of the contractual Q-function (2), i.e., q∗
ρ=q∗(ρ). The contractual
Q-function is then a fixed point of a contraction operator and can be found with Q-learning. The
contractual Q-function can also be used to compute the subgame-perfect principal’s policy as ρ∗(s) =
arg maxb(Hρq∗
ρ)(s, π∗(s, b|ρ)) = arg maxbQ∗(s, b|π∗(ρ)). We address computing the arg max
in Appendix B.8 using Linear Programming.
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3)
Observation B.7. A principal-agent stochastic game Gis in SPE if and only if every subgame of G
is in SPE.
Observation B.7 will be useful for the proofs in this section.
LetSt⊆Sdenote the set of all possible states at time step t. For example, S0={s0}. States in ST
are terminal by definition. We assume that sets Stare disjoint. This is without loss of generality, as
we can always redefine the state space of a finite-horizon MDP such that the assumption holds; e.g.,
by concatenating the time step to a state as snew
t= (st, t). In other words, any finite-horizon MDP
can be represented as a directed acyclic graph.
The next lemma is a precursor to proving the convergence of Algorithm 1 and concerns its single
iteration. Given a pair of policies that form an SPE in all subgames but the original game, it states
that performing one additional iteration of the algorithm (update the agent, then the principal) yields
an SPE in the game. This is because the agent observes the contract offered in a state and adapts
its action, in accordance with our definition of the agent’s MDP in Appendix B.2. In particular,
the agent’s best-responding policy is defined as π∗(s, b|ρ)foranypair(s, b), so in s0, the agent
best-responds with π∗(s0, b|ρ)for any bregardless of the principal’s policy ρ(s0).
Lemma B.8. Given a finite-horizon principal-agent stochastic game Gand a principal’s policy
ρ, if(ρ, π∗(ρ))is an SPE in all subgames with a possible exception of G(i.e., all subgames in
s∈S\ {s0}), then (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G.
Proof. Ins0, the agent observes the principal’s action. Consequently and because the agent best-
responds to ρ, it also best-responds to any {ρ′| ∀s∈S\ {s0}:ρ′(s) =ρ(s)}regardless of the
offered contract ρ′(s0), including the subgame-perfect ρ∗(π∗(ρ))(that only differs from ρins0, as
subgames in other states are in SPE already). Thus, (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G, as well as in
all subgames of G(by Observation B.7).
Corollary B.9. Given Gwith a single subgame ( S={s0}),(ρ∗(π∗(ρ)), π∗(ρ))is an SPE in Gfor
anyρ.
This corollary concerns MDPs with a single state, which could also be interpreted as stateless. This
covers static contract design problems, as well as subgames in terminal states in our model.
By using Lemma B.8, we can now show that each iteration of the algorithm expands the set of
subgames that are in SPE, as long as some subgames satisfy the conditions of the lemma for an
arbitrarily initialized ρ. This is always the case for finite-horizon MDPs, as the subgames in terminal
states have a single subgame (itself), and thus Corollary B.9 applies. This reasoning is used to prove
Theorem 3.3.
Proof of Theorem 3.3. Denote the policy initialized at line 1 as ρ0. Denote the best-responding policy
toρ0asπ1≡π∗(ρ0)and the subgame-perfect policy against π1asρ1≡ρ∗(π1). Likewise, πiand
23
ρirespectively denote the best-responding policy to ρi−1and the subgame-perfect policy against πi,
where iis an iteration of the algorithm.
By Corollary B.9, (ρ1, π1)forms an SPE in all subgames in terminal states, including s∈ST.
Applying Lemma B.8, as well as our assumption that sets Stare disjoint, (ρ2, π2)is an SPE in all
subgames in ST∪ST−1. By induction, (ρi, πi)is an SPE in all subgames in s∈ST∪ST−1··· ∪
ST−i+1. Thus, (ρT+1, πT+1)is an SPE in all subgames in s∈ST∪ ··· ∪ S0=S, and thus in the
gameG(by Observation B.7).
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4)
Consider the principal’s optimization task (line 4 of the meta-algorithm). As we discuss in Ap-
pendix B.3, solving this task can be interpreted as finding the fixed point of a contraction operator Bρ
defined in (10). By definition of contraction, this fixed point can be found by iteratively applying the
operator until convergence, which we denote as H∗=Bρ(Bρ(Bρ...Q(s, b))).
Observation B.10. H∗is a composition of linear operators and thus is a linear operator.
ForH∗to be a contraction, its fixed point has to be unique. Since its iterative application (the
meta-algorithm, Algorithm 1) converges to an SPE, we next prove the uniqueness of Q-functions in
SPE.
Lemma B.11. Given a finite-horizon principal-agent stochastic game G, the principal’s Q-function
is equal in all SPE for any state-action; the same holds for the agent’s Q-function.
Proof. Consider a principal’s policy ρthat forms SPE with any best-responding agent’s policy π∗(ρ).
Anyπ∗(ρ)solves the agent’s MDP and thus all such policies define a unique agent’s Q-function
(which is the fixed point of the Bellman optimality operator). Furthermore, by the assumption that
the agent breaks ties in favor of the principal, all best-responding policies also uniquely define the
principal’s Q-function (in other words, any policy that solves the agent’s MDP but does not maximize
the principal’s Q-function when breaking ties in some state is not a best-responding policy by the
assumed tie-breaking). Thus, for any pair of SPE with non-equal Q-functions, the principal’s policies
must also differ.
Consider two principal’s policies, ρxandρy, that form SPE with any respective best-responding
agents’ policies, π∗(ρx)andπ∗(ρy). By the above argument, the choice of π∗(ρx)andπ∗(ρy)is
inconsequential, so we can assume those to be unique (e.g. by adding lexicographic tie-breaking if
the principal-favored tie-breaking does not break all ties).
Forρxandρyto differ, there must be a state s∈Stsuch that 1) all subgames in states “after” t,
i.e.,{St′}t′>t, are in unique SPE given by some ρandπ∗(ρ)(e.g., this holds in a terminal state)
and 2) the subgame in shas two contracts, bx=ρx(s)andby=ρy(s), that both maximize the
principal’s utility, i.e., Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)). Denote the agent’s actions in s
asax=π∗(s, bx|ρ)anday=π∗(s, by|ρ). We now show that the choice between bxandbyis
inconsequential as both contracts also yield the same utility for the agent.
Assume the agent prefers bxtoby, i.e., Q∗((s, bx), ax|ρ)> Q∗((s, by), ay|ρ). First, use
the observed-action notation. Applying the Bellman optimality operator and using the defi-
nition of R, we have E[r(s, ax) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +bx(ax)>E[r(s, ay) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +by(ay). Observe that the principal may simply decrease the
payment bx(ax)by the difference of the agent’s Q-values (so that the inequality becomes equality),
increasing the principal’s utility. So, the assumption that the agent prefers bxtobymeans that neither
contract maximizes the principal’s utility in the subgame, leading to a contradiction.
The same can be shown in the hidden-action model. The agent preferring bxtoby
would mean E[r(s, ax) +bx(o) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)]>E[r(s, ay) +by(o) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)], and the principal would be able to adjust bxin order to decrease the
expected payment E[bx(o)]relatively to E[by(o)], e.g., by decreasing each non-zero payment bx(o)
by a constant. Again, this leads to a contradiction.
We thus have shown that the choice between bxandbyinsis inconsequential for the value functions
of both principal and agent in s:V∗(s|π∗(ρx)) = Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)) =
V∗(s|π∗(ρy))andV∗(s, bx|ρ) =Q∗((s, bx), ax|ρ) =Q∗((s, by), ay|ρ) =V∗(s, by|ρ). By
Bellman optimality equations ( (7)and(8)for the agent, (11) and(12) for the principal), it is also
24
inconsequential for the players’ Q-functions in all states “before” t, i.e.,{St′}t′<t. For states “after”
t, the choice also has no effect by the MDP being finite-horizon (and our w.l.o.g. assumption about
the uniqueness of states). This holds for any such bxandbyin any s. Thus, for any SPE (ρ, π∗(ρ)),
each player’s Q-function is identical in all SPE for any state-action.
Proof of Theorem 3.4. By Observation B.10, H∗is a linear operator. Moreover, as Algorithm 1
converges to SPE by Theorem 3.3 and the payoffs in SPE are unique by Lemma B.11, the iterative
application of H∗converges to a unique fixed point. By using a converse of the Banach theorem
(Theorem 1 in Daskalakis et al. [13]), this operator is a contraction under any norm that forms a
complete and proper metric space. This includes the sup-norm.
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs
Here we present an example of a hidden-action infinite-horizon principal-agent MDP where the
meta-algorithm diverges by getting stuck in a cycle. To solve the principal’s and agent’s optimization
tasks, we specifically developed exact solvers for principal’s and agent’s MDPs.
The MDP consists of two states, s1ands2. In each state, the agent has two actions, a1anda2, which
determine probabilities of sampling one of two outcomes, o1ando2. When agent chooses a1in any
states, outcomes are sampled with respective probabilities O(o1|s, a 1) = 0 .9andO(o2|s, a 1) =
0.1. Vice versa, choosing a2in any state ssamples an outcome with probabilities O(o1|s, a 2) = 0 .1
andO(o2|s, a 2) = 0 .9. After sampling an outcome oi, the MDP deterministically transitions to si
(e.g., if o1is sampled, the MDP transitions to s1regardless of the old state and the agent’s action).
Choosing an action that is more likely to change the state of the MDP (so, a2ins1anda1ins2)
requires effort from the agent, respectively costing c(s1, a2) = 1 andc(s2, a1) = 2 . The other action
is free for the agent: c(s1, a1) = 0 andc(s2, a2) = 0 . Other things equal, the principal prefers the
agent to invest an effort: it only enjoys a reward whenever the MDP transitions to a different state,
equal to rp(s1, o2) =rp(s2, o1) = 1 .5. The discount factor is set to γ= 0.9.
We now describe several iterations of the meta-algorithm, showing that it oscillates between two pairs
of players’ policies. We report the agent’s truncated Q-function (1)and the principal’s contractual
Q-function (2)at each iteration of the algorithm (rounded to three decimals). We also verify that
these Q-functions are indeed fixed points of respective operators and thus solve the respective MDPs,
but only do so in (s1, a2)as derivations in other state-action pairs are identical.
Initialization
Initialize the principal with a policy ρ0that does not offer any payments, i.e., ρ0(s1) =ρ0(s2) =
(0,0), where we denote a contract by a tuple b= (b(o1), b(o2)).
Iteration 1: agent
The agent’s best-responding policy π1simply minimizes costs by never investing an effort:
π1(s1, ρ0(s1)) =a1,π1(s2, ρ0(s2)) =a2. This corresponds to the following truncated Q-function:
Qπ1(s1, a1) =Qπ1(s2, a2) = 0 ,Qπ1(s1, a2) =−c(s1, a2) =−1andQπ1(s2, a1) =−c(s2, a1) =
−2.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−1 =Qπ1(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1·0 + 0 .9·0] =−1.
In the absence of contracts, the agent’s truncated Q-function is equal to its Q-function under the
principal’s policy: Qπ1((s, ρ 0(s)), a) =Qπ1(s, a).
Iteration 1: principal
The principal’s subgame-perfect policy ρ1attempts to incentivize effort in s1and offers the following
contracts: ρ1(s1) = (0 ,1.25),ρ1(s2) = (0 ,0). This corresponds to the following contractual Q-
function: qρ1(s1, a1) = 1 .991,qρ1(s1, a2) = 2 .048,qρ1(s2, a1) = 1 .391, and qρ1(s2, a2) = 2 .023.
25
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
2.048 = qρ1(s1, a2) =Eo,s′[−ρ1(s1)(o) +rp(s1, o) +γmax
a′qρ1(s′, a′)] =
0.1(0 + 0 + 0 .9·2.048) + 0 .9(−1.25 + 1 .5 + 0 .9·2.023) = 2 .048.
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .5,0), which is not worth it for the
principal, as evidenced by qρ1(s2, a1)< qρ1(s2, a2).
Iteration 2: agent
The principal ρ1underestimated the payment required to incentivize effort, and the agent’s best-
responding policy π2still never invests an effort: π2(s1, ρ1(s1)) = a1,π2(s2, ρ1(s2)) = a2. This
corresponds to the following truncated Q-function: Qπ2(s1, a1) = 0 .723,Qπ2(s1, a2) =−0.598,
Qπ2(s2, a1) =−1.277, and Qπ2(s2, a2) = 0 .402.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−0.598 = Qπ2(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1(0.9(0 + 0 .723) + 0 .1(1.25 + 0 .402))+
0.9(0.1(0 + 0 .723) + 0 .9(0 + 0 .402))] = −0.598.
Given the contracts from the principal’s policy ρ1, we can compute the agent’s Q-values using (1):
Qπ2((s1, ρ1(s1)), a1) = 0 .848,Qπ2((s1, ρ1(s1)), a2) = 0 .527,Qπ2((s2, ρ1(s2)), a1) =−1.277,
andQπ2((s2, ρ1(s2)), a2) = 0 .402. Observe that indeed, the agent still prefers not to invest an effort
ins1, as evidenced by Qπ2((s1, ρ1(s1)), a1)> Qπ2((s1, ρ1(s1)), a2).
Iteration 2: principal
The principal gives up on incentivizing effort and once again offers no contracts: ρ2(s1) = (0 ,0),
ρ2(s2) = (0 ,0). This corresponds to the following contractual Q-function: qρ2(s1, a1) = 1 .661,
qρ2(s1, a2) = 1 .503,qρ2(s2, a1) = 1 .422, and qρ2(s2, a2) = 1 .839.
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, to incentivize a2in
s1, the principal has to offer a contract ρ(s1) = (0 ,1.652) , which gives us:
1.503 = qρ2(s1, a2) =Eo,s′[−ρ2(s2)(o) +rp(s1, o) +γmax
a′qρ2(s′, a′)] =
0.1(0 + 0 + 0 .9·1.661) + 0 .9(−1.652 + 1 .5 + 0 .9·1.839) = 1 .503,
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .098,0), which is still not worth it for
the principal, as evidenced by qρ2(s2, a1)< qρ2(s2, a2).
Subsequent iterations
Because the principal’s subgame-perfect policy ρ2repeats the policy ρ0from a previous iteration, the
meta-algorithm is now stuck in a cycle where iterations 1 and 2 repeat infinitely. In other words, the
meta-algorithm diverges.
B.7 Meta-Algorithm in the Observed-Action Model
In the special case where the agent’s actions are observed (defined in Section 2.2 and summarized
in Table 2), the meta-algorithm can be shown to find SPE in a single (rather than T+ 1) iteration,
as we show in Theorem B.12. This property is based on the observation that the agent is indifferent
between an MDP without a principal and an MDP augmented with a subgame-perfect principal;
similar observation has been made in contemporaneous work [ 3]. Consequently, evaluating minimal
implementation only requires access to the agent’s optimal Q-function in the absence of the principal.
26
Is is also easy to show that SPE coincides with Stackelberg equilibrium in the observed-action
scenario (Lemma B.14), and consequently the meta-algorithm finds Stackelberg equilibrium.
Theorem B.12. Given a principal-agent stochastic game, G, with observed actions and either finite
or infinite horizon, if the principal’s policy is initialized to offer zero-vectors as contracts in all states,
the meta-algorithm finds SPE in one iteration.
Proof of Theorem B.12. Use the same notations of ρiandπias in the proof of Theorem 3.3 in
Appendix B.4.
After initializing ρ0(that always offers 0) and finding the best-responding agent π1, consider the
optimal payments found at the outer optimization level of Algorithm 1. Given a state s∈S, denote
the agent’s action as
a∗= arg max
aQ∗((s,0), a|ρ0).
For now, let contracts in states other than sremain 0; we will omit the conditioning of Q∗onρ0for
brevity. The optimal contract in s, denoted as b∗, reimburses the agent for taking a suboptimal action,
paying exactly
b∗(s, ap) =Q∗((s,0), a∗)−Q∗((s,0), ap)
if the agent selects ap, and pays 0otherwise. Note that b∗=0ifap=a∗. This contract makes the
agent indifferent between apanda∗because
Q∗((s, b∗), ap) =Q∗((s,0), ap) +b∗(s, ap) =Q∗((s,0), a∗),
changing the agent’s action in stoap(according to tie-breaking). However, the agent’s value function
remains unchanged:
V∗(s, b∗) =Q∗((s, b∗), ap) =Q∗((s,0), a∗) =V∗(s,0).
Thus, the Bellman optimality equations (7)and(8)still hold in all states after replacing 0withb∗in
s, and π1still best-responds to the updated principal. This replacement of zero-vectors for optimal
contracts b∗is performed in all states during the update of the principal at the outer optimization
level, yielding a principal’s policy ρ1subgame-perfect against π1. At the same time, π1remains
best-responding against ρ1. Thus, (ρ1, π1)is an SPE.
Remark B.13 .Unlike our general Theorem 3.3, the above proof relies on the specifics of our model
such as the principal’s action set and the players’ reward functions.
Lemma B.14. Given a principal-agent stochastic game, G, with observed actions, any SPE is a
Stackelberg equilibrium.
Proof. Consider an SPE. As discussed in the above proof, the contracts in SPE exactly reimburse the
agent for choosing suboptimal actions, and the agent’s value function when offered such a contract in
some state sremains the same as in the absence of the contract. Additionally, notice that the principal
may never decrease the agent’s value in any state below the value it gets in the absence of contracts
(since payments are non-negative). Thus, the principal may not deviate from SPE by decreasing
the agent’s value in any of the future states through suboptimal contracts in order to incentivize a
suboptimal action apwhile paying less in s.
On the other hand, consider the principal trying to pay less in some state sby increasing the agent’s
value in some future states. If transition function is determenistic, then in order to decrease the
payment in sby some v < b∗(ap)while still incentivizing ap, the principal must, for example,
increase the payment in s′=T(s,O(s, ap))byv/γ– which is inconsequential for the principal’s
value in s(in our model, the discount factor is the same for the principal and the agent). In case
of a stochastic transition function, the increase of payments in future states required to balance the
decrease of the payment in sbyvmay even decrease the principal’s value in scompared to SPE.
Thus, the principal may not deviate from an SPE (commit to non-credible threats) to increase its
value in the initial state, and therefore any SPE is a Stackelberg equilibrium.
27
B.8 Deriving the Linear Program (Section 4)
In Section 4, we describe an RL approach to solving the principal’s MDP that involves two interde-
pendent tasks of 1) learning a policy that the principal wants to implement and 2) computing the
contracts that do so optimally. The former is solved by learning the contractual Q-function (2), which
we derive as a fixed point of a contraction operator Hρ(13) in Appendix B.3. The latter (which is
required as a subroutine to apply Hρ) we solve using Linear Programming, akin to how the static
principal-agent problems are typically solved (as mentioned in Section 2.1).
Given a state s∈Sand an action to recommend ap∈A, rewrite the right-hand side of Hρas the
following constrained optimization problem:
max
b∈BEo∼O(s,ap),s′∼T(s,o)h
rp(s, o)−b(o) +γmax
a′q(s′, a′)i
s.t.
∀a∈A:Q∗((s, b), ap|ρ)≥Q∗((s, b), a|ρ),(16)
where the constraints explicitly require the recommended action apto be at least as ‘good’ for the
agent as any other action a. Note that rp(s, o)andq(s′, a′)are constants with respect to band can
be omitted from the objective. To see that the constraints are linear, apply the Bellman optimality
operator to the agent’s Q-function, and rewrite constraints through the truncated Q-function using (1):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(17)
Because both the objective and the conditions are linear, the problem (17) is an LP.
As discussed in Section 4, our approach to solving the agent’s optimization problem is to learn the
truncated Q-function Q∗(ρ)and transform it into the Q-function by adding the expected payment.
Note that this representation of the agent’s Q-function is used in the constraints of the above LP. The
requirement of the principal having access to the agent’s (truncated) Q-function can be seen as a
limitation of the outlined approach. A potential remedy is to instead parameterize the principal’s
Q-function Q∗(π)with a discontinuous neural network able to efficiently approximate the Q-function
and the solutions to LPs without requiring access to the agent’s private information [ 79]. Of course,
one could also directly learn Q∗(π)with simpler approaches, e.g., by discretizing the contract space
or employing deep RL | Section not found | theoretical framework that applies to such scenarios is known in economics as principal-agent
theory (e.g., [ 32,26,66,71]). In the aforementioned applications, it distinguishes between the agents,
who directly interact with the MDP while incurring costs for their actions, and the principal, who
receives rewards from the interaction. One of the most important tools in economics for shaping
incentives is contracts . A contract defines payments from the principal to the agent (monetary or
other) based on the observable outcomes (i.e., rewards) of the actions chosen by the agent(s). The
mapping from actions to rewards is often (but not necessarily) modeled as being stochastic, in which
case it may be impossible to infer the chosen actions from the observed outcomes. A standard
assumption in economics, known as limited liability , is that the payments must be non-negative. The
agent(s), in turn, choose an action policy that maximizes their utility, given by payments minus costs.
We are thus looking at a stochastic game, in which principal and agent(s) best respond to each other.
The celebrated theory of contracts was awarded the Nobel Prize in Economics in 2016. While it has
seen a surge of interest from the computer science and learning communities recently (e.g., [ 30,19,
∗Israel Institute of Technology, Haifa, Israel. Email: [email protected]
†Google, Zurich, Switzerland. Email: [email protected]
‡Israel Institute of Technology, Haifa, Israel. Email: [email protected]
§Harvard University, Cambridge, USA. Email: [email protected]
¶Harvard University, Cambridge, USA. Email: [email protected]
Preprint. Under review.arXiv:2407.18074v1 [cs.GT] 25 Jul 2024
20,91,79]) it has received relatively little attention from the RL perspective. In this work we bridge
this gap by providing theory-inspired, practical algorithms for solving RL problems with misaligned
incentives (with standard RL pipelines, achieving scale with deep RL).
Why is principal-agent RL challenging? Principal-agent RL is challenging for several reasons:
(1)Complexity of the setting. MDPs are inherently combinatorial due to their temporal nature, even
more so when multiple parties are involved. Contracts are continuous, making the set of all possible
contracts (even for single-period problems) infinite. (2) Misaligned preferences and strategic behavior.
Principal and agent have misaligned preferences, each learning to maximize their own utility in the
presence of the other. Private information (such as hidden actions) further complicates the problem.
(3)Approximation and learning. In practice, learning inherently comes with approximation errors.
Even slight errors may have devastating effects due to discontinuity of the principal’s utility function.
1.1 Our Contribution
We formulate and study a principal-agent game in which the agent learns a policy for an MDP on
behalf of the principal, and the principal learns to guide the agent via a series of contracts. After
defining this setup formally (Section 2), we first discuss the purely economic setting (Section 3) with
full access to the MDP model and no learning required. We focus on the standard solution concept
for extensive-form games, namely subgame-perfect equilibrium (SPE)—see Section 3.1.
A key observation is that fixing one player’s policy defines a standard MDP for another player. Based
on this, we formulate a simple meta-algorithm (Algorithm 1) that finds SPE in a finite-horizon game
in at most T+ 1iterations, where Tis the horizon of the MDP (Theorem 3.3). The meta-algorithm
iteratively optimizes the principal’s and agent’s policies in their respective MDPs, but does not specify
the optimization steps. We also give the meta-algorithm a clean mathematical interpretation as an
iterative application of a contraction operator to the principal’s Q-function (Theorem 3.4).
Next, we turn to the standard model-free RL setting where the MDP is a black box, and the policies
are learned by sampling stochastic transitions and rewards through interacting with the MDP. We
instantiate the meta-algorithm by solving both principal’s and agent’s MDPs with (deep) Q-learning
and apply it in a two-phase setup. First, we train the policies assuming the principal has access
to the agent’s optimization problem (of maximizing its Q-function estimate given a contract in a
state). Such an access is a standard assumption in economics, and does not trivialize the problem.
Then, we relax the assumption and validate the learned principal’s policy against black-box agents
trained from scratch, mimicking its execution in the real world. Alternatively, it is possible to lift
this assumption completely by applying any learning algorithm for the one-shot contracting problem,
such as the deep-learning approach of Wang et al. [79]. Through this setup, we verify empirically
that our method approximates SPE well despite early termination and approximation errors.
In Section 5, we extend our approach to multi-agent RL and sequential social dilemmas (SSDs) [42],
a generalization of prisoner’s-dilemma-style single-shot games to multiple time periods and complex
state spaces. A common approach to SSDs is through shaping the agents’ rewards, with a focus on
cooperation and social welfare maximization. However, the extent to which the rewards are modified
is typically ignored, and despite the vast literature on the topic, there is no general procedure for
finding a minimal intervention into agents’ rewards that drives cooperation. We address this gap using
our developed principal-agent machinery. We empirically validate our approach on a prominent SSD
known as the Coin Game [23]. We compare to an alternative, simpler approach with hand-coded
payment schemes inspired by a reward-redistribution method of Christoffersen et al. [8], and observe
that with the same amount of subsidy, this less-targeted intervention achieves a significantly lower
welfare level.
1.2 Related Work
Our work fits into the wider literature on automated mechanism design [ 10], in particular approaches
based on deep learning [ 18,79] also known as differentiable economics [ 21]. Most closely related
from this line of work, Wang et al. [79] consider stateless one-shot contracting problems and provide
a network architecture for capturing the discontinuities in the principal’s utility function. We differ
from this work in our focus on sequential contracting problems and the entailing unique challenges.
2
There is a number of algorithmic works that focus on repeated principal-agent interactions on MDPs,
including work on environment design andpolicy teaching [87,89,85,3]. Our approach differs from
these earlier works in several ways, including that we actively search for the best (unconstrained)
equilibrium in the game between the principal and the agent through reinforcement learning. A
closely related line of work, including [ 24], is concerned with learning Stackelberg equilibria in
general leader-follower games, including games on MDPs. Our work differs in its focus on SPE,
which is the more standard equilibrium concept in dynamic contract design problems. Several
works have studied repeated contract design problems from a no-regret online-learning perspective
[30,91,29,70]. However, these works are typically limited to stateless and/or non-sequential
interactions. A prominent exception is a contemporaneous study by Wu et al. [82] that introduces a
model of principal-agent MDPs nearly identical to ours, barring an important notational distinction
of encoding outcomes as next states. However, their and our studies pursue orthogonal algorithmic
developments: whereas they treat contract policies as arms of a bandit and minimize regret, we rely
on deep RL to scale to large MDPs and multiple agents.
Starting with the work of Leibo et al. [42], there is a huge literature on SSDs. Most closely related in
this direction is the work by Christoffersen et al. [8]on multi-agent RL and applications to SSDs.
This work pursues an approach in which one of the agents (rather than the principal) proposes a
contract (an outcome-contingent, zero-sum reward redistribution scheme), and the other agents can
either accept or veto. They consider several SSDs and show how hand-crafted contract spaces strike a
balance between generality and tractability, and can be an effective tool in mitigating social dilemmas.
An important distinction of our work is that we distinguish between principal and agent(s), and insist
on the standard limited liability requirement from economics. Furthermore, in our approach the
principal learns the conditions for payments, allowing it to utilize contracts in their full generality.
Also, our method has an interpretation as learning k-implementation [52].
We provide additional details on the related literature in Appendix A.
2 Problem Setup
In this section, we first introduce the classic (limited liability) contract design model of Holmström
[32] and Grossman and Hart [26], and then propose its extension to MDPs. We defer further extension
to multi-agent MDPs to Section 5.1.
2.1 Static Hidden-Action Principal-Agent Problem
In a principal-agent problem, the principal wants the agent to perform a task. The agent has a choice
between several actions a∈Awith different costs c(a), interpreted as effort levels. Each action
stochastically maps to outcomes o∈Oaccording to a distribution O(a), with higher effort levels
more likely to result in good outcomes, as measured by the associated principal’s reward rp(o). By
default, a rational agent would choose the cost-minimizing action. To incentivize the agent to invest
an effort, the principal may offer a contract bprior to the action choice. Crucially, the principal may
be unable (or unwilling) to directly monitor the agent’s action, so the contractual payments b(o)≥0
are defined per outcome o∈O. The principal seeks an optimal contract: a payment scheme that
maximizes the principal’s utility, max bEo∼O(a)[rp(o)−b(o)], given that the agent best-responds
withmax aEo∼O(a)[b(o)]−c(a).
If costs and outcome distributions are known, the optimal contract can be precisely found using
Linear Programming (LP): for each action a∈A, find the contract that implements it (makes the
agent at least indifferent between this and other actions) through a minimal expected payment, and
then choose the best action to implement. Otherwise or if the LPs are infeasible, an approximation
can be obtained by training a neural network on a sample of past interactions with the agent [79].
2.2 Hidden-Action Principal-Agent MDPs
In order to extend contract design to MDPs, we assume a principal-agent problem in each state of
the MDP, and let the outcomes additionally define its (stochastic) transitioning to the next state. A
hidden-action principal-agent MDP is a tuple M= (S, s 0, A, B, O, O,R,Rp,T, γ). As usual in
MDPs, Sis a set of states, s0∈Sis the initial state, and Ais a set of nagent’s actions a∈A.
Additionally, Ois a set of moutcomes o∈O,B⊂Rm
≥0is a set of principal’s actions (contracts)
3
Figure 1: Example of a principal-agent MDP with three states S={s0, sL, sR}.In each state, the
agent can take one of two actions: noisy-left ( aL), which is costly and leads to outcomes LandRwith
probabilities 0.9and0.1, and noisy-right (aR), which is free and has the roles of LandRreversed.
The principal’s rewards in any state s∈Sfor outcomes L, R arerp(s, L) =14
9, rp(s, R) = 0 ,
resp., while those of the agent for the actions are r(s, aL) =−4
5, r(s, aR) = 0 . For analysis, see
Appendix B.1.
b∈B, andb(o)is the o-th coordinate of a contract (payment). In each state, the outcome is sampled
based on the agent’s action from a distribution O(s, a), where O:S×A→∆(O)is the outcome
function. Then, the agent’s reward is determined by the reward function R(s, a, b, o ) =r(s, a)+b(o)
for some r(s, a). Likewise, the principal’s reward is determined by Rp(s, b, o ) =rp(s, o)−b(o)for
some rp(s, o); note that the agent’s action is private and thus Rpdoes not explicitly depend on it.
Based on the outcome, the MDP transitions to the next state s′∼ T(s, o), where T:S×O→∆(S)
is the transition function. Finally, γ∈[0,1]is the discount factor. For an example of a principal-agent
MDP, see Figure 1. In the main text, we focus on MDPs with a finite time horizon T. We assume
w.l.o.g. that each state is uniquely associated with a time step (see Appendix B.4).
We analyze the principal-agent MDP as a stochastic game G(can be seen as extensive-form when
the horizon is finite), where two players maximize their long-term payoffs. The game progresses
as follows. At each timestep t, the principal observes the state stof the MDP and constructs a
contract bt∈Baccording to its policy ρ:S→∆(B). Then, the agent observes the pair (st, bt)
and chooses an action at∈Aaccording to its policy π:S×B→∆(A). After this, the MDP
transitions, and the interaction repeats. Both players maximize their value functions: the principal’s
value function, Vρ(π), of a policy ρgiven the agent’s policy πis defined in a state sbyVρ(s|π) =
E[P
tγtRp(st, bt, ot)|s0=s]; likewise, the agent’s value function Vπ(ρ)is defined in a state sand
given a contract bbyVπ(s, b|ρ) =E[P
tγtR(st, at, bt, ot)|s0=s, b0=b]. Players’ utilities in
the game are their values in the initial state. Additionally, define the players’ Q-value functions Qρ(π)
andQπ(ρ)byQρ(s, b|π) =Vρ(s|b0=b, π)andQπ((s, b), a|ρ) =Vπ(s, b|a0=a, ρ).
A special case of the principal-agent MDP trivializes hidden actions by making the outcome function
deterministic and bijective; the resulting observed-action model is similar to Ben-Porat et al. [3]. For
an explicit comparison of the two models with each other and with standard MDPs, see Appendix B.
3 Purely Economic Setting
In this section, we define our solution concept for principal-agent stochastic games (Section 3.1) and
introduce a meta-algorithm that finds this solution (Section 3.2). We assume full access to the MDP
model (including transition and reward functions) and address the learning setting in the next section.
3.1 Subgame-Perfect Equilibrium (SPE)
In what follows let Gbe a principal-agent stochastic game. Let a subgame ofGin state s∈Sbe a
gameG′defined by replacing s0withs, and Swith a subset of states that can be reached from s.
Observation 3.1. Fixing one player’s policy in Gdefines a (standard) MDP for another player. In
particular, a principal’s policy defines the agent’s MDP by modifying the reward function through
contracts; likewise, an agent’s policy defines the principal’s MDP by modifying the transition and
4
Algorithm 1 Meta-algorithm for finding SPE
1:Initialize the principal’s policy ρarbitrarily ▷e.g.,∀s∈S:ρ(s) =0
2:while ρnot converged do ▷Inner-outer optimization loop
3: Solve the agent’s MDP: find π:=π∗(ρ) ▷Inner optimization level
4: Solve the principal’s MDP: find ρ:=ρ∗(π) ▷Outer optimization level
5:return (ρ, π)
reward functions through the agent’s responses to contracts. For exact formulations of these MDPs,
see Appendix B.2. The optimal policies in both MDPs can be assumed w.l.o.g. to be deterministic (in
single-agent setting), and can be found with any suitable dynamic programming or RL algorithm [ 75].
Agent’s perspective. In the agent’s MDP defined by ρ, refer to the optimal policy as best-responding
toρ(where ties are broken in favor of the principal, as is standard in contract design). Define
a function π∗that maps a principal’s policy ρto the best-responding policy π∗(ρ). Denote the
action prescribed by π∗(ρ)in state sgiven contract bbyπ∗(s, b|ρ)≡π∗(ρ)(s, b). Note that the
best-responding policy is defined in sfor any b∈Band is not limited to the principal’s action ρ(s).
Principal’s perspective. Similarly, in the principal’s MDP defined by π, refer to the optimal policy as
subgame-perfect against π. Define a function ρ∗that maps an agent’s policy πto the subgame-perfect
policy ρ∗(π). Denote the contract prescribed by ρ∗(π)in state sbyρ∗(s|π)≡ρ∗(π)(s). In all
states, this policy satisfies: ρ∗(s|π)∈arg maxbQ∗(s, b|π), where Q∗(s, b|π)≡Qρ∗(π)(s, b|π)
– that is, in each subgame, the principal takes the optimal action.
Definition 3.2. Asubgame-perfect equilibrium (SPE) ofGis a pair of policies (ρ, π), where the
principal’s policy ρ≡ρ∗(π)is subgame-perfect against an agent that best-responds with π≡π∗(ρ).
SPE is a standard solution concept for extensive-form games [ 55]. It always exists and is essentially
unique (see Lemma B.11 for completeness). Compared to non-subgame-perfect solutions like the
well–studied Stackelberg equilibrium, SPE can lose utility for the principal. However, it disallows
threats that are non-credible , i.e., require playing a suboptimal contract in a subgame. We demonstrate
the difference on our example in Appendix B.1. Furthermore, Gerstgrasser and Parkes [24] show
that learning a Stackelberg equilibrium necessitates the principal to go through long episodes with
observations of the learning dynamics of the followers, and with only sparse rewards (see also Brero
et al. [5]). SPE, in contrast, naturally fits RL, as both players’ policies solve the respective MDPs.
3.2 Meta-Algorithm for Finding SPE
Algorithm 1 presents a general pipeline for finding SPE in a principal-agent stochastic game. It can be
seen as an inner-outer (bilevel) optimization loop, with agent and principal optimization respectively
constituting the inner and outer levels. We refer to this as a meta-algorithm, as we do not yet specify
how to perform the optimization (in Lines 3 and 4). Superficially, this approach resembles the use of
bilevel optimization for learning optimal reward shaping [ 72,33,7,78,6,49]. The crucial difference
of that setting is that the two levels optimize the same downstream task rather than distinct and
possibly conflicting objectives of principal and agent.
It is well-known that SPE of an extensive-form game can be found with backward induction (e.g., see
Section 5.6 of Osborne [55]). Theorem 3.3 states that the proposed meta-algorithm also finds SPE.
The proof, provided in Appendix B.4, essentially shows that it performs backward induction implicitly.
That is, each iteration of the meta-algorithm, the players’ policies reach SPE in an expanding set of
subgames, starting from terminal states and ending with the initial state. The proof does not rely on
the specifics of our model and applies to any game where players move sequentially, and the agent
observes and can respond to anyprincipal’s action in a state.
Theorem 3.3. Given a principal-agent stochastic game Gwith a finite horizon T, the meta-algorithm
finds SPE in at most T+ 1iterations.
The meta-algorithm has several unique advantages. First, as we discuss in Section 4, both inner and
outer optimization tasks can be instantiated with Q-learning. This removes the need to know the
model of the MDP and allows handling of large-scale MDPs by utilizing deep learning. Second, it
can also be seen as iteratively applying a contraction operator, which we formulate as a theorem:
5
Table 1: Correctness of the meta-algorithm in different scenarios
finite horizon T infinite horizon
hidden action finds SPE in T+ 1iterations (Theorem 3.3) may diverge (Appendix B.6)
observed action finds SPE that is also Stackelberg in 1 iteration (Appendix B.7)
Theorem 3.4. Given a principal-agent finite-horizon stochastic game G, each iteration of the meta-
algorithm applies to the principal’s Q-function an operator that is a contraction in the sup-norm.
The proof is provided in Appendix B.5. This property implies that each iteration of the meta-algorithm
monotonically improves the principal’s policy in terms of its Q-function converging. This has a
practical advantage: if meta-algorithm is terminated early, the policies still partially converge to SPE.
As an independent observation, Theorem 3.3 complements the theoretical results of Gerstgrasser
and Parkes [24]. Specifically, their Theorem 2 presents an example where RL fails to converge to a
Stackelberg equilibrium if the agent ‘immediately’ best responds. This procedure is our Algorithm 1,
with agent optimization solved by an oracle and principal optimization performed with RL. Our
Theorem 3.3 complements their negative result by showing that such a procedure converges to SPE.
Finally, while we focus on finite-horizon hidden-action MDPs in the main text, we also analyze the
other scenarios in the Appendix. Our findings are summarized in Table 1.
4 Learning Setting
In this section, we develop an RL approach to principal-agent MDPs by solving both inner and
outer optimization tasks of the meta-algorithm with Q-learning. These tasks correspond to finding
optimal policies in the respective agent’s and principal’s MDPs defined in Observation 3.1. We
operate in a standard model-free RL setting, where learning is performed through interactions with a
black-box MDP. For both principal and agent, we introduce modified Q-functions, which we formally
derive as fixed points of contraction operators in Appendix B.3. We detail deep implementations in
Appendix D. Our approach consists of the following two-phase setup:
1.Training: Principal’s policy is trained ‘for free’ in simulated interactions with agent and
MDP. Principal has access to the learning agent and essentially controls it.
2.Execution / Validation: Trained principal’s policy can be executed or validated against a
black-box (possibly learning) agent.
This is in contrast with the online setup where the principal interacts with an actual black-box agent
during learning, incurring losses from payments in the process [ 31,92]. On the other hand, this setup
is one step ahead of the MARL literature adjacent to our application in Section 5, where the analysis
is typically limited to the training phase.
Agent’s perspective. Consider the agent’s MDP defined by principal’s policy ρ. The best-responding
agent’s Q-function in a state s,Q∗((s, b), a|ρ), depends on the observed contract b– particularly on
the expected payment. This effect can be isolated by applying Bellman optimality operator:
Q∗((s, b), a|ρ) =Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ), (1)
where Q∗(s, a|ρ) = [r(s, a)+γEmax a′Q∗((s′, ρ(s′)), a′|ρ)]is the truncated optimal Q-function,
which represents agent’s expected long-term utility barring the immediate payment. Our approach to
training the agent (solving inner optimization) is to learn the truncated Q-function and compute the
Q-function through (1). This way, the Q-function is defined for any b∈Bins, under an assumption
that the principal plays according to ρin future (e.g., ρ(s′)in the next state). From the agent’s
perspective, this is justified in SPE, where ρis optimal for the principal in all future subgames. Note
that computing the expected payment requires the outcome distribution – if unknown, it can be
approximated as a probabilistic classifier (more on this in Appendix D.1).
Principal’s perspective. Consider the principal’s MDP defined by a best-responding agent π∗(ρ)for
an arbitrary ρ. The basic idea is to divide the principal’s learning problem into two parts: 1) learn the
6
agent’s policy that the principal wants to implement ( recommends to the agent), and 2) compute the
optimal contracts that implement it (the minimal implementation ) using Linear Programming (LP).
Essentially, this extends the classic LP approach from static contract design described in Section 2.1.
To approach the first subproblem, we need an analogue of the principal’s Q-function that is a function
of an agent’s action. To this end, we define the contractual Q-function q∗(π∗(ρ)) :S×A→Rby
q∗(s, ap|π∗(ρ)) = max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)), (2)
which can be interpreted in sas the maximal principal’s Q-value that can be achieved by implementing
ap∈A. To compute the optimal contract arg maxbQ∗(s, b|ρ)using q∗(π∗(ρ)), we can select
the optimal action to implement as arg maxapq∗(s, ap|π∗(ρ)), and then find the corresponding
contract as solution to the conditional maximization in (2). This conditional maximization is the
second subproblem defined above. We solve it as LP (for details, see Appendix B.8):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(3)
Solving this LP requires access to the agent’s truncated Q-function Q∗. Although this requirement
is in line with the training phase of our setup, it can be alleviated, e.g., by approximating optimal
contracts with deep learning [ 79]. We do not explore this direction, so as to not conflate the distinct
learning problems originating from our MDP formulation and the agent being black-box.
Practical concerns. The above instantiation of the meta-algorithm assumes that Q-learning is
run until convergence to precisely solve both inner and outer optimization tasks. In practice, one
has to terminate early and approximate; in case of using deep RL, function approximation also
contributes to the error. In our model, even a small error can have a devastating effect because the
principal’s Q-function is discontinuous : a misestimation of the optimal contract (however slight) may
change the agent’s action, resulting in a worse outcome (see also [ 79]). We empirically validate the
robustness of our implementation to this effect: In Appendix D.1, we apply it to solve toy tree MDPs
(generalizations of Figure 1). Furthermore, our multi-agent experiments in Section 5.3 are validated
in a complex and highly combinatorial sequential social dilemma. We report additional multi-agent
experiments in Appendix D.2, where we apply a form of nudging the agents to desirable behaviour
through extra payments, which helps counteract the degrading effect of approximation errors.
5 Extension to Multi-Agent RL
In this section, we explore an extension to multiple agents. We state the formal model in Section 5.1.
We introduce sequential social dilemmas (SSDs) and the Coin Game (in Section 5.2). We present
experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this appendix, we provide formal proofs and derivations for the results in Sections 3 and 4.
Appendix B.1 provides additional intuition on the differences between the solution concepts of
Stackelberg and Subgame-Perfect Equilibria. Appendix B.2 supplements Observation 3.1 and defines
the principal’s and agent’s MDPs. Appendix B.3 defines contraction operators useful for succeeding
proofs and connects these operators to the modified Q-functions defined in Section 4. Appendices
B.4 and B.5 present the respective proofs of Theorems 3.3 and 3.4. While the theory in the main
text focuses on the finite-horizon hidden-action scenario, we also discuss the infinite-horizon and
observed-action scenarios in appendices B.6 and B.7, respectively. Finally, the linear program
formulated in Section 4 is derived and described in more detail in Appendix B.8.
Table 2 summarizes the differences between standard MDPs and Principal-Agent MDPs with and
without hidden actions.
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited)
First, consider the SPE notion: At the left subgame, the principal incentivizes the agent to take
noisy-left by choosing a contract that pays 1for outcome Land0otherwise. This way, both actions
yield the same value for the agent, 0.9·1 + 0 .1·0−0.8 = 0 .1·1 + 0 .9·0 = 0 .1, and the
agent chooses aLby tie-breaking in favour of the principal. So the principal’s value in state sLis
0.9(rp(sL, L)−1) = 0 .9(14
9−1) = 0 .5. By the same logic, the principal offers the same contract
insRand its value equals 0.5(and the agent’s value equals 0.1). Then, in s0, the agent is indifferent
between transitioning to sLandsR, so the principal has to offer the same contract again. The
principal’s value in s0(given that the agent chooses aL) is0.5 + 0 .9·0.5 + 0 .1·0.5 = 1 , and the
agent’s value is 0.1 + 0 .9·0.1 + 0 .1·0.1 = 0 .2. These are estimated by considering utilities in sL
andsRwithout discounting (using γ= 1). Note that in this analysis, we found SPE using backward
induction: we first analyzed the terminal states, then the root state.
18
Compare this with Stackelberg: If non-credible threats were allowed, the principal could threaten to
act suboptimally in the right subgame by always paying the agent 0. Both principal and agent then
value sRat0. InsL, the contract is the same as in SPE. Knowing this, the agent values sLoversR
(0.1>0), which would drive it to choose the noisy-left action at the root state even if the principal
pays only 1−0.1 = 0 .9for outcome L. By paying less, the principal’s utility (value in s0) would be
higher compared to SPE, (14
9−0.9 + 0 .5)·0.9 = 1 .04>1.
This illustrates how Stackelberg equilibrium may produce more utility for the principal, but the
surplus comes at the cost of the inability to engage in mutually beneficial contractual agreements
in certain subgames, even if these subgames are reached by pure chance and despite the agent’s
best efforts. On the one hand, Stackelberg requires more commitment power from the principal.
Whereas in SPE the agent can be certain that the principal sticks to its policy in future states because
it is optimal in any subgame, in Stackelberg, the principal has to preemptively commit to inefficient
contracts and ignore potential beneficial deviations. On the other hand, Stackelberg is not robust to
mistakes: if the agent mistakenly chooses the wrong action, it might be punished by the principal,
losing utility for both players. This is especially concerning in the context of learning, where mistakes
can happen due to approximation errors, or even due to the agent exploring (in online setups). SPE is
hence a more practical solution concept.
B.2 Principal’s and Agent’s MDPs (Observation 3.1)
A (standard) MDP is a tuple (S, S 0, A,R,T, γ), where Sis a set of states, S0∈Sis a set of
possible initial states, Ais a set of actions, T:S×A→∆(S)is a stochastic transition function,
R:S×A×S→ P(R)is a stochastic reward function ( R(s, a, s′)is a distribution and may depend
on the next state s′),γis an (optional) discounting factor. Assume finite horizon (as in Section 2).
Consider a hidden-action principal-agent MDP M= (S, s 0, A, B, O, O,R,Rp,T, γ)as defined in
Section 2. First, consider the agent’s perspective. Let the principal’s policy be some ρ. This defines
a standard MDP (Sa, Sa
0, A,Ra,Ta, γ)that we call the agent’s MDP, where: The set of states is
Sa=S×B(infinite unless Bis discretized). The set of initial states is S0={s0} ×B. The set of
actions is A.
The transition function Ta:Sa×A→∆(Sa)defines distributions over next state-contract pairs
(s′, ρ(s′)), where s′∼ T(s, o∼ O(s, a)). Note that the next state s′is sampled from a distribution
that is a function of state-action pairs (s, a)marginalized over outcomes, and the next contract ρ(s′)
is given by the principal’s policy. Informally, the agent expects the principal to stick to its policy
in any future state. At the same time, since the state space Sais defined over the set of contracts
B, the agent may adapt its policy to any immediate contract in the current state, and thus its policy
π:Sa→∆(A)is defined by π(s, b)for any b∈B.
The reward function is a bit cumbersome to formalize because it should not depend on outcomes,
while both OandTcan be stochastic. Specifically, the new reward function has to be stochastic
w.r.t. outcomes: Ra((s, b), a, s′) = [ r(s, a) +b(o)|o∼P(o|s, a, s′)], where the conditional
distribution of outcomes is given by P(o|s, a, s′) =P(O(s,a)=o)P(T(s,o)=s′)P
o∗P(O(s,a)=o∗)P(T(s,o∗)=s′).
Next, consider the principal’s perspective. Let the agent’s policy be some π. This defines a standard
MDP (S,{s0}, B,Rp,Tp, γ)that we call the principal’s MDP, where: the set of states is S; the set
of initial states is {s0}; the set of actions is B(infinite unless discretized); the transition function is
defined by Tp(s, b) =T(s, o∼ O(s, a∼π(s, b))); the reward function is defined similarly to the
agent’s MDP by Rp(s, b, s′) = [r(s, o)−b(o)|o∼P(o|s, a, s′)].
Thus, the optimization task of the principal (agent) given a fixed policy of the agent (principal) can be
cast as a standard single-agent MDP. In both players’ MDPs, the other player’s presence is implicit,
embedded into transition and reward functions. Note that our definition of standard MDP allows for
stochastic reward functions that depend on the next state, as well as a set of initial states that is not
a singleton. The same generalizations can be made in our Principal-Agent MDP definition, and in
particular, the above derivations would still hold, but we decided to slightly specify our model for
brevity.
19
B.3 Contraction Operators and their Fixed Points
Our meta-algorithm iteratively solves a sequence of principal’s and agent’s MDPs as defined in
Appendix B.2. Both tasks can be performed with Q-learning and interpreted as finding fixed points
of the Bellman optimality operator in the respective MDPs. Furthermore, our learning approach in
Section 4 makes use of modified Q-functions, which are also fixed points of contraction operators.
For convenience, we define all four operators below. Where necessary, we prove the operators being
contractions and define their fixed points.
B.3.1 Optimality operators in the agent’s MDP
Here we assume some fixed principal’s policy ρthat defines an agent’s MDP.
Bellman optimality operator. Consider the agent’s optimization task (line 3 of the meta-algorithm).
Solving it implies finding a fixed point of an operator Sρ, which is the Bellman optimality operator in
the agent’s MDP defined by a principal’s policy ρ.
Definition B.1. Given an agent’s MDP defined by a principal’s policy ρ, the Bellman optimality
operator Sρis defined by
(SρQ)((s, b), a) =Eo∼O(s,a),s′∼T(s,o)h
R(s, a, b, o ) +γmax
a′Q((s′, ρ(s′)), a′)i
, (6)
whereR(s, a, b, o ) =r(s, a) +b(o),Qis an element of a vector space QSBA={S×B×A→R},
and subscript ρdenotes conditioning on the principal’s policy ρ.
This operator is a contraction and admits a unique fixed point Q∗(ρ)that satisfies:
V∗(s, b|ρ) = max
aQ∗((s, b), a|ρ), (7)
Q∗((s, b), a|ρ) =Eh
R(s, a, b, o ) +γmax
a′Q∗((s′, ρ(s′)), a′|ρ)i
. (8)
The policy corresponding to the fixed point is called the best-responding policy π∗(ρ):
∀s∈S, b∈B:π∗(s, b|ρ) = arg max
aQ∗((s, b), a|ρ),
where ties are broken in favour of the principal.
Truncated Bellman optimality operator. Here we show that the truncated Q-function Q∗(ρ)
defined in the main text (1)is a fixed point of a contraction operator and thus can be found with
Q-learning.
Definition B.2. Given an agent’s MDP defined by principal’s policy ρ, the truncated Bellman
optimality operator Sρis defined by
(SρQ)(s, a) =r(s, a) +γEo∼O(s,a),s′∼T(s,o)max
a′
Eo′∼O(s′,a′)ρ(s′)(o′) +Q(s′, a′)
,(9)
where Qis an element of a vector space QSA={S×A→R}.
Lemma B.3. Operator Sρis a contraction in the sup-norm.7
Proof. LetQ1,Q2∈ QSA,γ∈[0,1). The operator Sρis a contraction in the sup-norm if it satisfies
∥SρQ1−SρQ2∥∞≤γ∥Q1−Q2∥∞. This inequality holds because:
7In lemmas B.3 and B.6, we show for a case that includes finite- and infinite-horizon MDPs, but requires
γ < 1. For γ= 1and finite-horizon MDPs, per-timestep operators can be shown to be contractions, similar to
the Bellman operator in chapter 4.3 of Puterman [60].
20
∥SρQ1−SρQ2∥∞= max
s,aγEo,s′
max
a′(Eo′ρ(s′)(o′) +Q1(s′, a′))−
max
a′(Eo′ρ(s′)(o′) +Q2(s′, a′))
+r(s, a)−r(s, a)≤
max
s,aγEo,s′max
a′Eo′
ρ(s′)(o′) +Q1(s′, a′)−ρ(s′)(o′)−Q2(s′, a′)=
max
s,aγEo,s′max
a′
Q1(s′, a′)−Q2(s′, a′)≤
max
s,aγmax
s′,a′Q1(s′, a′)−Q2(s′, a′)=γ∥Q1−Q2∥∞.
Because Sρis a contraction as shown in Lemma B.3, by the Banach theorem, it admits a unique fixed
point Q∗
ρs.t.∀s, a:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a). We now show that this fixed point is the truncated
Q-function. Define Qρ((s, b), a) =Eo∼O(s,a)b(o) +Q∗
ρ(s, a). Notice that the fixed point satisfies:
∀s∈S, a∈A:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a)(Eq. 9)=
r(s, a) +γEo,s′max
a′
Eo′ρ(s′)(o′) +Q∗
ρ(s′, a′)
=
r(s, a) +γEo,s′max
a′Qρ((s′, ρ(s′)), a′).
At the same time, by definition:
∀s∈S, a∈A:Q∗
ρ(s, a) =Qρ((s, b), a)−Eo∼O(s,a)b(o).
Combining the above two equations and swapping terms:
∀s∈S, a∈A:Qρ((s, b), a) =r(s, a) +Eo,s′[b(o) +γmax
a′Qρ((s′, ρ(s′)), a′)].
Notice that the last equation shows that Qρis the fixed point of the Bellman optimality operator
Sρ(6), i.e., Qρ=Q∗(ρ), as it satisfies the optimality equations (8). It follows that Q∗((s, b), a|
ρ) =Eob(o) +Q∗
ρ(s, a), and thus Q∗
ρsatisfies the definition of the truncated Q-function (1), i.e.,
Q∗
ρ=Q∗(ρ). The truncated Q-function is then a fixed point of a contraction operator and can be
found with Q-learning. It can also be used to compute the best-responding policy: π∗(s, b|ρ) =
arg maxa[Eob(o) +Q∗(s, a|ρ)].
B.3.2 Optimality operators in the principal’s MDP
Here we assume some fixed best-responding agent’s policy π∗(ρ)that defines a principal’s MDP.
While we could instead assume an arbitrary policy π, we are only interested in solving the principal’s
MDP as the outer level of the meta-algorithm, which always follows the inner level that outputs an
agent’s policy π∗(ρ)best-responding to some ρ.
Bellman optimality operator. Consider the principal’s optimization level (line 4 of the meta-
algorithm). Solving it implies finding a fixed point of an operator Bρ, which is the Bellman optimality
operator in the principal’s MDP defined by the agent’s policy π∗(ρ)is best-responding to some ρ.
Definition B.4. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the Bellman optimality operator Bρis defined by
(BρQ)(s, b) =Eo∼O(s,a),s′∼T(s,o)h
Rp(s, b, o ) +γmax
b′Q(s′, b′)
|a=π∗(s, b|ρ)i
,(10)
where Rp(s, b, o ) =rp(s, o)−b(o),Qis an element of a vector space QSB={S×B→R}, and
subscript ρdenotes conditioning on the agent’s best-responding policy π∗(ρ).
21
This operator is a contraction and admits a unique fixed point Q∗(π∗(ρ))that satisfies optimality
equations:
V∗(s|π∗(ρ)) = max
bQ∗(s, b|π∗(ρ)), (11)
Q∗(s, b|π∗(ρ)) =Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))
|a=π∗(s, b|ρ)i
.(12)
The policy corresponding to the fixed point is called the subgame-perfect policy ρ∗(π∗(ρ)):
∀s∈S:ρ∗(s|π∗(ρ)) = arg max
bQ∗(s, b|π∗(ρ)).
Contractual Bellman optimality operator. Here we show that the contractual Q-function
q∗(π∗(ρ))defined in the main text (2)is a fixed point of a contraction operator and thus can be found
with Q-learning.
Definition B.5. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the contractual Bellman optimality operator Hρis defined by
(Hρq)(s, ap) = max
{b|π∗(s,b|ρ)=ap}Eo∼O(s,ap),s′∼T(s,o)h
Rp(s, b, o ) +γmax
a′q(s′, a′)i
, (13)
where qis an element of a vector space QSA={S×A→R}, and ap∈Adenotes the principal’s
recommended action.
Lemma B.6. Operator Hρis a contraction in the sup-norm.
Proof. Letq1, q2∈ QSA,γ∈[0,1). The operator Hρis a contraction in the sup-norm if it satisfies
∥Hρq1− H ρq2∥∞≤γ∥q1−q2∥∞. This inequality holds because:
∥Hρq1− H ρq2∥∞= max
s,a max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q1(s′, a′)
−
max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q2(s′, a′)=
max
s,aγE[max
a′q1(s′, a′)−max
a′q2(s′, a′)]≤
max
s,aγEmax
a′q1(s′, a′)−max
a′q2(s′, a′)≤
max
s,aγEmax
a′|q1(s′, a′)−q2(s′, a′)| ≤
max
s,aγmax
s′,a′|q1(s′, a′)−q2(s′, a′)|=γ∥q1−q2∥∞.
Because Hρis a contraction as shown in Lemma B.6, by the Banach theorem, it admits a unique fixed
point q∗
ρs.t.∀s, ap:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap). We now show that this fixed point is the contractual
Q-function. Notice that the fixed point satisfies:
∀s∈S: max
apq∗
ρ(s, ap) = max
ap(Hρq∗
ρ)(s, ap)(Eq. 13)=
max
b(Hρq∗
ρ)(s, π∗(s, b|ρ)) = max
b(Hρ(Hρq∗
ρ))(s, π∗(s, b|ρ)) =···=
max
bEX
th
γtRp(st, bt, ot)|s0=s, b0=b, π∗(ρ)i
= max
bQ∗(s, b|π∗(ρ)),(14)
22
and:
∀s∈S, ap∈A:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap)(Eq. 13)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
a′q∗
ρ(s′, a′)i(Eq. 14)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))i(Eq. 12)=
max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)).(15)
Thus, q∗
ρsatisfies the definition of the contractual Q-function (2), i.e., q∗
ρ=q∗(ρ). The contractual
Q-function is then a fixed point of a contraction operator and can be found with Q-learning. The
contractual Q-function can also be used to compute the subgame-perfect principal’s policy as ρ∗(s) =
arg maxb(Hρq∗
ρ)(s, π∗(s, b|ρ)) = arg maxbQ∗(s, b|π∗(ρ)). We address computing the arg max
in Appendix B.8 using Linear Programming.
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3)
Observation B.7. A principal-agent stochastic game Gis in SPE if and only if every subgame of G
is in SPE.
Observation B.7 will be useful for the proofs in this section.
LetSt⊆Sdenote the set of all possible states at time step t. For example, S0={s0}. States in ST
are terminal by definition. We assume that sets Stare disjoint. This is without loss of generality, as
we can always redefine the state space of a finite-horizon MDP such that the assumption holds; e.g.,
by concatenating the time step to a state as snew
t= (st, t). In other words, any finite-horizon MDP
can be represented as a directed acyclic graph.
The next lemma is a precursor to proving the convergence of Algorithm 1 and concerns its single
iteration. Given a pair of policies that form an SPE in all subgames but the original game, it states
that performing one additional iteration of the algorithm (update the agent, then the principal) yields
an SPE in the game. This is because the agent observes the contract offered in a state and adapts
its action, in accordance with our definition of the agent’s MDP in Appendix B.2. In particular,
the agent’s best-responding policy is defined as π∗(s, b|ρ)foranypair(s, b), so in s0, the agent
best-responds with π∗(s0, b|ρ)for any bregardless of the principal’s policy ρ(s0).
Lemma B.8. Given a finite-horizon principal-agent stochastic game Gand a principal’s policy
ρ, if(ρ, π∗(ρ))is an SPE in all subgames with a possible exception of G(i.e., all subgames in
s∈S\ {s0}), then (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G.
Proof. Ins0, the agent observes the principal’s action. Consequently and because the agent best-
responds to ρ, it also best-responds to any {ρ′| ∀s∈S\ {s0}:ρ′(s) =ρ(s)}regardless of the
offered contract ρ′(s0), including the subgame-perfect ρ∗(π∗(ρ))(that only differs from ρins0, as
subgames in other states are in SPE already). Thus, (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G, as well as in
all subgames of G(by Observation B.7).
Corollary B.9. Given Gwith a single subgame ( S={s0}),(ρ∗(π∗(ρ)), π∗(ρ))is an SPE in Gfor
anyρ.
This corollary concerns MDPs with a single state, which could also be interpreted as stateless. This
covers static contract design problems, as well as subgames in terminal states in our model.
By using Lemma B.8, we can now show that each iteration of the algorithm expands the set of
subgames that are in SPE, as long as some subgames satisfy the conditions of the lemma for an
arbitrarily initialized ρ. This is always the case for finite-horizon MDPs, as the subgames in terminal
states have a single subgame (itself), and thus Corollary B.9 applies. This reasoning is used to prove
Theorem 3.3.
Proof of Theorem 3.3. Denote the policy initialized at line 1 as ρ0. Denote the best-responding policy
toρ0asπ1≡π∗(ρ0)and the subgame-perfect policy against π1asρ1≡ρ∗(π1). Likewise, πiand
23
ρirespectively denote the best-responding policy to ρi−1and the subgame-perfect policy against πi,
where iis an iteration of the algorithm.
By Corollary B.9, (ρ1, π1)forms an SPE in all subgames in terminal states, including s∈ST.
Applying Lemma B.8, as well as our assumption that sets Stare disjoint, (ρ2, π2)is an SPE in all
subgames in ST∪ST−1. By induction, (ρi, πi)is an SPE in all subgames in s∈ST∪ST−1··· ∪
ST−i+1. Thus, (ρT+1, πT+1)is an SPE in all subgames in s∈ST∪ ··· ∪ S0=S, and thus in the
gameG(by Observation B.7).
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4)
Consider the principal’s optimization task (line 4 of the meta-algorithm). As we discuss in Ap-
pendix B.3, solving this task can be interpreted as finding the fixed point of a contraction operator Bρ
defined in (10). By definition of contraction, this fixed point can be found by iteratively applying the
operator until convergence, which we denote as H∗=Bρ(Bρ(Bρ...Q(s, b))).
Observation B.10. H∗is a composition of linear operators and thus is a linear operator.
ForH∗to be a contraction, its fixed point has to be unique. Since its iterative application (the
meta-algorithm, Algorithm 1) converges to an SPE, we next prove the uniqueness of Q-functions in
SPE.
Lemma B.11. Given a finite-horizon principal-agent stochastic game G, the principal’s Q-function
is equal in all SPE for any state-action; the same holds for the agent’s Q-function.
Proof. Consider a principal’s policy ρthat forms SPE with any best-responding agent’s policy π∗(ρ).
Anyπ∗(ρ)solves the agent’s MDP and thus all such policies define a unique agent’s Q-function
(which is the fixed point of the Bellman optimality operator). Furthermore, by the assumption that
the agent breaks ties in favor of the principal, all best-responding policies also uniquely define the
principal’s Q-function (in other words, any policy that solves the agent’s MDP but does not maximize
the principal’s Q-function when breaking ties in some state is not a best-responding policy by the
assumed tie-breaking). Thus, for any pair of SPE with non-equal Q-functions, the principal’s policies
must also differ.
Consider two principal’s policies, ρxandρy, that form SPE with any respective best-responding
agents’ policies, π∗(ρx)andπ∗(ρy). By the above argument, the choice of π∗(ρx)andπ∗(ρy)is
inconsequential, so we can assume those to be unique (e.g. by adding lexicographic tie-breaking if
the principal-favored tie-breaking does not break all ties).
Forρxandρyto differ, there must be a state s∈Stsuch that 1) all subgames in states “after” t,
i.e.,{St′}t′>t, are in unique SPE given by some ρandπ∗(ρ)(e.g., this holds in a terminal state)
and 2) the subgame in shas two contracts, bx=ρx(s)andby=ρy(s), that both maximize the
principal’s utility, i.e., Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)). Denote the agent’s actions in s
asax=π∗(s, bx|ρ)anday=π∗(s, by|ρ). We now show that the choice between bxandbyis
inconsequential as both contracts also yield the same utility for the agent.
Assume the agent prefers bxtoby, i.e., Q∗((s, bx), ax|ρ)> Q∗((s, by), ay|ρ). First, use
the observed-action notation. Applying the Bellman optimality operator and using the defi-
nition of R, we have E[r(s, ax) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +bx(ax)>E[r(s, ay) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +by(ay). Observe that the principal may simply decrease the
payment bx(ax)by the difference of the agent’s Q-values (so that the inequality becomes equality),
increasing the principal’s utility. So, the assumption that the agent prefers bxtobymeans that neither
contract maximizes the principal’s utility in the subgame, leading to a contradiction.
The same can be shown in the hidden-action model. The agent preferring bxtoby
would mean E[r(s, ax) +bx(o) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)]>E[r(s, ay) +by(o) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)], and the principal would be able to adjust bxin order to decrease the
expected payment E[bx(o)]relatively to E[by(o)], e.g., by decreasing each non-zero payment bx(o)
by a constant. Again, this leads to a contradiction.
We thus have shown that the choice between bxandbyinsis inconsequential for the value functions
of both principal and agent in s:V∗(s|π∗(ρx)) = Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)) =
V∗(s|π∗(ρy))andV∗(s, bx|ρ) =Q∗((s, bx), ax|ρ) =Q∗((s, by), ay|ρ) =V∗(s, by|ρ). By
Bellman optimality equations ( (7)and(8)for the agent, (11) and(12) for the principal), it is also
24
inconsequential for the players’ Q-functions in all states “before” t, i.e.,{St′}t′<t. For states “after”
t, the choice also has no effect by the MDP being finite-horizon (and our w.l.o.g. assumption about
the uniqueness of states). This holds for any such bxandbyin any s. Thus, for any SPE (ρ, π∗(ρ)),
each player’s Q-function is identical in all SPE for any state-action.
Proof of Theorem 3.4. By Observation B.10, H∗is a linear operator. Moreover, as Algorithm 1
converges to SPE by Theorem 3.3 and the payoffs in SPE are unique by Lemma B.11, the iterative
application of H∗converges to a unique fixed point. By using a converse of the Banach theorem
(Theorem 1 in Daskalakis et al. [13]), this operator is a contraction under any norm that forms a
complete and proper metric space. This includes the sup-norm.
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs
Here we present an example of a hidden-action infinite-horizon principal-agent MDP where the
meta-algorithm diverges by getting stuck in a cycle. To solve the principal’s and agent’s optimization
tasks, we specifically developed exact solvers for principal’s and agent’s MDPs.
The MDP consists of two states, s1ands2. In each state, the agent has two actions, a1anda2, which
determine probabilities of sampling one of two outcomes, o1ando2. When agent chooses a1in any
states, outcomes are sampled with respective probabilities O(o1|s, a 1) = 0 .9andO(o2|s, a 1) =
0.1. Vice versa, choosing a2in any state ssamples an outcome with probabilities O(o1|s, a 2) = 0 .1
andO(o2|s, a 2) = 0 .9. After sampling an outcome oi, the MDP deterministically transitions to si
(e.g., if o1is sampled, the MDP transitions to s1regardless of the old state and the agent’s action).
Choosing an action that is more likely to change the state of the MDP (so, a2ins1anda1ins2)
requires effort from the agent, respectively costing c(s1, a2) = 1 andc(s2, a1) = 2 . The other action
is free for the agent: c(s1, a1) = 0 andc(s2, a2) = 0 . Other things equal, the principal prefers the
agent to invest an effort: it only enjoys a reward whenever the MDP transitions to a different state,
equal to rp(s1, o2) =rp(s2, o1) = 1 .5. The discount factor is set to γ= 0.9.
We now describe several iterations of the meta-algorithm, showing that it oscillates between two pairs
of players’ policies. We report the agent’s truncated Q-function (1)and the principal’s contractual
Q-function (2)at each iteration of the algorithm (rounded to three decimals). We also verify that
these Q-functions are indeed fixed points of respective operators and thus solve the respective MDPs,
but only do so in (s1, a2)as derivations in other state-action pairs are identical.
Initialization
Initialize the principal with a policy ρ0that does not offer any payments, i.e., ρ0(s1) =ρ0(s2) =
(0,0), where we denote a contract by a tuple b= (b(o1), b(o2)).
Iteration 1: agent
The agent’s best-responding policy π1simply minimizes costs by never investing an effort:
π1(s1, ρ0(s1)) =a1,π1(s2, ρ0(s2)) =a2. This corresponds to the following truncated Q-function:
Qπ1(s1, a1) =Qπ1(s2, a2) = 0 ,Qπ1(s1, a2) =−c(s1, a2) =−1andQπ1(s2, a1) =−c(s2, a1) =
−2.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−1 =Qπ1(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1·0 + 0 .9·0] =−1.
In the absence of contracts, the agent’s truncated Q-function is equal to its Q-function under the
principal’s policy: Qπ1((s, ρ 0(s)), a) =Qπ1(s, a).
Iteration 1: principal
The principal’s subgame-perfect policy ρ1attempts to incentivize effort in s1and offers the following
contracts: ρ1(s1) = (0 ,1.25),ρ1(s2) = (0 ,0). This corresponds to the following contractual Q-
function: qρ1(s1, a1) = 1 .991,qρ1(s1, a2) = 2 .048,qρ1(s2, a1) = 1 .391, and qρ1(s2, a2) = 2 .023.
25
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
2.048 = qρ1(s1, a2) =Eo,s′[−ρ1(s1)(o) +rp(s1, o) +γmax
a′qρ1(s′, a′)] =
0.1(0 + 0 + 0 .9·2.048) + 0 .9(−1.25 + 1 .5 + 0 .9·2.023) = 2 .048.
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .5,0), which is not worth it for the
principal, as evidenced by qρ1(s2, a1)< qρ1(s2, a2).
Iteration 2: agent
The principal ρ1underestimated the payment required to incentivize effort, and the agent’s best-
responding policy π2still never invests an effort: π2(s1, ρ1(s1)) = a1,π2(s2, ρ1(s2)) = a2. This
corresponds to the following truncated Q-function: Qπ2(s1, a1) = 0 .723,Qπ2(s1, a2) =−0.598,
Qπ2(s2, a1) =−1.277, and Qπ2(s2, a2) = 0 .402.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−0.598 = Qπ2(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1(0.9(0 + 0 .723) + 0 .1(1.25 + 0 .402))+
0.9(0.1(0 + 0 .723) + 0 .9(0 + 0 .402))] = −0.598.
Given the contracts from the principal’s policy ρ1, we can compute the agent’s Q-values using (1):
Qπ2((s1, ρ1(s1)), a1) = 0 .848,Qπ2((s1, ρ1(s1)), a2) = 0 .527,Qπ2((s2, ρ1(s2)), a1) =−1.277,
andQπ2((s2, ρ1(s2)), a2) = 0 .402. Observe that indeed, the agent still prefers not to invest an effort
ins1, as evidenced by Qπ2((s1, ρ1(s1)), a1)> Qπ2((s1, ρ1(s1)), a2).
Iteration 2: principal
The principal gives up on incentivizing effort and once again offers no contracts: ρ2(s1) = (0 ,0),
ρ2(s2) = (0 ,0). This corresponds to the following contractual Q-function: qρ2(s1, a1) = 1 .661,
qρ2(s1, a2) = 1 .503,qρ2(s2, a1) = 1 .422, and qρ2(s2, a2) = 1 .839.
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, to incentivize a2in
s1, the principal has to offer a contract ρ(s1) = (0 ,1.652) , which gives us:
1.503 = qρ2(s1, a2) =Eo,s′[−ρ2(s2)(o) +rp(s1, o) +γmax
a′qρ2(s′, a′)] =
0.1(0 + 0 + 0 .9·1.661) + 0 .9(−1.652 + 1 .5 + 0 .9·1.839) = 1 .503,
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .098,0), which is still not worth it for
the principal, as evidenced by qρ2(s2, a1)< qρ2(s2, a2).
Subsequent iterations
Because the principal’s subgame-perfect policy ρ2repeats the policy ρ0from a previous iteration, the
meta-algorithm is now stuck in a cycle where iterations 1 and 2 repeat infinitely. In other words, the
meta-algorithm diverges.
B.7 Meta-Algorithm in the Observed-Action Model
In the special case where the agent’s actions are observed (defined in Section 2.2 and summarized
in Table 2), the meta-algorithm can be shown to find SPE in a single (rather than T+ 1) iteration,
as we show in Theorem B.12. This property is based on the observation that the agent is indifferent
between an MDP without a principal and an MDP augmented with a subgame-perfect principal;
similar observation has been made in contemporaneous work [ 3]. Consequently, evaluating minimal
implementation only requires access to the agent’s optimal Q-function in the absence of the principal.
26
Is is also easy to show that SPE coincides with Stackelberg equilibrium in the observed-action
scenario (Lemma B.14), and consequently the meta-algorithm finds Stackelberg equilibrium.
Theorem B.12. Given a principal-agent stochastic game, G, with observed actions and either finite
or infinite horizon, if the principal’s policy is initialized to offer zero-vectors as contracts in all states,
the meta-algorithm finds SPE in one iteration.
Proof of Theorem B.12. Use the same notations of ρiandπias in the proof of Theorem 3.3 in
Appendix B.4.
After initializing ρ0(that always offers 0) and finding the best-responding agent π1, consider the
optimal payments found at the outer optimization level of Algorithm 1. Given a state s∈S, denote
the agent’s action as
a∗= arg max
aQ∗((s,0), a|ρ0).
For now, let contracts in states other than sremain 0; we will omit the conditioning of Q∗onρ0for
brevity. The optimal contract in s, denoted as b∗, reimburses the agent for taking a suboptimal action,
paying exactly
b∗(s, ap) =Q∗((s,0), a∗)−Q∗((s,0), ap)
if the agent selects ap, and pays 0otherwise. Note that b∗=0ifap=a∗. This contract makes the
agent indifferent between apanda∗because
Q∗((s, b∗), ap) =Q∗((s,0), ap) +b∗(s, ap) =Q∗((s,0), a∗),
changing the agent’s action in stoap(according to tie-breaking). However, the agent’s value function
remains unchanged:
V∗(s, b∗) =Q∗((s, b∗), ap) =Q∗((s,0), a∗) =V∗(s,0).
Thus, the Bellman optimality equations (7)and(8)still hold in all states after replacing 0withb∗in
s, and π1still best-responds to the updated principal. This replacement of zero-vectors for optimal
contracts b∗is performed in all states during the update of the principal at the outer optimization
level, yielding a principal’s policy ρ1subgame-perfect against π1. At the same time, π1remains
best-responding against ρ1. Thus, (ρ1, π1)is an SPE.
Remark B.13 .Unlike our general Theorem 3.3, the above proof relies on the specifics of our model
such as the principal’s action set and the players’ reward functions.
Lemma B.14. Given a principal-agent stochastic game, G, with observed actions, any SPE is a
Stackelberg equilibrium.
Proof. Consider an SPE. As discussed in the above proof, the contracts in SPE exactly reimburse the
agent for choosing suboptimal actions, and the agent’s value function when offered such a contract in
some state sremains the same as in the absence of the contract. Additionally, notice that the principal
may never decrease the agent’s value in any state below the value it gets in the absence of contracts
(since payments are non-negative). Thus, the principal may not deviate from SPE by decreasing
the agent’s value in any of the future states through suboptimal contracts in order to incentivize a
suboptimal action apwhile paying less in s.
On the other hand, consider the principal trying to pay less in some state sby increasing the agent’s
value in some future states. If transition function is determenistic, then in order to decrease the
payment in sby some v < b∗(ap)while still incentivizing ap, the principal must, for example,
increase the payment in s′=T(s,O(s, ap))byv/γ– which is inconsequential for the principal’s
value in s(in our model, the discount factor is the same for the principal and the agent). In case
of a stochastic transition function, the increase of payments in future states required to balance the
decrease of the payment in sbyvmay even decrease the principal’s value in scompared to SPE.
Thus, the principal may not deviate from an SPE (commit to non-credible threats) to increase its
value in the initial state, and therefore any SPE is a Stackelberg equilibrium.
27
B.8 Deriving the Linear Program (Section 4)
In Section 4, we describe an RL approach to solving the principal’s MDP that involves two interde-
pendent tasks of 1) learning a policy that the principal wants to implement and 2) computing the
contracts that do so optimally. The former is solved by learning the contractual Q-function (2), which
we derive as a fixed point of a contraction operator Hρ(13) in Appendix B.3. The latter (which is
required as a subroutine to apply Hρ) we solve using Linear Programming, akin to how the static
principal-agent problems are typically solved (as mentioned in Section 2.1).
Given a state s∈Sand an action to recommend ap∈A, rewrite the right-hand side of Hρas the
following constrained optimization problem:
max
b∈BEo∼O(s,ap),s′∼T(s,o)h
rp(s, o)−b(o) +γmax
a′q(s′, a′)i
s.t.
∀a∈A:Q∗((s, b), ap|ρ)≥Q∗((s, b), a|ρ),(16)
where the constraints explicitly require the recommended action apto be at least as ‘good’ for the
agent as any other action a. Note that rp(s, o)andq(s′, a′)are constants with respect to band can
be omitted from the objective. To see that the constraints are linear, apply the Bellman optimality
operator to the agent’s Q-function, and rewrite constraints through the truncated Q-function using (1):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(17)
Because both the objective and the conditions are linear, the problem (17) is an LP.
As discussed in Section 4, our approach to solving the agent’s optimization problem is to learn the
truncated Q-function Q∗(ρ)and transform it into the Q-function by adding the expected payment.
Note that this representation of the agent’s Q-function is used in the constraints of the above LP. The
requirement of the principal having access to the agent’s (truncated) Q-function can be seen as a
limitation of the outlined approach. A potential remedy is to instead parameterize the principal’s
Q-function Q∗(π)with a discontinuous neural network able to efficiently approximate the Q-function
and the solutions to LPs without requiring access to the agent’s private information [ 79]. Of course,
one could also directly learn Q∗(π)with simpler approaches, e.g., by discretizing the contract space
or employing deep RL | Section not found | methods for continuous action spaces (such as Deep Deterministic Policy
Gradient or Soft Actor-Critic).
Solving the LP also requires access to the outcome function O; we discuss in Appendix D.1 how
this can be circumvented by parameterizing the outcome function with an additional neural network,
trained as a probabilistic outcome classifier.
In the special case of the observed-action model, the LP has a simple solution if the agent best-
responds to a specific principal that always offers a zero-vector 0as a contract. In this solution, the
principal exactly reimburses the agent for choosing a (suboptimal) recommended action ap, and pays
0if agent chooses any other action a̸=ap. Similar observation has been made in contemporaneous
work, see end of Section 3.1 in Wu et al. [82].
C Principal-Multi-Agent Example: Prisoner’s Dilemma
Below we illustrate the multi-agent model from Section 5.1 on the example of a simple matrix game.
Consider a standard one-step Prisoner’s Dilemma with the payoff matrix as in Table 3a. Here, the
only equilibrium is mutual defection (DD), despite cooperation (CC) being mutually beneficial. How
should a benevolent principal change the matrix through payments to incentivize cooperation?
One answer is that CC should become an equilibrium through minimal payments in CC. In one of
the payment schemes that achieve this, the principal pays a unit of utility to both players for the
28
Table 3: Prisoner’s Dilemma as a principal-multi-agent game. ‘Def’ denotes ‘Defect’ and ‘Coop’
denotes ‘Cooperate’. Blue highlights principal’s changes of agents’ payoffs.
(a) no payments (b) arbitrary payments in SPE (c) IC payments in SPE
Def Coop
Def 2, 2 4, 0
Coop 0, 4 3, 3Def Coop
Def 2, 2 4, 0
Coop 0, 4 4, 4Def Coop
Def 2, 2 4, 2
Coop 2, 4 4, 4
CC outcome, resulting in the payoff matrix as in Table 3b.8However, note that DD remains an
equilibrium for the agents. In fact, the new payoff matrix is also a social dilemma known as the Stag
Hunt. In the context of (decentralized) learning, there is no reason to expect the agents to converge
to CC instead of DD, and convergence to suboptimal equilibria has been observed empirically in
generalized Stag Hunt games [58].
As a more robust approach, the principal can make action C dominant. This is stronger than just
making CC an equilibrium because each agent will prefer action C regardless of the actions of others.
To achieve this, in addition to paying a unit of utility to both agents in CC, the principal pays two units
of utility to the cooperating agent in CD and DC, resulting in the payoff matrix as in Table 3c. This is
the kind of solution we implement in our application to SSDs, where we formulate the principal’s
objective as learning a social welfare maximizing strategy profile and its minimal implementation.
Importantly, in the context of our principal-agent model, the minimal implementation is consistent
with SPE in that the principal minimizes payments when agents best-respond by following recom-
mendations (CC in our example). So the IC property is an additional constraint, which specifies
an otherwise ambiguous objective of finding the principal’s policy in SPE, and which only requires
additional payments in equilibrium.
Note that in our example, the payment to each agent for the same action depends on the other agent’s
action (e.g., the row agent receives +2 in CD and +1 in CC). This dependence on other agents is
even more pronounced in stochastic games, where payments of a minimal implementation condition
on the policies of others – not only on their immediate actions in the current state but also on their
actions in all possible future states.9For this reason, learning the precise minimal implementation
is generally impractical: consider a neural network used for contract estimation for some agent
explicitly conditioning on the parameters of neural networks of all other agents, or on their actions in
all states of the MDP.
As a tractable alternative, we use a simple approximation that performs well in our experiments.
Specifically, we train the principal assuming that each agent sticks to one of two policies: either
always follow the principal’s recommendations and get paid, or ignore them and act independently as
if there is no principal. In equilibrium, both policies maximize the agent’s welfare, which justifies the
assumption. For implementation details of this approximation, see Appendix D.2.
D Experiments
D.1 Experiments in Tree MDPs
In this section, we empirically test the convergence of Algorithm 1 towards SPE in hidden-action
MDPs. We experiment with a small variation on the algorithm, which expedites convergence: the
agent and principal policies are updated simultaneously instead of iteratively. This can be seen as
terminating inner and outer tasks early, after one update, leading to approximately optimal policies.
Environment. In these experiments, we simulate a multi-stage project in which the principal offers
contracts at intermediate stages, influencing the agent’s choice of effort. Specifically, we model an
MDP that is a complete binary tree, where the agent’s decisions at each state are binary, representing
8Unlike the single-agent model, the optimal payment scheme here is ambiguous. Any payment scheme that
gives a unit of utility to both agents in CC and no utility to a defecting agent in DC and CD forms an SPE when
coupled with best-responding agents: CC becomes an equilibrium, the payments in which are minimized.
9Here we refer to the dependence of value functions on π−iin the IC constraints (5).
29
Algorithm 2 A deep Q-learning implementation of Algorithm 1 in the single-agent setting
Require: principal’s Q-network θ, agent’s Q-network ϕ, target networks θ′andϕ′, replay buffer RB
1:Initialize buffer RBwith random transitions, networks θandϕwith random parameters
2:fornumber of updates do ▷Training loop
3: fornumber of interactions per update do ▷Interact with the MDP
4: Select an action to recommend, ap, with qθ(s, a)viaϵ-greedy
5: Sample o∼ O(s, a),ra=r(s, a),rp=rp(s, o), transition the MDP to s′∼ T(s, o)
6: Add the transition (s, ap, ra, rp, o, d, s′)to the buffer RB
7: Ifd= 1, reset the MDP ▷ dis a binary ‘done’ variable indicating termination
8: Sample a mini-batch of transitions mb∼RB
9: for(s, ap, ra, rp, o, d, s′)∈mbdo ▷Estimate target variables to update θandϕ
10: ap′= arg maxa′qθ(s′, a′) ▷Select the next action for Q-learning updates
11: Find optimal contracts b∗(s, ap)andb∗(s′, ap′)by solving LP (17)
12: yp(s, ap) =rp−b∗(s, ap, o) +γ(1−d)qθ′(s′, ap′)
13: ya(s, ap) =ra+γ(1−d)(Eo′∼O(s′,ap′)b∗(s′, ap′, o′) +Qϕ′
(s′, ap′))
14: Minimize L(θ) =P
mb
qθ(s, ap)−yp(s, ap)2▷Update θas DQN
15: Minimize L(ϕ) =P
mb
Qϕ(s, ap)−ya(s, ap)2
▷Update ϕas DQN
high or low effort, and correspond to good or bad outcomes with different probabilities. This is an
intentionally simple environment, allowing us to compare with precise ground truth.
The MDP is represented by a complete binary decision tree with depth 10, resulting in 1023 states.
In each state, the agent may take two actions, a0anda1, which may result in two outcomes, o0and
o1. The action a0 | Section not found | data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity | Section not found | results of Gerstgrasser
and Parkes [24]. Specifically, their Theorem 2 presents an example where RL fails to converge to a
Stackelberg equilibrium if the agent ‘immediately’ best responds. This procedure is our Algorithm 1,
with agent optimization solved by an oracle and principal optimization performed with RL. Our
Theorem 3.3 complements their negative result by showing that such a procedure converges to SPE.
Finally, while we focus on finite-horizon hidden-action MDPs in the main text, we also analyze the
other scenarios in the Appendix. Our | findings are summarized in Table 1.
4 Learning Setting
In this section, we develop an RL approach to principal-agent MDPs by solving both inner and
outer optimization tasks of the meta-algorithm with Q-learning. These tasks correspond to finding
optimal policies in the respective agent’s and principal’s MDPs defined in Observation 3.1. We
operate in a standard model-free RL setting, where learning is performed through interactions with a
black-box MDP. For both principal and agent, we introduce modified Q-functions, which we formally
derive as fixed points of contraction operators in Appendix B.3. We detail deep implementations in
Appendix D. Our approach consists of the following two-phase setup:
1.Training: Principal’s policy is trained ‘for free’ in simulated interactions with agent and
MDP. Principal has access to the learning agent and essentially controls it.
2.Execution / Validation: Trained principal’s policy can be executed or validated against a
black-box (possibly learning) agent.
This is in contrast with the online setup where the principal interacts with an actual black-box agent
during learning, incurring losses from payments in the process [ 31,92]. On the other hand, this setup
is one step ahead of the MARL literature adjacent to our application in Section 5, where the analysis
is typically limited to the training phase.
Agent’s perspective. Consider the agent’s MDP defined by principal’s policy ρ. The best-responding
agent’s Q-function in a state s,Q∗((s, b), a|ρ), depends on the observed contract b– particularly on
the expected payment. This effect can be isolated by applying Bellman optimality operator:
Q∗((s, b), a|ρ) =Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ), (1)
where Q∗(s, a|ρ) = [r(s, a)+γEmax a′Q∗((s′, ρ(s′)), a′|ρ)]is the truncated optimal Q-function,
which represents agent’s expected long-term utility barring the immediate payment. Our approach to
training the agent (solving inner optimization) is to learn the truncated Q-function and compute the
Q-function through (1). This way, the Q-function is defined for any b∈Bins, under an assumption
that the principal plays according to ρin future (e.g., ρ(s′)in the next state). From the agent’s
perspective, this is justified in SPE, where ρis optimal for the principal in all future subgames. Note
that computing the expected payment requires the outcome distribution – if unknown, it can be
approximated as a probabilistic classifier (more on this in Appendix D.1).
Principal’s perspective. Consider the principal’s MDP defined by a best-responding agent π∗(ρ)for
an arbitrary ρ. The basic idea is to divide the principal’s learning problem into two parts: 1) learn the
6
agent’s policy that the principal wants to implement ( recommends to the agent), and 2) compute the
optimal contracts that implement it (the minimal implementation ) using Linear Programming (LP).
Essentially, this extends the classic LP approach from static contract design described in Section 2.1.
To approach the first subproblem, we need an analogue of the principal’s Q-function that is a function
of an agent’s action. To this end, we define the contractual Q-function q∗(π∗(ρ)) :S×A→Rby
q∗(s, ap|π∗(ρ)) = max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)), (2)
which can be interpreted in sas the maximal principal’s Q-value that can be achieved by implementing
ap∈A. To compute the optimal contract arg maxbQ∗(s, b|ρ)using q∗(π∗(ρ)), we can select
the optimal action to implement as arg maxapq∗(s, ap|π∗(ρ)), and then find the corresponding
contract as solution to the conditional maximization in (2). This conditional maximization is the
second subproblem defined above. We solve it as LP (for details, see Appendix B.8):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(3)
Solving this LP requires access to the agent’s truncated Q-function Q∗. Although this requirement
is in line with the training phase of our setup, it can be alleviated, e.g., by approximating optimal
contracts with deep learning [ 79]. We do not explore this direction, so as to not conflate the distinct
learning problems originating from our MDP formulation and the agent being black-box.
Practical concerns. The above instantiation of the meta-algorithm assumes that Q-learning is
run until convergence to precisely solve both inner and outer optimization tasks. In practice, one
has to terminate early and approximate; in case of using deep RL, function approximation also
contributes to the error. In our model, even a small error can have a devastating effect because the
principal’s Q-function is discontinuous : a misestimation of the optimal contract (however slight) may
change the agent’s action, resulting in a worse outcome (see also [ 79]). We empirically validate the
robustness of our implementation to this effect: In Appendix D.1, we apply it to solve toy tree MDPs
(generalizations of Figure 1). Furthermore, our multi-agent experiments in Section 5.3 are validated
in a complex and highly combinatorial sequential social dilemma. We report additional multi-agent
experiments in Appendix D.2, where we apply a form of nudging the agents to desirable behaviour
through extra payments, which helps counteract the degrading effect of approximation errors.
5 Extension to Multi-Agent RL
In this section, we explore an extension to multiple agents. We state the formal model in Section 5.1.
We introduce sequential social dilemmas (SSDs) and the Coin Game (in Section 5.2). We present
experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this appendix, we provide formal proofs and derivations for the results in Sections 3 and 4.
Appendix B.1 provides additional intuition on the differences between the solution concepts of
Stackelberg and Subgame-Perfect Equilibria. Appendix B.2 supplements Observation 3.1 and defines
the principal’s and agent’s MDPs. Appendix B.3 defines contraction operators useful for succeeding
proofs and connects these operators to the modified Q-functions defined in Section 4. Appendices
B.4 and B.5 present the respective proofs of Theorems 3.3 and 3.4. While the theory in the main
text focuses on the finite-horizon hidden-action scenario, we also discuss the infinite-horizon and
observed-action scenarios in appendices B.6 and B.7, respectively. Finally, the linear program
formulated in Section 4 is derived and described in more detail in Appendix B.8.
Table 2 summarizes the differences between standard MDPs and Principal-Agent MDPs with and
without hidden actions.
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited)
First, consider the SPE notion: At the left subgame, the principal incentivizes the agent to take
noisy-left by choosing a contract that pays 1for outcome Land0otherwise. This way, both actions
yield the same value for the agent, 0.9·1 + 0 .1·0−0.8 = 0 .1·1 + 0 .9·0 = 0 .1, and the
agent chooses aLby tie-breaking in favour of the principal. So the principal’s value in state sLis
0.9(rp(sL, L)−1) = 0 .9(14
9−1) = 0 .5. By the same logic, the principal offers the same contract
insRand its value equals 0.5(and the agent’s value equals 0.1). Then, in s0, the agent is indifferent
between transitioning to sLandsR, so the principal has to offer the same contract again. The
principal’s value in s0(given that the agent chooses aL) is0.5 + 0 .9·0.5 + 0 .1·0.5 = 1 , and the
agent’s value is 0.1 + 0 .9·0.1 + 0 .1·0.1 = 0 .2. These are estimated by considering utilities in sL
andsRwithout discounting (using γ= 1). Note that in this analysis, we found SPE using backward
induction: we first analyzed the terminal states, then the root state.
18
Compare this with Stackelberg: If non-credible threats were allowed, the principal could threaten to
act suboptimally in the right subgame by always paying the agent 0. Both principal and agent then
value sRat0. InsL, the contract is the same as in SPE. Knowing this, the agent values sLoversR
(0.1>0), which would drive it to choose the noisy-left action at the root state even if the principal
pays only 1−0.1 = 0 .9for outcome L. By paying less, the principal’s utility (value in s0) would be
higher compared to SPE, (14
9−0.9 + 0 .5)·0.9 = 1 .04>1.
This illustrates how Stackelberg equilibrium may produce more utility for the principal, but the
surplus comes at the cost of the inability to engage in mutually beneficial contractual agreements
in certain subgames, even if these subgames are reached by pure chance and despite the agent’s
best efforts. On the one hand, Stackelberg requires more commitment power from the principal.
Whereas in SPE the agent can be certain that the principal sticks to its policy in future states because
it is optimal in any subgame, in Stackelberg, the principal has to preemptively commit to inefficient
contracts and ignore potential beneficial deviations. On the other hand, Stackelberg is not robust to
mistakes: if the agent mistakenly chooses the wrong action, it might be punished by the principal,
losing utility for both players. This is especially concerning in the context of learning, where mistakes
can happen due to approximation errors, or even due to the agent exploring (in online setups). SPE is
hence a more practical solution concept.
B.2 Principal’s and Agent’s MDPs (Observation 3.1)
A (standard) MDP is a tuple (S, S 0, A,R,T, γ), where Sis a set of states, S0∈Sis a set of
possible initial states, Ais a set of actions, T:S×A→∆(S)is a stochastic transition function,
R:S×A×S→ P(R)is a stochastic reward function ( R(s, a, s′)is a distribution and may depend
on the next state s′),γis an (optional) discounting factor. Assume finite horizon (as in Section 2).
Consider a hidden-action principal-agent MDP M= (S, s 0, A, B, O, O,R,Rp,T, γ)as defined in
Section 2. First, consider the agent’s perspective. Let the principal’s policy be some ρ. This defines
a standard MDP (Sa, Sa
0, A,Ra,Ta, γ)that we call the agent’s MDP, where: The set of states is
Sa=S×B(infinite unless Bis discretized). The set of initial states is S0={s0} ×B. The set of
actions is A.
The transition function Ta:Sa×A→∆(Sa)defines distributions over next state-contract pairs
(s′, ρ(s′)), where s′∼ T(s, o∼ O(s, a)). Note that the next state s′is sampled from a distribution
that is a function of state-action pairs (s, a)marginalized over outcomes, and the next contract ρ(s′)
is given by the principal’s policy. Informally, the agent expects the principal to stick to its policy
in any future state. At the same time, since the state space Sais defined over the set of contracts
B, the agent may adapt its policy to any immediate contract in the current state, and thus its policy
π:Sa→∆(A)is defined by π(s, b)for any b∈B.
The reward function is a bit cumbersome to formalize because it should not depend on outcomes,
while both OandTcan be stochastic. Specifically, the new reward function has to be stochastic
w.r.t. outcomes: Ra((s, b), a, s′) = [ r(s, a) +b(o)|o∼P(o|s, a, s′)], where the conditional
distribution of outcomes is given by P(o|s, a, s′) =P(O(s,a)=o)P(T(s,o)=s′)P
o∗P(O(s,a)=o∗)P(T(s,o∗)=s′).
Next, consider the principal’s perspective. Let the agent’s policy be some π. This defines a standard
MDP (S,{s0}, B,Rp,Tp, γ)that we call the principal’s MDP, where: the set of states is S; the set
of initial states is {s0}; the set of actions is B(infinite unless discretized); the transition function is
defined by Tp(s, b) =T(s, o∼ O(s, a∼π(s, b))); the reward function is defined similarly to the
agent’s MDP by Rp(s, b, s′) = [r(s, o)−b(o)|o∼P(o|s, a, s′)].
Thus, the optimization task of the principal (agent) given a fixed policy of the agent (principal) can be
cast as a standard single-agent MDP. In both players’ MDPs, the other player’s presence is implicit,
embedded into transition and reward functions. Note that our definition of standard MDP allows for
stochastic reward functions that depend on the next state, as well as a set of initial states that is not
a singleton. The same generalizations can be made in our Principal-Agent MDP definition, and in
particular, the above derivations would still hold, but we decided to slightly specify our model for
brevity.
19
B.3 Contraction Operators and their Fixed Points
Our meta-algorithm iteratively solves a sequence of principal’s and agent’s MDPs as defined in
Appendix B.2. Both tasks can be performed with Q-learning and interpreted as finding fixed points
of the Bellman optimality operator in the respective MDPs. Furthermore, our learning approach in
Section 4 makes use of modified Q-functions, which are also fixed points of contraction operators.
For convenience, we define all four operators below. Where necessary, we prove the operators being
contractions and define their fixed points.
B.3.1 Optimality operators in the agent’s MDP
Here we assume some fixed principal’s policy ρthat defines an agent’s MDP.
Bellman optimality operator. Consider the agent’s optimization task (line 3 of the meta-algorithm).
Solving it implies finding a fixed point of an operator Sρ, which is the Bellman optimality operator in
the agent’s MDP defined by a principal’s policy ρ.
Definition B.1. Given an agent’s MDP defined by a principal’s policy ρ, the Bellman optimality
operator Sρis defined by
(SρQ)((s, b), a) =Eo∼O(s,a),s′∼T(s,o)h
R(s, a, b, o ) +γmax
a′Q((s′, ρ(s′)), a′)i
, (6)
whereR(s, a, b, o ) =r(s, a) +b(o),Qis an element of a vector space QSBA={S×B×A→R},
and subscript ρdenotes conditioning on the principal’s policy ρ.
This operator is a contraction and admits a unique fixed point Q∗(ρ)that satisfies:
V∗(s, b|ρ) = max
aQ∗((s, b), a|ρ), (7)
Q∗((s, b), a|ρ) =Eh
R(s, a, b, o ) +γmax
a′Q∗((s′, ρ(s′)), a′|ρ)i
. (8)
The policy corresponding to the fixed point is called the best-responding policy π∗(ρ):
∀s∈S, b∈B:π∗(s, b|ρ) = arg max
aQ∗((s, b), a|ρ),
where ties are broken in favour of the principal.
Truncated Bellman optimality operator. Here we show that the truncated Q-function Q∗(ρ)
defined in the main text (1)is a fixed point of a contraction operator and thus can be found with
Q-learning.
Definition B.2. Given an agent’s MDP defined by principal’s policy ρ, the truncated Bellman
optimality operator Sρis defined by
(SρQ)(s, a) =r(s, a) +γEo∼O(s,a),s′∼T(s,o)max
a′
Eo′∼O(s′,a′)ρ(s′)(o′) +Q(s′, a′)
,(9)
where Qis an element of a vector space QSA={S×A→R}.
Lemma B.3. Operator Sρis a contraction in the sup-norm.7
Proof. LetQ1,Q2∈ QSA,γ∈[0,1). The operator Sρis a contraction in the sup-norm if it satisfies
∥SρQ1−SρQ2∥∞≤γ∥Q1−Q2∥∞. This inequality holds because:
7In lemmas B.3 and B.6, we show for a case that includes finite- and infinite-horizon MDPs, but requires
γ < 1. For γ= 1and finite-horizon MDPs, per-timestep operators can be shown to be contractions, similar to
the Bellman operator in chapter 4.3 of Puterman [60].
20
∥SρQ1−SρQ2∥∞= max
s,aγEo,s′
max
a′(Eo′ρ(s′)(o′) +Q1(s′, a′))−
max
a′(Eo′ρ(s′)(o′) +Q2(s′, a′))
+r(s, a)−r(s, a)≤
max
s,aγEo,s′max
a′Eo′
ρ(s′)(o′) +Q1(s′, a′)−ρ(s′)(o′)−Q2(s′, a′)=
max
s,aγEo,s′max
a′
Q1(s′, a′)−Q2(s′, a′)≤
max
s,aγmax
s′,a′Q1(s′, a′)−Q2(s′, a′)=γ∥Q1−Q2∥∞.
Because Sρis a contraction as shown in Lemma B.3, by the Banach theorem, it admits a unique fixed
point Q∗
ρs.t.∀s, a:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a). We now show that this fixed point is the truncated
Q-function. Define Qρ((s, b), a) =Eo∼O(s,a)b(o) +Q∗
ρ(s, a). Notice that the fixed point satisfies:
∀s∈S, a∈A:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a)(Eq. 9)=
r(s, a) +γEo,s′max
a′
Eo′ρ(s′)(o′) +Q∗
ρ(s′, a′)
=
r(s, a) +γEo,s′max
a′Qρ((s′, ρ(s′)), a′).
At the same time, by definition:
∀s∈S, a∈A:Q∗
ρ(s, a) =Qρ((s, b), a)−Eo∼O(s,a)b(o).
Combining the above two equations and swapping terms:
∀s∈S, a∈A:Qρ((s, b), a) =r(s, a) +Eo,s′[b(o) +γmax
a′Qρ((s′, ρ(s′)), a′)].
Notice that the last equation shows that Qρis the fixed point of the Bellman optimality operator
Sρ(6), i.e., Qρ=Q∗(ρ), as it satisfies the optimality equations (8). It follows that Q∗((s, b), a|
ρ) =Eob(o) +Q∗
ρ(s, a), and thus Q∗
ρsatisfies the definition of the truncated Q-function (1), i.e.,
Q∗
ρ=Q∗(ρ). The truncated Q-function is then a fixed point of a contraction operator and can be
found with Q-learning. It can also be used to compute the best-responding policy: π∗(s, b|ρ) =
arg maxa[Eob(o) +Q∗(s, a|ρ)].
B.3.2 Optimality operators in the principal’s MDP
Here we assume some fixed best-responding agent’s policy π∗(ρ)that defines a principal’s MDP.
While we could instead assume an arbitrary policy π, we are only interested in solving the principal’s
MDP as the outer level of the meta-algorithm, which always follows the inner level that outputs an
agent’s policy π∗(ρ)best-responding to some ρ.
Bellman optimality operator. Consider the principal’s optimization level (line 4 of the meta-
algorithm). Solving it implies finding a fixed point of an operator Bρ, which is the Bellman optimality
operator in the principal’s MDP defined by the agent’s policy π∗(ρ)is best-responding to some ρ.
Definition B.4. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the Bellman optimality operator Bρis defined by
(BρQ)(s, b) =Eo∼O(s,a),s′∼T(s,o)h
Rp(s, b, o ) +γmax
b′Q(s′, b′)
|a=π∗(s, b|ρ)i
,(10)
where Rp(s, b, o ) =rp(s, o)−b(o),Qis an element of a vector space QSB={S×B→R}, and
subscript ρdenotes conditioning on the agent’s best-responding policy π∗(ρ).
21
This operator is a contraction and admits a unique fixed point Q∗(π∗(ρ))that satisfies optimality
equations:
V∗(s|π∗(ρ)) = max
bQ∗(s, b|π∗(ρ)), (11)
Q∗(s, b|π∗(ρ)) =Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))
|a=π∗(s, b|ρ)i
.(12)
The policy corresponding to the fixed point is called the subgame-perfect policy ρ∗(π∗(ρ)):
∀s∈S:ρ∗(s|π∗(ρ)) = arg max
bQ∗(s, b|π∗(ρ)).
Contractual Bellman optimality operator. Here we show that the contractual Q-function
q∗(π∗(ρ))defined in the main text (2)is a fixed point of a contraction operator and thus can be found
with Q-learning.
Definition B.5. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the contractual Bellman optimality operator Hρis defined by
(Hρq)(s, ap) = max
{b|π∗(s,b|ρ)=ap}Eo∼O(s,ap),s′∼T(s,o)h
Rp(s, b, o ) +γmax
a′q(s′, a′)i
, (13)
where qis an element of a vector space QSA={S×A→R}, and ap∈Adenotes the principal’s
recommended action.
Lemma B.6. Operator Hρis a contraction in the sup-norm.
Proof. Letq1, q2∈ QSA,γ∈[0,1). The operator Hρis a contraction in the sup-norm if it satisfies
∥Hρq1− H ρq2∥∞≤γ∥q1−q2∥∞. This inequality holds because:
∥Hρq1− H ρq2∥∞= max
s,a max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q1(s′, a′)
−
max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q2(s′, a′)=
max
s,aγE[max
a′q1(s′, a′)−max
a′q2(s′, a′)]≤
max
s,aγEmax
a′q1(s′, a′)−max
a′q2(s′, a′)≤
max
s,aγEmax
a′|q1(s′, a′)−q2(s′, a′)| ≤
max
s,aγmax
s′,a′|q1(s′, a′)−q2(s′, a′)|=γ∥q1−q2∥∞.
Because Hρis a contraction as shown in Lemma B.6, by the Banach theorem, it admits a unique fixed
point q∗
ρs.t.∀s, ap:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap). We now show that this fixed point is the contractual
Q-function. Notice that the fixed point satisfies:
∀s∈S: max
apq∗
ρ(s, ap) = max
ap(Hρq∗
ρ)(s, ap)(Eq. 13)=
max
b(Hρq∗
ρ)(s, π∗(s, b|ρ)) = max
b(Hρ(Hρq∗
ρ))(s, π∗(s, b|ρ)) =···=
max
bEX
th
γtRp(st, bt, ot)|s0=s, b0=b, π∗(ρ)i
= max
bQ∗(s, b|π∗(ρ)),(14)
22
and:
∀s∈S, ap∈A:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap)(Eq. 13)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
a′q∗
ρ(s′, a′)i(Eq. 14)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))i(Eq. 12)=
max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)).(15)
Thus, q∗
ρsatisfies the definition of the contractual Q-function (2), i.e., q∗
ρ=q∗(ρ). The contractual
Q-function is then a fixed point of a contraction operator and can be found with Q-learning. The
contractual Q-function can also be used to compute the subgame-perfect principal’s policy as ρ∗(s) =
arg maxb(Hρq∗
ρ)(s, π∗(s, b|ρ)) = arg maxbQ∗(s, b|π∗(ρ)). We address computing the arg max
in Appendix B.8 using Linear Programming.
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3)
Observation B.7. A principal-agent stochastic game Gis in SPE if and only if every subgame of G
is in SPE.
Observation B.7 will be useful for the proofs in this section.
LetSt⊆Sdenote the set of all possible states at time step t. For example, S0={s0}. States in ST
are terminal by definition. We assume that sets Stare disjoint. This is without loss of generality, as
we can always redefine the state space of a finite-horizon MDP such that the assumption holds; e.g.,
by concatenating the time step to a state as snew
t= (st, t). In other words, any finite-horizon MDP
can be represented as a directed acyclic graph.
The next lemma is a precursor to proving the convergence of Algorithm 1 and concerns its single
iteration. Given a pair of policies that form an SPE in all subgames but the original game, it states
that performing one additional iteration of the algorithm (update the agent, then the principal) yields
an SPE in the game. This is because the agent observes the contract offered in a state and adapts
its action, in accordance with our definition of the agent’s MDP in Appendix B.2. In particular,
the agent’s best-responding policy is defined as π∗(s, b|ρ)foranypair(s, b), so in s0, the agent
best-responds with π∗(s0, b|ρ)for any bregardless of the principal’s policy ρ(s0).
Lemma B.8. Given a finite-horizon principal-agent stochastic game Gand a principal’s policy
ρ, if(ρ, π∗(ρ))is an SPE in all subgames with a possible exception of G(i.e., all subgames in
s∈S\ {s0}), then (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G.
Proof. Ins0, the agent observes the principal’s action. Consequently and because the agent best-
responds to ρ, it also best-responds to any {ρ′| ∀s∈S\ {s0}:ρ′(s) =ρ(s)}regardless of the
offered contract ρ′(s0), including the subgame-perfect ρ∗(π∗(ρ))(that only differs from ρins0, as
subgames in other states are in SPE already). Thus, (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G, as well as in
all subgames of G(by Observation B.7).
Corollary B.9. Given Gwith a single subgame ( S={s0}),(ρ∗(π∗(ρ)), π∗(ρ))is an SPE in Gfor
anyρ.
This corollary concerns MDPs with a single state, which could also be interpreted as stateless. This
covers static contract design problems, as well as subgames in terminal states in our model.
By using Lemma B.8, we can now show that each iteration of the algorithm expands the set of
subgames that are in SPE, as long as some subgames satisfy the conditions of the lemma for an
arbitrarily initialized ρ. This is always the case for finite-horizon MDPs, as the subgames in terminal
states have a single subgame (itself), and thus Corollary B.9 applies. This reasoning is used to prove
Theorem 3.3.
Proof of Theorem 3.3. Denote the policy initialized at line 1 as ρ0. Denote the best-responding policy
toρ0asπ1≡π∗(ρ0)and the subgame-perfect policy against π1asρ1≡ρ∗(π1). Likewise, πiand
23
ρirespectively denote the best-responding policy to ρi−1and the subgame-perfect policy against πi,
where iis an iteration of the algorithm.
By Corollary B.9, (ρ1, π1)forms an SPE in all subgames in terminal states, including s∈ST.
Applying Lemma B.8, as well as our assumption that sets Stare disjoint, (ρ2, π2)is an SPE in all
subgames in ST∪ST−1. By induction, (ρi, πi)is an SPE in all subgames in s∈ST∪ST−1··· ∪
ST−i+1. Thus, (ρT+1, πT+1)is an SPE in all subgames in s∈ST∪ ··· ∪ S0=S, and thus in the
gameG(by Observation B.7).
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4)
Consider the principal’s optimization task (line 4 of the meta-algorithm). As we discuss in Ap-
pendix B.3, solving this task can be interpreted as finding the fixed point of a contraction operator Bρ
defined in (10). By definition of contraction, this fixed point can be found by iteratively applying the
operator until convergence, which we denote as H∗=Bρ(Bρ(Bρ...Q(s, b))).
Observation B.10. H∗is a composition of linear operators and thus is a linear operator.
ForH∗to be a contraction, its fixed point has to be unique. Since its iterative application (the
meta-algorithm, Algorithm 1) converges to an SPE, we next prove the uniqueness of Q-functions in
SPE.
Lemma B.11. Given a finite-horizon principal-agent stochastic game G, the principal’s Q-function
is equal in all SPE for any state-action; the same holds for the agent’s Q-function.
Proof. Consider a principal’s policy ρthat forms SPE with any best-responding agent’s policy π∗(ρ).
Anyπ∗(ρ)solves the agent’s MDP and thus all such policies define a unique agent’s Q-function
(which is the fixed point of the Bellman optimality operator). Furthermore, by the assumption that
the agent breaks ties in favor of the principal, all best-responding policies also uniquely define the
principal’s Q-function (in other words, any policy that solves the agent’s MDP but does not maximize
the principal’s Q-function when breaking ties in some state is not a best-responding policy by the
assumed tie-breaking). Thus, for any pair of SPE with non-equal Q-functions, the principal’s policies
must also differ.
Consider two principal’s policies, ρxandρy, that form SPE with any respective best-responding
agents’ policies, π∗(ρx)andπ∗(ρy). By the above argument, the choice of π∗(ρx)andπ∗(ρy)is
inconsequential, so we can assume those to be unique (e.g. by adding lexicographic tie-breaking if
the principal-favored tie-breaking does not break all ties).
Forρxandρyto differ, there must be a state s∈Stsuch that 1) all subgames in states “after” t,
i.e.,{St′}t′>t, are in unique SPE given by some ρandπ∗(ρ)(e.g., this holds in a terminal state)
and 2) the subgame in shas two contracts, bx=ρx(s)andby=ρy(s), that both maximize the
principal’s utility, i.e., Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)). Denote the agent’s actions in s
asax=π∗(s, bx|ρ)anday=π∗(s, by|ρ). We now show that the choice between bxandbyis
inconsequential as both contracts also yield the same utility for the agent.
Assume the agent prefers bxtoby, i.e., Q∗((s, bx), ax|ρ)> Q∗((s, by), ay|ρ). First, use
the observed-action notation. Applying the Bellman optimality operator and using the defi-
nition of R, we have E[r(s, ax) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +bx(ax)>E[r(s, ay) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +by(ay). Observe that the principal may simply decrease the
payment bx(ax)by the difference of the agent’s Q-values (so that the inequality becomes equality),
increasing the principal’s utility. So, the assumption that the agent prefers bxtobymeans that neither
contract maximizes the principal’s utility in the subgame, leading to a contradiction.
The same can be shown in the hidden-action model. The agent preferring bxtoby
would mean E[r(s, ax) +bx(o) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)]>E[r(s, ay) +by(o) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)], and the principal would be able to adjust bxin order to decrease the
expected payment E[bx(o)]relatively to E[by(o)], e.g., by decreasing each non-zero payment bx(o)
by a constant. Again, this leads to a contradiction.
We thus have shown that the choice between bxandbyinsis inconsequential for the value functions
of both principal and agent in s:V∗(s|π∗(ρx)) = Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)) =
V∗(s|π∗(ρy))andV∗(s, bx|ρ) =Q∗((s, bx), ax|ρ) =Q∗((s, by), ay|ρ) =V∗(s, by|ρ). By
Bellman optimality equations ( (7)and(8)for the agent, (11) and(12) for the principal), it is also
24
inconsequential for the players’ Q-functions in all states “before” t, i.e.,{St′}t′<t. For states “after”
t, the choice also has no effect by the MDP being finite-horizon (and our w.l.o.g. assumption about
the uniqueness of states). This holds for any such bxandbyin any s. Thus, for any SPE (ρ, π∗(ρ)),
each player’s Q-function is identical in all SPE for any state-action.
Proof of Theorem 3.4. By Observation B.10, H∗is a linear operator. Moreover, as Algorithm 1
converges to SPE by Theorem 3.3 and the payoffs in SPE are unique by Lemma B.11, the iterative
application of H∗converges to a unique fixed point. By using a converse of the Banach theorem
(Theorem 1 in Daskalakis et al. [13]), this operator is a contraction under any norm that forms a
complete and proper metric space. This includes the sup-norm.
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs
Here we present an example of a hidden-action infinite-horizon principal-agent MDP where the
meta-algorithm diverges by getting stuck in a cycle. To solve the principal’s and agent’s optimization
tasks, we specifically developed exact solvers for principal’s and agent’s MDPs.
The MDP consists of two states, s1ands2. In each state, the agent has two actions, a1anda2, which
determine probabilities of sampling one of two outcomes, o1ando2. When agent chooses a1in any
states, outcomes are sampled with respective probabilities O(o1|s, a 1) = 0 .9andO(o2|s, a 1) =
0.1. Vice versa, choosing a2in any state ssamples an outcome with probabilities O(o1|s, a 2) = 0 .1
andO(o2|s, a 2) = 0 .9. After sampling an outcome oi, the MDP deterministically transitions to si
(e.g., if o1is sampled, the MDP transitions to s1regardless of the old state and the agent’s action).
Choosing an action that is more likely to change the state of the MDP (so, a2ins1anda1ins2)
requires effort from the agent, respectively costing c(s1, a2) = 1 andc(s2, a1) = 2 . The other action
is free for the agent: c(s1, a1) = 0 andc(s2, a2) = 0 . Other things equal, the principal prefers the
agent to invest an effort: it only enjoys a reward whenever the MDP transitions to a different state,
equal to rp(s1, o2) =rp(s2, o1) = 1 .5. The discount factor is set to γ= 0.9.
We now describe several iterations of the meta-algorithm, showing that it oscillates between two pairs
of players’ policies. We report the agent’s truncated Q-function (1)and the principal’s contractual
Q-function (2)at each iteration of the algorithm (rounded to three decimals). We also verify that
these Q-functions are indeed fixed points of respective operators and thus solve the respective MDPs,
but only do so in (s1, a2)as derivations in other state-action pairs are identical.
Initialization
Initialize the principal with a policy ρ0that does not offer any payments, i.e., ρ0(s1) =ρ0(s2) =
(0,0), where we denote a contract by a tuple b= (b(o1), b(o2)).
Iteration 1: agent
The agent’s best-responding policy π1simply minimizes costs by never investing an effort:
π1(s1, ρ0(s1)) =a1,π1(s2, ρ0(s2)) =a2. This corresponds to the following truncated Q-function:
Qπ1(s1, a1) =Qπ1(s2, a2) = 0 ,Qπ1(s1, a2) =−c(s1, a2) =−1andQπ1(s2, a1) =−c(s2, a1) =
−2.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−1 =Qπ1(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1·0 + 0 .9·0] =−1.
In the absence of contracts, the agent’s truncated Q-function is equal to its Q-function under the
principal’s policy: Qπ1((s, ρ 0(s)), a) =Qπ1(s, a).
Iteration 1: principal
The principal’s subgame-perfect policy ρ1attempts to incentivize effort in s1and offers the following
contracts: ρ1(s1) = (0 ,1.25),ρ1(s2) = (0 ,0). This corresponds to the following contractual Q-
function: qρ1(s1, a1) = 1 .991,qρ1(s1, a2) = 2 .048,qρ1(s2, a1) = 1 .391, and qρ1(s2, a2) = 2 .023.
25
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
2.048 = qρ1(s1, a2) =Eo,s′[−ρ1(s1)(o) +rp(s1, o) +γmax
a′qρ1(s′, a′)] =
0.1(0 + 0 + 0 .9·2.048) + 0 .9(−1.25 + 1 .5 + 0 .9·2.023) = 2 .048.
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .5,0), which is not worth it for the
principal, as evidenced by qρ1(s2, a1)< qρ1(s2, a2).
Iteration 2: agent
The principal ρ1underestimated the payment required to incentivize effort, and the agent’s best-
responding policy π2still never invests an effort: π2(s1, ρ1(s1)) = a1,π2(s2, ρ1(s2)) = a2. This
corresponds to the following truncated Q-function: Qπ2(s1, a1) = 0 .723,Qπ2(s1, a2) =−0.598,
Qπ2(s2, a1) =−1.277, and Qπ2(s2, a2) = 0 .402.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−0.598 = Qπ2(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1(0.9(0 + 0 .723) + 0 .1(1.25 + 0 .402))+
0.9(0.1(0 + 0 .723) + 0 .9(0 + 0 .402))] = −0.598.
Given the contracts from the principal’s policy ρ1, we can compute the agent’s Q-values using (1):
Qπ2((s1, ρ1(s1)), a1) = 0 .848,Qπ2((s1, ρ1(s1)), a2) = 0 .527,Qπ2((s2, ρ1(s2)), a1) =−1.277,
andQπ2((s2, ρ1(s2)), a2) = 0 .402. Observe that indeed, the agent still prefers not to invest an effort
ins1, as evidenced by Qπ2((s1, ρ1(s1)), a1)> Qπ2((s1, ρ1(s1)), a2).
Iteration 2: principal
The principal gives up on incentivizing effort and once again offers no contracts: ρ2(s1) = (0 ,0),
ρ2(s2) = (0 ,0). This corresponds to the following contractual Q-function: qρ2(s1, a1) = 1 .661,
qρ2(s1, a2) = 1 .503,qρ2(s2, a1) = 1 .422, and qρ2(s2, a2) = 1 .839.
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, to incentivize a2in
s1, the principal has to offer a contract ρ(s1) = (0 ,1.652) , which gives us:
1.503 = qρ2(s1, a2) =Eo,s′[−ρ2(s2)(o) +rp(s1, o) +γmax
a′qρ2(s′, a′)] =
0.1(0 + 0 + 0 .9·1.661) + 0 .9(−1.652 + 1 .5 + 0 .9·1.839) = 1 .503,
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .098,0), which is still not worth it for
the principal, as evidenced by qρ2(s2, a1)< qρ2(s2, a2).
Subsequent iterations
Because the principal’s subgame-perfect policy ρ2repeats the policy ρ0from a previous iteration, the
meta-algorithm is now stuck in a cycle where iterations 1 and 2 repeat infinitely. In other words, the
meta-algorithm diverges.
B.7 Meta-Algorithm in the Observed-Action Model
In the special case where the agent’s actions are observed (defined in Section 2.2 and summarized
in Table 2), the meta-algorithm can be shown to find SPE in a single (rather than T+ 1) iteration,
as we show in Theorem B.12. This property is based on the observation that the agent is indifferent
between an MDP without a principal and an MDP augmented with a subgame-perfect principal;
similar observation has been made in contemporaneous work [ 3]. Consequently, evaluating minimal
implementation only requires access to the agent’s optimal Q-function in the absence of the principal.
26
Is is also easy to show that SPE coincides with Stackelberg equilibrium in the observed-action
scenario (Lemma B.14), and consequently the meta-algorithm finds Stackelberg equilibrium.
Theorem B.12. Given a principal-agent stochastic game, G, with observed actions and either finite
or infinite horizon, if the principal’s policy is initialized to offer zero-vectors as contracts in all states,
the meta-algorithm finds SPE in one iteration.
Proof of Theorem B.12. Use the same notations of ρiandπias in the proof of Theorem 3.3 in
Appendix B.4.
After initializing ρ0(that always offers 0) and finding the best-responding agent π1, consider the
optimal payments found at the outer optimization level of Algorithm 1. Given a state s∈S, denote
the agent’s action as
a∗= arg max
aQ∗((s,0), a|ρ0).
For now, let contracts in states other than sremain 0; we will omit the conditioning of Q∗onρ0for
brevity. The optimal contract in s, denoted as b∗, reimburses the agent for taking a suboptimal action,
paying exactly
b∗(s, ap) =Q∗((s,0), a∗)−Q∗((s,0), ap)
if the agent selects ap, and pays 0otherwise. Note that b∗=0ifap=a∗. This contract makes the
agent indifferent between apanda∗because
Q∗((s, b∗), ap) =Q∗((s,0), ap) +b∗(s, ap) =Q∗((s,0), a∗),
changing the agent’s action in stoap(according to tie-breaking). However, the agent’s value function
remains unchanged:
V∗(s, b∗) =Q∗((s, b∗), ap) =Q∗((s,0), a∗) =V∗(s,0).
Thus, the Bellman optimality equations (7)and(8)still hold in all states after replacing 0withb∗in
s, and π1still best-responds to the updated principal. This replacement of zero-vectors for optimal
contracts b∗is performed in all states during the update of the principal at the outer optimization
level, yielding a principal’s policy ρ1subgame-perfect against π1. At the same time, π1remains
best-responding against ρ1. Thus, (ρ1, π1)is an SPE.
Remark B.13 .Unlike our general Theorem 3.3, the above proof relies on the specifics of our model
such as the principal’s action set and the players’ reward functions.
Lemma B.14. Given a principal-agent stochastic game, G, with observed actions, any SPE is a
Stackelberg equilibrium.
Proof. Consider an SPE. As discussed in the above proof, the contracts in SPE exactly reimburse the
agent for choosing suboptimal actions, and the agent’s value function when offered such a contract in
some state sremains the same as in the absence of the contract. Additionally, notice that the principal
may never decrease the agent’s value in any state below the value it gets in the absence of contracts
(since payments are non-negative). Thus, the principal may not deviate from SPE by decreasing
the agent’s value in any of the future states through suboptimal contracts in order to incentivize a
suboptimal action apwhile paying less in s.
On the other hand, consider the principal trying to pay less in some state sby increasing the agent’s
value in some future states. If transition function is determenistic, then in order to decrease the
payment in sby some v < b∗(ap)while still incentivizing ap, the principal must, for example,
increase the payment in s′=T(s,O(s, ap))byv/γ– which is inconsequential for the principal’s
value in s(in our model, the discount factor is the same for the principal and the agent). In case
of a stochastic transition function, the increase of payments in future states required to balance the
decrease of the payment in sbyvmay even decrease the principal’s value in scompared to SPE.
Thus, the principal may not deviate from an SPE (commit to non-credible threats) to increase its
value in the initial state, and therefore any SPE is a Stackelberg equilibrium.
27
B.8 Deriving the Linear Program (Section 4)
In Section 4, we describe an RL approach to solving the principal’s MDP that involves two interde-
pendent tasks of 1) learning a policy that the principal wants to implement and 2) computing the
contracts that do so optimally. The former is solved by learning the contractual Q-function (2), which
we derive as a fixed point of a contraction operator Hρ(13) in Appendix B.3. The latter (which is
required as a subroutine to apply Hρ) we solve using Linear Programming, akin to how the static
principal-agent problems are typically solved (as mentioned in Section 2.1).
Given a state s∈Sand an action to recommend ap∈A, rewrite the right-hand side of Hρas the
following constrained optimization problem:
max
b∈BEo∼O(s,ap),s′∼T(s,o)h
rp(s, o)−b(o) +γmax
a′q(s′, a′)i
s.t.
∀a∈A:Q∗((s, b), ap|ρ)≥Q∗((s, b), a|ρ),(16)
where the constraints explicitly require the recommended action apto be at least as ‘good’ for the
agent as any other action a. Note that rp(s, o)andq(s′, a′)are constants with respect to band can
be omitted from the objective. To see that the constraints are linear, apply the Bellman optimality
operator to the agent’s Q-function, and rewrite constraints through the truncated Q-function using (1):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(17)
Because both the objective and the conditions are linear, the problem (17) is an LP.
As discussed in Section 4, our approach to solving the agent’s optimization problem is to learn the
truncated Q-function Q∗(ρ)and transform it into the Q-function by adding the expected payment.
Note that this representation of the agent’s Q-function is used in the constraints of the above LP. The
requirement of the principal having access to the agent’s (truncated) Q-function can be seen as a
limitation of the outlined approach. A potential remedy is to instead parameterize the principal’s
Q-function Q∗(π)with a discontinuous neural network able to efficiently approximate the Q-function
and the solutions to LPs without requiring access to the agent’s private information [ 79]. Of course,
one could also directly learn Q∗(π)with simpler approaches, e.g., by discretizing the contract space
or employing deep RL methods for continuous action spaces (such as Deep Deterministic Policy
Gradient or Soft Actor-Critic).
Solving the LP also requires access to the outcome function O; we discuss in Appendix D.1 how
this can be circumvented by parameterizing the outcome function with an additional neural network,
trained as a probabilistic outcome classifier.
In the special case of the observed-action model, the LP has a simple solution if the agent best-
responds to a specific principal that always offers a zero-vector 0as a contract. In this solution, the
principal exactly reimburses the agent for choosing a (suboptimal) recommended action ap, and pays
0if agent chooses any other action a̸=ap. Similar observation has been made in contemporaneous
work, see end of Section 3.1 in Wu et al. [82].
C Principal-Multi-Agent Example: Prisoner’s Dilemma
Below we illustrate the multi-agent model from Section 5.1 on the example of a simple matrix game.
Consider a standard one-step Prisoner’s Dilemma with the payoff matrix as in Table 3a. Here, the
only equilibrium is mutual defection (DD), despite cooperation (CC) being mutually beneficial. How
should a benevolent principal change the matrix through payments to incentivize cooperation?
One answer is that CC should become an equilibrium through minimal payments in CC. In one of
the payment schemes that achieve this, the principal pays a unit of utility to both players for the
28
Table 3: Prisoner’s Dilemma as a principal-multi-agent game. ‘Def’ denotes ‘Defect’ and ‘Coop’
denotes ‘Cooperate’. Blue highlights principal’s changes of agents’ payoffs.
(a) no payments (b) arbitrary payments in SPE (c) IC payments in SPE
Def Coop
Def 2, 2 4, 0
Coop 0, 4 3, 3Def Coop
Def 2, 2 4, 0
Coop 0, 4 4, 4Def Coop
Def 2, 2 4, 2
Coop 2, 4 4, 4
CC outcome, resulting in the payoff matrix as in Table 3b.8However, note that DD remains an
equilibrium for the agents. In fact, the new payoff matrix is also a social dilemma known as the Stag
Hunt. In the context of (decentralized) learning, there is no reason to expect the agents to converge
to CC instead of DD, and convergence to suboptimal equilibria has been observed empirically in
generalized Stag Hunt games [58].
As a more robust approach, the principal can make action C dominant. This is stronger than just
making CC an equilibrium because each agent will prefer action C regardless of the actions of others.
To achieve this, in addition to paying a unit of utility to both agents in CC, the principal pays two units
of utility to the cooperating agent in CD and DC, resulting in the payoff matrix as in Table 3c. This is
the kind of solution we implement in our application to SSDs, where we formulate the principal’s
objective as learning a social welfare maximizing strategy profile and its minimal implementation.
Importantly, in the context of our principal-agent model, the minimal implementation is consistent
with SPE in that the principal minimizes payments when agents best-respond by following recom-
mendations (CC in our example). So the IC property is an additional constraint, which specifies
an otherwise ambiguous objective of finding the principal’s policy in SPE, and which only requires
additional payments in equilibrium.
Note that in our example, the payment to each agent for the same action depends on the other agent’s
action (e.g., the row agent receives +2 in CD and +1 in CC). This dependence on other agents is
even more pronounced in stochastic games, where payments of a minimal implementation condition
on the policies of others – not only on their immediate actions in the current state but also on their
actions in all possible future states.9For this reason, learning the precise minimal implementation
is generally impractical: consider a neural network used for contract estimation for some agent
explicitly conditioning on the parameters of neural networks of all other agents, or on their actions in
all states of the MDP.
As a tractable alternative, we use a simple approximation that performs well in our experiments.
Specifically, we train the principal assuming that each agent sticks to one of two policies: either
always follow the principal’s recommendations and get paid, or ignore them and act independently as
if there is no principal. In equilibrium, both policies maximize the agent’s welfare, which justifies the
assumption. For implementation details of this approximation, see Appendix D.2.
D Experiments
D.1 Experiments in Tree MDPs
In this section, we empirically test the convergence of Algorithm 1 towards SPE in hidden-action
MDPs. We experiment with a small variation on the algorithm, which expedites convergence: the
agent and principal policies are updated simultaneously instead of iteratively. This can be seen as
terminating inner and outer tasks early, after one update, leading to approximately optimal policies.
Environment. In these experiments, we simulate a multi-stage project in which the principal offers
contracts at intermediate stages, influencing the agent’s choice of effort. Specifically, we model an
MDP that is a complete binary tree, where the agent’s decisions at each state are binary, representing
8Unlike the single-agent model, the optimal payment scheme here is ambiguous. Any payment scheme that
gives a unit of utility to both agents in CC and no utility to a defecting agent in DC and CD forms an SPE when
coupled with best-responding agents: CC becomes an equilibrium, the payments in which are minimized.
9Here we refer to the dependence of value functions on π−iin the IC constraints (5).
29
Algorithm 2 A deep Q-learning implementation of Algorithm 1 in the single-agent setting
Require: principal’s Q-network θ, agent’s Q-network ϕ, target networks θ′andϕ′, replay buffer RB
1:Initialize buffer RBwith random transitions, networks θandϕwith random parameters
2:fornumber of updates do ▷Training loop
3: fornumber of interactions per update do ▷Interact with the MDP
4: Select an action to recommend, ap, with qθ(s, a)viaϵ-greedy
5: Sample o∼ O(s, a),ra=r(s, a),rp=rp(s, o), transition the MDP to s′∼ T(s, o)
6: Add the transition (s, ap, ra, rp, o, d, s′)to the buffer RB
7: Ifd= 1, reset the MDP ▷ dis a binary ‘done’ variable indicating termination
8: Sample a mini-batch of transitions mb∼RB
9: for(s, ap, ra, rp, o, d, s′)∈mbdo ▷Estimate target variables to update θandϕ
10: ap′= arg maxa′qθ(s′, a′) ▷Select the next action for Q-learning updates
11: Find optimal contracts b∗(s, ap)andb∗(s′, ap′)by solving LP (17)
12: yp(s, ap) =rp−b∗(s, ap, o) +γ(1−d)qθ′(s′, ap′)
13: ya(s, ap) =ra+γ(1−d)(Eo′∼O(s′,ap′)b∗(s′, ap′, o′) +Qϕ′
(s′, ap′))
14: Minimize L(θ) =P
mb
qθ(s, ap)−yp(s, ap)2▷Update θas DQN
15: Minimize L(ϕ) =P
mb
Qϕ(s, ap)−ya(s, ap)2
▷Update ϕas DQN
high or low effort, and correspond to good or bad outcomes with different probabilities. This is an
intentionally simple environment, allowing us to compare with precise ground truth.
The MDP is represented by a complete binary decision tree with depth 10, resulting in 1023 states.
In each state, the agent may take two actions, a0anda1, which may result in two outcomes, o0and
o1. The action a0results in the outcome o0with probability 0.9in all states; likewise, a1results in o1
with probability 0.9. The tree transitions to the left subtree after outcome o0and to the right subtree
after outcome o1.
The action a0yields no cost for the agent, i.e., ∀s:r(s, a 0) = 0 ; and the outcome o0yields no
reward for the principal, i.e. ∀s:rp(s, o 0) = 0 . Conversely, the action a1is always costly and
the outcome o1is always rewarding, with values randomly sampled. Specifically, let Udenote
one-dimensional uniform distribution, U1=U[0,1]andU2=U[0,2]. Then, the agent’s reward
is generated as r(s, a 1) =−(u∼U[0,1−(v∼U1)]), and the principal’s reward is generated as
rp(s, o 1) = (u∼U[0,2−(v∼U2)])Note that the principal’s reward is on average higher than the
agent’s cost. Using this reward function sampling method, the principal’s policy ρ∗in SPE offers
non-trivial contracts that incentivize a1in about 60% of states.
Experimental procedure. We generate three instances of the Tree MDP, each with randomly
sampled reward functions, and used five trials of our algorithm on each Tree MDP. We also use
backward induction to find the exact policies in SPE (π∗, ρ∗)and the corresponding optimal utilities,
which we adopt as the ground truth. By comparing with ground truth directly, our two-phase procedure
from Section 4 becomes somewhat redundant, so we defer it to our multi-agent experiments in a
significantly more complex MDP.
Implementation details. We parameterize the principal’s and the agent’s Q-functions as Deep
Q-Networks [51] respectively denoted by θandϕ. The input to both networks is a state s, and both
networks approximate Q-values for all actions a∈A. Specifically, the principal’s network estimates
the contractual optimal Q-values qθ(s, a), representing its payoffs when optimally incentivizing the
agent to take action ain state s; and the agent’s network estimates the truncated optimal Q-values
Qϕ(s, a), representing its payoffs minus the expected immediate payment.
Algorithm 2 describes our Deep Q-learning-based implementation of Algorithm 1 for the single-agent
MDPs. The overall pipeline is standard, with a few notable details.
First, unlike the iterative convergence of the principal and the agent in Algorithm 1, the two policies
are trained simultaneously.
30
(a) Principal’s utility
(b) Agent’s utility
(c) Accuracy of Principal Action
Figure 3: Results in Tree MDPs. Solid lines are learning curves of DQNs trained with Algorithm 2.
Dashed lines represent ‘optimal’ utilities in SPE obtained with dynamic programming. Different
colors represent three distinct instances of the tree environment. For each, we use five trials of the
algorithm (shaded regions represent standard errors).
Second, the outcome function Ois assumed to be known. If not, it can be parameterized as an
additional neural network ξand trained as a probabilistic classifier with sampled outcomes used
as ground truth; the resulting loss function would be L(ξ) =P
mbCE[Oξ(s, ap), o], where CE
denotes cross-entropy, mbdenotes a mini-batch, and Oξ(s, ap)denotes the predicted probabilities of
outcomes as a function of state-action. We implemented this in our single-agent experiments with O
constant across states and found no difference from having access to O, although this might change
in more complex scenarios.
Third, when updating the agent’s network ϕ, the target variable yϕ′(s, ap)is estimated based on the
contract in the next state s′rather than the current state s. Since payment is a part of reward, the
target variable is effectively estimated as a mixture of parts of rewards in sands′. This is required so
that the truncated rather than the standard Q-function is learned.
Hyperparameters. The neural networks have 2hidden fully connected layers, each consisting
of256neurons and followed by a ReLU activation. The networks are trained for 20000 iterations,
each iteration including 8environment interactions and a single gradient update on a mini-batch
with128transitions, sampled from the replay buffer. Every 100iterations, the target networks are
updated by copying the parameters of the online networks. The learning rate is initialized at 0.001
and is exponentially annealed to 0.0001 throughout the training. Similarly, the exploration rate ϵis
initialized at 1and is linearly annealed to 0throughout the training. Rewards are not discounted, i.e.,
γ= 1.
Results. The results are presented in Figure 3. From Figure 3a, we observe that our algorithm
attains a principal’s utility of just 2%below the optimal utility in SPE. On the other hand, Figure 3b
shows that the agent’s utility can exhibit similar (in absolute terms) deviations from SPE in either
direction. The ’accuracy’ metric in Figure 3c indicates that the principal recommends the action
prescribed by the optimal policy in approximately 90% of the states.
The small underperformance in the principal’s utility and the biases in the agent’s utility can be
partially attributed to the 10% of the non-optimal principal’s actions. That around 90% of correct
actions amount to around 98% of the principal’s utility suggests errors likely occur in rarely visited
states or states where actions result in similar payoffs. effectiveness in approximating the SPE. The
minor discrepancies in utility, coupled with the learning dynamics, underscore the complex interplay
between the principal and the agent as they adapt to each other throughout training.
D.2 Experiments in the Coin Game
Implementation details. Algorithm 3 describes our Deep Q-learning-based implementation of
Algorithm 1 for the multi-agent MDPs with self-interested agents, often referred to as “sequential
social dilemmas”. The experimental procedure consists of two phases: training and validation.
In the training phase, for each agent i, the principal’s objective is to find a policy to recommend
by learning the contractual Q-function, qθ
i, as well as its minimal implementation by learning the
agent’s Q-function in the absence of the principal, Qϕ
i. In Section 5.1, we additionally require the
31
(a) Social welfare
(b) Social welfare, nudging
(c) Proportion of social welfare paid
(d) Accuracy
(e) Convergence to SPE?
(f) Incentive-Compatible contracts?
Figure 4: Learning curves in the Coin Game with a 3×3grid and each episode lasting for 20
time steps. The structure is the same as in Figure 2, with the addition of the top middle plot. The
definition of the plots is as follows: a) total return of the two agents (without payments); b) same,
but our algorithm and constant baseline additionally pay 10% of social welfare to the agents; c) a
ratio of the total payment by the principal to what the agents would effectively be paid if directly
maximizing social welfare; d) the proportion of the principal’s recommendations followed by the
validation agents; r) a ratio between the utilities of an agent’s policy at a given iteration and the
recommended policy, with the opponent using the recommended policy; f) same ratio, but with the
opponent’s policy at a given iteration. Each experiment is repeated 5 times, and each measurement is
averaged over 80 episodes.
minimal implementation to be in dominant strategies. Learning such an implementation requires
conditioning Qϕ
ion the inter-agent policies π−i, which is intractable. As a tractable approximation,
given that rational agents will only deviate from recommendations if their expected payoffs are
not compromised, we simplify each agent’s strategy space to two primary strategies: cooperation
(following the principal’s recommendations) or rational deviation (default optimal policy disregarding
contracts, which gives the same utility). We encapsulate this behavior in a binary variable fi∈ {0,1},
indicating whether agent ifollows the recommendation ap. Then, Qϕ
iis conditioned on the joint f−i
variable of the other agents, indicating both the immediate outcome and the agents’ future behavior.
The efficacy of this simplification is validated through our experimental results.
During the training phase, we randomly sample fifor each agent at the beginning of an episode. For
the episode’s remainder, each agent either follows the recommendations given by qθ
i(iffi= 1) or
acts selfishly according to Qϕ
i(iffi= 0). The experience generated this way is then used to train
bothθandϕ, enhancing exploration and covering the whole space of f.
Given the principal obtained in the training phase, the subsequent validation phase independently
trains selfish agents parameterized by ψifrom scratch in the modified environment. Specifically, each
agent observes an action recommendation when computing Q-values, Qψi
i((s, ap
i), ai), and is paid
by the principal if the recommendation is followed. When estimating payments, fisimply indicates
whether agent ifollowed the recommendation. Other than these changes, we use the standard DQN
training procedure. We also do not assume the principal’s access to the agents’ private information
like Q-values or parameters.
Hyperparameters. The neural networks consist of 1hidden convolutional layer followed by 2
hidden fully connected layers and an output layer. The convolutions have 4×4kernels and transform
the initial 4-channel states into 32channels. The fully connected layers consist of 64neurons. All
hidden layers are followed by ReLU activations. The networks are trained for 1000000 iterations,
each iteration including a single environment interaction and a single gradient update on a mini-batch
with128transitions, sampled from the replay buffer. Every 100iterations, the target networks are
32
updated by copying the parameters of the online networks. The learning rate is initialized at 0.0005
and is exponentially annealed to 0.0001 throughout the training. Similarly, the exploration rate ϵis
initialized at 0.4and is linearly annealed to 0throughout the training. The discounting factor is set at
γ= 0.99. For more efficient training, we use prioritized replay buffers [ 69] with a maximum size of
100000 ,α= 0.4,β= 0, and ϵ= 10−7.
Additional results. In Figure 4, we report results in the Coin Game with a 3×3grid and each
episode lasting for 20time steps. This is a simpler environment than the one in the main text, as the
state space and the horizon are smaller.
During training, our algorithm finds an approximately optimal joint policy (Fig. 4a) and estimates
that about 30% of social welfare is sufficient for an IC implementation (Fig. 4c). Interestingly
and contrary to our previous results, the validation phase does not confirm this: we observe that
the validation agents fall short of the optimal performance, as well as that our algorithm does not
outperform the constant proportion baseline (Fig. 4a). On the one hand, we do not find evidence that
it does not converge to SPE, as in Figure 4e, the utility ratio hovers around 1. On the other hand, a
test on incentive compatibility (Fig. 4f) reveals that the validation agents consistently find policies
that perform 5%to10% better against the opponent DQNs, meaning that the principal fails to learn
IC contracts. For more information on these tests, see the | discussion in Section 5.3 We conjecture
that this negative result is due to using the approximation of IC through fivariables during training,
as described in the | interpretation as an
iterative application of a contraction operator to the principal’s Q-function (Theorem 3.4).
Next, we turn to the standard model-free RL setting where the MDP is a black box, and the policies
are learned by sampling stochastic transitions and rewards through interacting with the MDP. We
instantiate the meta-algorithm by solving both principal’s and agent’s MDPs with (deep) Q-learning
and apply it in a two-phase setup. First, we train the policies assuming the principal has access
to the agent’s optimization problem (of maximizing its Q-function estimate given a contract in a
state). Such an access is a standard assumption in economics, and does not trivialize the problem.
Then, we relax the assumption and validate the learned principal’s policy against black-box agents
trained from scratch, mimicking its execution in the real world. Alternatively, it is possible to lift
this assumption completely by applying any learning algorithm for the one-shot contracting problem,
such as the deep-learning approach of Wang et al. [79]. Through this setup, we verify empirically
that our method approximates SPE well despite early termination and approximation errors.
In Section 5, we extend our approach to multi-agent RL and sequential social dilemmas (SSDs) [42],
a generalization of prisoner’s-dilemma-style single-shot games to multiple time periods and complex
state spaces. A common approach to SSDs is through shaping the agents’ rewards, with a focus on
cooperation and social welfare maximization. However, the extent to which the rewards are modified
is typically ignored, and despite the vast literature on the topic, there is no general procedure for
finding a minimal intervention into agents’ rewards that drives cooperation. We address this gap using
our developed principal-agent machinery. We empirically validate our approach on a prominent SSD
known as the Coin Game [23]. We compare to an alternative, simpler approach with hand-coded
payment schemes inspired by a reward-redistribution method of Christoffersen et al. [8], and observe
that with the same amount of subsidy, this less-targeted intervention achieves a significantly lower
welfare level.
1.2 Related Work
Our work fits into the wider literature on automated mechanism design [ 10], in particular approaches
based on deep learning [ 18,79] also known as differentiable economics [ 21]. Most closely related
from this line of work, Wang et al. [79] consider stateless one-shot contracting problems and provide
a network architecture for capturing the discontinuities in the principal’s utility function. We differ
from this work in our focus on sequential contracting problems and the entailing unique challenges.
2
There is a number of algorithmic works that focus on repeated principal-agent interactions on MDPs,
including work on environment design andpolicy teaching [87,89,85,3]. Our approach differs from
these earlier works in several ways, including that we actively search for the best (unconstrained)
equilibrium in the game between the principal and the agent through reinforcement learning. A
closely related line of work, including [ 24], is concerned with learning Stackelberg equilibria in
general leader-follower games, including games on MDPs. Our work differs in its focus on SPE,
which is the more standard equilibrium concept in dynamic contract design problems. Several
works have studied repeated contract design problems from a no-regret online-learning perspective
[30,91,29,70]. However, these works are typically limited to stateless and/or non-sequential
interactions. A prominent exception is a contemporaneous study by Wu et al. [82] that introduces a
model of principal-agent MDPs nearly identical to ours, barring an important notational distinction
of encoding outcomes as next states. However, their and our studies pursue orthogonal algorithmic
developments: whereas they treat contract policies as arms of a bandit and minimize regret, we rely
on deep RL to scale to large MDPs and multiple agents.
Starting with the work of Leibo et al. [42], there is a huge literature on SSDs. Most closely related in
this direction is the work by Christoffersen et al. [8]on multi-agent RL and applications to SSDs.
This work pursues an approach in which one of the agents (rather than the principal) proposes a
contract (an outcome-contingent, zero-sum reward redistribution scheme), and the other agents can
either accept or veto. They consider several SSDs and show how hand-crafted contract spaces strike a
balance between generality and tractability, and can be an effective tool in mitigating social dilemmas.
An important distinction of our work is that we distinguish between principal and agent(s), and insist
on the standard limited liability requirement from economics. Furthermore, in our approach the
principal learns the conditions for payments, allowing it to utilize contracts in their full generality.
Also, our method has an interpretation as learning k-implementation [52].
We provide additional details on the related literature in Appendix A.
2 Problem Setup
In this section, we first introduce the classic (limited liability) contract design model of Holmström
[32] and Grossman and Hart [26], and then propose its extension to MDPs. We defer further extension
to multi-agent MDPs to Section 5.1.
2.1 Static Hidden-Action Principal-Agent Problem
In a principal-agent problem, the principal wants the agent to perform a task. The agent has a choice
between several actions a∈Awith different costs c(a), interpreted as effort levels. Each action
stochastically maps to outcomes o∈Oaccording to a distribution O(a), with higher effort levels
more likely to result in good outcomes, as measured by the associated principal’s reward rp(o). By
default, a rational agent would choose the cost-minimizing action. To incentivize the agent to invest
an effort, the principal may offer a contract bprior to the action choice. Crucially, the principal may
be unable (or unwilling) to directly monitor the agent’s action, so the contractual payments b(o)≥0
are defined per outcome o∈O. The principal seeks an optimal contract: a payment scheme that
maximizes the principal’s utility, max bEo∼O(a)[rp(o)−b(o)], given that the agent best-responds
withmax aEo∼O(a)[b(o)]−c(a).
If costs and outcome distributions are known, the optimal contract can be precisely found using
Linear Programming (LP): for each action a∈A, find the contract that implements it (makes the
agent at least indifferent between this and other actions) through a minimal expected payment, and
then choose the best action to implement. Otherwise or if the LPs are infeasible, an approximation
can be obtained by training a neural network on a sample of past interactions with the agent [79].
2.2 Hidden-Action Principal-Agent MDPs
In order to extend contract design to MDPs, we assume a principal-agent problem in each state of
the MDP, and let the outcomes additionally define its (stochastic) transitioning to the next state. A
hidden-action principal-agent MDP is a tuple M= (S, s 0, A, B, O, O,R,Rp,T, γ). As usual in
MDPs, Sis a set of states, s0∈Sis the initial state, and Ais a set of nagent’s actions a∈A.
Additionally, Ois a set of moutcomes o∈O,B⊂Rm
≥0is a set of principal’s actions (contracts)
3
Figure 1: Example of a principal-agent MDP with three states S={s0, sL, sR}.In each state, the
agent can take one of two actions: noisy-left ( aL), which is costly and leads to outcomes LandRwith
probabilities 0.9and0.1, and noisy-right (aR), which is free and has the roles of LandRreversed.
The principal’s rewards in any state s∈Sfor outcomes L, R arerp(s, L) =14
9, rp(s, R) = 0 ,
resp., while those of the agent for the actions are r(s, aL) =−4
5, r(s, aR) = 0 . For analysis, see
Appendix B.1.
b∈B, andb(o)is the o-th coordinate of a contract (payment). In each state, the outcome is sampled
based on the agent’s action from a distribution O(s, a), where O:S×A→∆(O)is the outcome
function. Then, the agent’s reward is determined by the reward function R(s, a, b, o ) =r(s, a)+b(o)
for some r(s, a). Likewise, the principal’s reward is determined by Rp(s, b, o ) =rp(s, o)−b(o)for
some rp(s, o); note that the agent’s action is private and thus Rpdoes not explicitly depend on it.
Based on the outcome, the MDP transitions to the next state s′∼ T(s, o), where T:S×O→∆(S)
is the transition function. Finally, γ∈[0,1]is the discount factor. For an example of a principal-agent
MDP, see Figure 1. In the main text, we focus on MDPs with a finite time horizon T. We assume
w.l.o.g. that each state is uniquely associated with a time step (see Appendix B.4).
We analyze the principal-agent MDP as a stochastic game G(can be seen as extensive-form when
the horizon is finite), where two players maximize their long-term payoffs. The game progresses
as follows. At each timestep t, the principal observes the state stof the MDP and constructs a
contract bt∈Baccording to its policy ρ:S→∆(B). Then, the agent observes the pair (st, bt)
and chooses an action at∈Aaccording to its policy π:S×B→∆(A). After this, the MDP
transitions, and the interaction repeats. Both players maximize their value functions: the principal’s
value function, Vρ(π), of a policy ρgiven the agent’s policy πis defined in a state sbyVρ(s|π) =
E[P
tγtRp(st, bt, ot)|s0=s]; likewise, the agent’s value function Vπ(ρ)is defined in a state sand
given a contract bbyVπ(s, b|ρ) =E[P
tγtR(st, at, bt, ot)|s0=s, b0=b]. Players’ utilities in
the game are their values in the initial state. Additionally, define the players’ Q-value functions Qρ(π)
andQπ(ρ)byQρ(s, b|π) =Vρ(s|b0=b, π)andQπ((s, b), a|ρ) =Vπ(s, b|a0=a, ρ).
A special case of the principal-agent MDP trivializes hidden actions by making the outcome function
deterministic and bijective; the resulting observed-action model is similar to Ben-Porat et al. [3]. For
an explicit comparison of the two models with each other and with standard MDPs, see Appendix B.
3 Purely Economic Setting
In this section, we define our solution concept for principal-agent stochastic games (Section 3.1) and
introduce a meta-algorithm that finds this solution (Section 3.2). We assume full access to the MDP
model (including transition and reward functions) and address the learning setting in the next section.
3.1 Subgame-Perfect Equilibrium (SPE)
In what follows let Gbe a principal-agent stochastic game. Let a subgame ofGin state s∈Sbe a
gameG′defined by replacing s0withs, and Swith a subset of states that can be reached from s.
Observation 3.1. Fixing one player’s policy in Gdefines a (standard) MDP for another player. In
particular, a principal’s policy defines the agent’s MDP by modifying the reward function through
contracts; likewise, an agent’s policy defines the principal’s MDP by modifying the transition and
4
Algorithm 1 Meta-algorithm for finding SPE
1:Initialize the principal’s policy ρarbitrarily ▷e.g.,∀s∈S:ρ(s) =0
2:while ρnot converged do ▷Inner-outer optimization loop
3: Solve the agent’s MDP: find π:=π∗(ρ) ▷Inner optimization level
4: Solve the principal’s MDP: find ρ:=ρ∗(π) ▷Outer optimization level
5:return (ρ, π)
reward functions through the agent’s responses to contracts. For exact formulations of these MDPs,
see Appendix B.2. The optimal policies in both MDPs can be assumed w.l.o.g. to be deterministic (in
single-agent setting), and can be found with any suitable dynamic programming or RL algorithm [ 75].
Agent’s perspective. In the agent’s MDP defined by ρ, refer to the optimal policy as best-responding
toρ(where ties are broken in favor of the principal, as is standard in contract design). Define
a function π∗that maps a principal’s policy ρto the best-responding policy π∗(ρ). Denote the
action prescribed by π∗(ρ)in state sgiven contract bbyπ∗(s, b|ρ)≡π∗(ρ)(s, b). Note that the
best-responding policy is defined in sfor any b∈Band is not limited to the principal’s action ρ(s).
Principal’s perspective. Similarly, in the principal’s MDP defined by π, refer to the optimal policy as
subgame-perfect against π. Define a function ρ∗that maps an agent’s policy πto the subgame-perfect
policy ρ∗(π). Denote the contract prescribed by ρ∗(π)in state sbyρ∗(s|π)≡ρ∗(π)(s). In all
states, this policy satisfies: ρ∗(s|π)∈arg maxbQ∗(s, b|π), where Q∗(s, b|π)≡Qρ∗(π)(s, b|π)
– that is, in each subgame, the principal takes the optimal action.
Definition 3.2. Asubgame-perfect equilibrium (SPE) ofGis a pair of policies (ρ, π), where the
principal’s policy ρ≡ρ∗(π)is subgame-perfect against an agent that best-responds with π≡π∗(ρ).
SPE is a standard solution concept for extensive-form games [ 55]. It always exists and is essentially
unique (see Lemma B.11 for completeness). Compared to non-subgame-perfect solutions like the
well–studied Stackelberg equilibrium, SPE can lose utility for the principal. However, it disallows
threats that are non-credible , i.e., require playing a suboptimal contract in a subgame. We demonstrate
the difference on our example in Appendix B.1. Furthermore, Gerstgrasser and Parkes [24] show
that learning a Stackelberg equilibrium necessitates the principal to go through long episodes with
observations of the learning dynamics of the followers, and with only sparse rewards (see also Brero
et al. [5]). SPE, in contrast, naturally fits RL, as both players’ policies solve the respective MDPs.
3.2 Meta-Algorithm for Finding SPE
Algorithm 1 presents a general pipeline for finding SPE in a principal-agent stochastic game. It can be
seen as an inner-outer (bilevel) optimization loop, with agent and principal optimization respectively
constituting the inner and outer levels. We refer to this as a meta-algorithm, as we do not yet specify
how to perform the optimization (in Lines 3 and 4). Superficially, this approach resembles the use of
bilevel optimization for learning optimal reward shaping [ 72,33,7,78,6,49]. The crucial difference
of that setting is that the two levels optimize the same downstream task rather than distinct and
possibly conflicting objectives of principal and agent.
It is well-known that SPE of an extensive-form game can be found with backward induction (e.g., see
Section 5.6 of Osborne [55]). Theorem 3.3 states that the proposed meta-algorithm also finds SPE.
The proof, provided in Appendix B.4, essentially shows that it performs backward induction implicitly.
That is, each iteration of the meta-algorithm, the players’ policies reach SPE in an expanding set of
subgames, starting from terminal states and ending with the initial state. The proof does not rely on
the specifics of our model and applies to any game where players move sequentially, and the agent
observes and can respond to anyprincipal’s action in a state.
Theorem 3.3. Given a principal-agent stochastic game Gwith a finite horizon T, the meta-algorithm
finds SPE in at most T+ 1iterations.
The meta-algorithm has several unique advantages. First, as we discuss in Section 4, both inner and
outer optimization tasks can be instantiated with Q-learning. This removes the need to know the
model of the MDP and allows handling of large-scale MDPs by utilizing deep learning. Second, it
can also be seen as iteratively applying a contraction operator, which we formulate as a theorem:
5
Table 1: Correctness of the meta-algorithm in different scenarios
finite horizon T infinite horizon
hidden action finds SPE in T+ 1iterations (Theorem 3.3) may diverge (Appendix B.6)
observed action finds SPE that is also Stackelberg in 1 iteration (Appendix B.7)
Theorem 3.4. Given a principal-agent finite-horizon stochastic game G, each iteration of the meta-
algorithm applies to the principal’s Q-function an operator that is a contraction in the sup-norm.
The proof is provided in Appendix B.5. This property implies that each iteration of the meta-algorithm
monotonically improves the principal’s policy in terms of its Q-function converging. This has a
practical advantage: if meta-algorithm is terminated early, the policies still partially converge to SPE.
As an independent observation, Theorem 3.3 complements the theoretical results of Gerstgrasser
and Parkes [24]. Specifically, their Theorem 2 presents an example where RL fails to converge to a
Stackelberg equilibrium if the agent ‘immediately’ best responds. This procedure is our Algorithm 1,
with agent optimization solved by an oracle and principal optimization performed with RL. Our
Theorem 3.3 complements their negative result by showing that such a procedure converges to SPE.
Finally, while we focus on finite-horizon hidden-action MDPs in the main text, we also analyze the
other scenarios in the Appendix. Our findings are summarized in Table 1.
4 Learning Setting
In this section, we develop an RL approach to principal-agent MDPs by solving both inner and
outer optimization tasks of the meta-algorithm with Q-learning. These tasks correspond to finding
optimal policies in the respective agent’s and principal’s MDPs defined in Observation 3.1. We
operate in a standard model-free RL setting, where learning is performed through interactions with a
black-box MDP. For both principal and agent, we introduce modified Q-functions, which we formally
derive as fixed points of contraction operators in Appendix B.3. We detail deep implementations in
Appendix D. Our approach consists of the following two-phase setup:
1.Training: Principal’s policy is trained ‘for free’ in simulated interactions with agent and
MDP. Principal has access to the learning agent and essentially controls it.
2.Execution / Validation: Trained principal’s policy can be executed or validated against a
black-box (possibly learning) agent.
This is in contrast with the online setup where the principal interacts with an actual black-box agent
during learning, incurring losses from payments in the process [ 31,92]. On the other hand, this setup
is one step ahead of the MARL literature adjacent to our application in Section 5, where the analysis
is typically limited to the training phase.
Agent’s perspective. Consider the agent’s MDP defined by principal’s policy ρ. The best-responding
agent’s Q-function in a state s,Q∗((s, b), a|ρ), depends on the observed contract b– particularly on
the expected payment. This effect can be isolated by applying Bellman optimality operator:
Q∗((s, b), a|ρ) =Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ), (1)
where Q∗(s, a|ρ) = [r(s, a)+γEmax a′Q∗((s′, ρ(s′)), a′|ρ)]is the truncated optimal Q-function,
which represents agent’s expected long-term utility barring the immediate payment. Our approach to
training the agent (solving inner optimization) is to learn the truncated Q-function and compute the
Q-function through (1). This way, the Q-function is defined for any b∈Bins, under an assumption
that the principal plays according to ρin future (e.g., ρ(s′)in the next state). From the agent’s
perspective, this is justified in SPE, where ρis optimal for the principal in all future subgames. Note
that computing the expected payment requires the outcome distribution – if unknown, it can be
approximated as a probabilistic classifier (more on this in Appendix D.1).
Principal’s perspective. Consider the principal’s MDP defined by a best-responding agent π∗(ρ)for
an arbitrary ρ. The basic idea is to divide the principal’s learning problem into two parts: 1) learn the
6
agent’s policy that the principal wants to implement ( recommends to the agent), and 2) compute the
optimal contracts that implement it (the minimal implementation ) using Linear Programming (LP).
Essentially, this extends the classic LP approach from static contract design described in Section 2.1.
To approach the first subproblem, we need an analogue of the principal’s Q-function that is a function
of an agent’s action. To this end, we define the contractual Q-function q∗(π∗(ρ)) :S×A→Rby
q∗(s, ap|π∗(ρ)) = max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)), (2)
which can be interpreted in sas the maximal principal’s Q-value that can be achieved by implementing
ap∈A. To compute the optimal contract arg maxbQ∗(s, b|ρ)using q∗(π∗(ρ)), we can select
the optimal action to implement as arg maxapq∗(s, ap|π∗(ρ)), and then find the corresponding
contract as solution to the conditional maximization in (2). This conditional maximization is the
second subproblem defined above. We solve it as LP (for details, see Appendix B.8):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(3)
Solving this LP requires access to the agent’s truncated Q-function Q∗. Although this requirement
is in line with the training phase of our setup, it can be alleviated, e.g., by approximating optimal
contracts with deep learning [ 79]. We do not explore this direction, so as to not conflate the distinct
learning problems originating from our MDP formulation and the agent being black-box.
Practical concerns. The above instantiation of the meta-algorithm assumes that Q-learning is
run until convergence to precisely solve both inner and outer optimization tasks. In practice, one
has to terminate early and approximate; in case of using deep RL, function approximation also
contributes to the error. In our model, even a small error can have a devastating effect because the
principal’s Q-function is discontinuous : a misestimation of the optimal contract (however slight) may
change the agent’s action, resulting in a worse outcome (see also [ 79]). We empirically validate the
robustness of our implementation to this effect: In Appendix D.1, we apply it to solve toy tree MDPs
(generalizations of Figure 1). Furthermore, our multi-agent experiments in Section 5.3 are validated
in a complex and highly combinatorial sequential social dilemma. We report additional multi-agent
experiments in Appendix D.2, where we apply a form of nudging the agents to desirable behaviour
through extra payments, which helps counteract the degrading effect of approximation errors.
5 Extension to Multi-Agent RL
In this section, we explore an extension to multiple agents. We state the formal model in Section 5.1.
We introduce sequential social dilemmas (SSDs) and the Coin Game (in Section 5.2). We present
experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and | implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as | Section not found | future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this | Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems. | Section not found | Section not found | references and strategic behavior.
Principal and agent have misaligned preferences, each learning to maximize their own utility in the
presence of the other. Private information (such as hidden actions) further complicates the problem.
(3)Approximation and learning. In practice, learning inherently comes with approximation errors.
Even slight errors may have devastating effects due to discontinuity of the principal’s utility function.
1.1 Our Contribution
We formulate and study a principal-agent game in which the agent learns a policy for an MDP on
behalf of the principal, and the principal learns to guide the agent via a series of contracts. After
defining this setup formally (Section 2), we first discuss the purely economic setting (Section 3) with
full access to the MDP model and no learning required. We focus on the standard solution concept
for extensive-form games, namely subgame-perfect equilibrium (SPE)—see Section 3.1.
A key observation is that fixing one player’s policy defines a standard MDP for another player. Based
on this, we formulate a simple meta-algorithm (Algorithm 1) that finds SPE in a finite-horizon game
in at most T+ 1iterations, where Tis the horizon of the MDP (Theorem 3.3). The meta-algorithm
iteratively optimizes the principal’s and agent’s policies in their respective MDPs, but does not specify
the optimization steps. We also give the meta-algorithm a clean mathematical interpretation as an
iterative application of a contraction operator to the principal’s Q-function (Theorem 3.4).
Next, we turn to the standard model-free RL setting where the MDP is a black box, and the policies
are learned by sampling stochastic transitions and rewards through interacting with the MDP. We
instantiate the meta-algorithm by solving both principal’s and agent’s MDPs with (deep) Q-learning
and apply it in a two-phase setup. First, we train the policies assuming the principal has access
to the agent’s optimization problem (of maximizing its Q-function estimate given a contract in a
state). Such an access is a standard assumption in economics, and does not trivialize the problem.
Then, we relax the assumption and validate the learned principal’s policy against black-box agents
trained from scratch, mimicking its execution in the real world. Alternatively, it is possible to lift
this assumption completely by applying any learning algorithm for the one-shot contracting problem,
such as the deep-learning approach of Wang et al. [79]. Through this setup, we verify empirically
that our method approximates SPE well despite early termination and approximation errors.
In Section 5, we extend our approach to multi-agent RL and sequential social dilemmas (SSDs) [42],
a generalization of prisoner’s-dilemma-style single-shot games to multiple time periods and complex
state spaces. A common approach to SSDs is through shaping the agents’ rewards, with a focus on
cooperation and social welfare maximization. However, the extent to which the rewards are modified
is typically ignored, and despite the vast literature on the topic, there is no general procedure for
finding a minimal intervention into agents’ rewards that drives cooperation. We address this gap using
our developed principal-agent machinery. We empirically validate our approach on a prominent SSD
known as the Coin Game [23]. We compare to an alternative, simpler approach with hand-coded
payment schemes inspired by a reward-redistribution method of Christoffersen et al. [8], and observe
that with the same amount of subsidy, this less-targeted intervention achieves a significantly lower
welfare level.
1.2 Related Work
Our work fits into the wider literature on automated mechanism design [ 10], in particular approaches
based on deep learning [ 18,79] also known as differentiable economics [ 21]. Most closely related
from this line of work, Wang et al. [79] consider stateless one-shot contracting problems and provide
a network architecture for capturing the discontinuities in the principal’s utility function. We differ
from this work in our focus on sequential contracting problems and the entailing unique challenges.
2
There is a number of algorithmic works that focus on repeated principal-agent interactions on MDPs,
including work on environment design andpolicy teaching [87,89,85,3]. Our approach differs from
these earlier works in several ways, including that we actively search for the best (unconstrained)
equilibrium in the game between the principal and the agent through reinforcement learning. A
closely related line of work, including [ 24], is concerned with learning Stackelberg equilibria in
general leader-follower games, including games on MDPs. Our work differs in its focus on SPE,
which is the more standard equilibrium concept in dynamic contract design problems. Several
works have studied repeated contract design problems from a no-regret online-learning perspective
[30,91,29,70]. However, these works are typically limited to stateless and/or non-sequential
interactions. A prominent exception is a contemporaneous study by Wu et al. [82] that introduces a
model of principal-agent MDPs nearly identical to ours, barring an important notational distinction
of encoding outcomes as next states. However, their and our studies pursue orthogonal algorithmic
developments: whereas they treat contract policies as arms of a bandit and minimize regret, we rely
on deep RL to scale to large MDPs and multiple agents.
Starting with the work of Leibo et al. [42], there is a huge literature on SSDs. Most closely related in
this direction is the work by Christoffersen et al. [8]on multi-agent RL and applications to SSDs.
This work pursues an approach in which one of the agents (rather than the principal) proposes a
contract (an outcome-contingent, zero-sum reward redistribution scheme), and the other agents can
either accept or veto. They consider several SSDs and show how hand-crafted contract spaces strike a
balance between generality and tractability, and can be an effective tool in mitigating social dilemmas.
An important distinction of our work is that we distinguish between principal and agent(s), and insist
on the standard limited liability requirement from economics. Furthermore, in our approach the
principal learns the conditions for payments, allowing it to utilize contracts in their full generality.
Also, our method has an interpretation as learning k-implementation [52].
We provide additional details on the related literature in | Appendix A.
2 Problem Setup
In this section, we first introduce the classic (limited liability) contract design model of Holmström
[32] and Grossman and Hart [26], and then propose its extension to MDPs. We defer further extension
to multi-agent MDPs to Section 5.1.
2.1 Static Hidden-Action Principal-Agent Problem
In a principal-agent problem, the principal wants the agent to perform a task. The agent has a choice
between several actions a∈Awith different costs c(a), interpreted as effort levels. Each action
stochastically maps to outcomes o∈Oaccording to a distribution O(a), with higher effort levels
more likely to result in good outcomes, as measured by the associated principal’s reward rp(o). By
default, a rational agent would choose the cost-minimizing action. To incentivize the agent to invest
an effort, the principal may offer a contract bprior to the action choice. Crucially, the principal may
be unable (or unwilling) to directly monitor the agent’s action, so the contractual payments b(o)≥0
are defined per outcome o∈O. The principal seeks an optimal contract: a payment scheme that
maximizes the principal’s utility, max bEo∼O(a)[rp(o)−b(o)], given that the agent best-responds
withmax aEo∼O(a)[b(o)]−c(a).
If costs and outcome distributions are known, the optimal contract can be precisely found using
Linear Programming (LP): for each action a∈A, find the contract that implements it (makes the
agent at least indifferent between this and other actions) through a minimal expected payment, and
then choose the best action to implement. Otherwise or if the LPs are infeasible, an approximation
can be obtained by training a neural network on a sample of past interactions with the agent [79].
2.2 Hidden-Action Principal-Agent MDPs
In order to extend contract design to MDPs, we assume a principal-agent problem in each state of
the MDP, and let the outcomes additionally define its (stochastic) transitioning to the next state. A
hidden-action principal-agent MDP is a tuple M= (S, s 0, A, B, O, O,R,Rp,T, γ). As usual in
MDPs, Sis a set of states, s0∈Sis the initial state, and Ais a set of nagent’s actions a∈A.
Additionally, Ois a set of moutcomes o∈O,B⊂Rm
≥0is a set of principal’s actions (contracts)
3
Figure 1: Example of a principal-agent MDP with three states S={s0, sL, sR}.In each state, the
agent can take one of two actions: noisy-left ( aL), which is costly and leads to outcomes LandRwith
probabilities 0.9and0.1, and noisy-right (aR), which is free and has the roles of LandRreversed.
The principal’s rewards in any state s∈Sfor outcomes L, R arerp(s, L) =14
9, rp(s, R) = 0 ,
resp., while those of the agent for the actions are r(s, aL) =−4
5, r(s, aR) = 0 . For analysis, see
Appendix B.1.
b∈B, andb(o)is the o-th coordinate of a contract (payment). In each state, the outcome is sampled
based on the agent’s action from a distribution O(s, a), where O:S×A→∆(O)is the outcome
function. Then, the agent’s reward is determined by the reward function R(s, a, b, o ) =r(s, a)+b(o)
for some r(s, a). Likewise, the principal’s reward is determined by Rp(s, b, o ) =rp(s, o)−b(o)for
some rp(s, o); note that the agent’s action is private and thus Rpdoes not explicitly depend on it.
Based on the outcome, the MDP transitions to the next state s′∼ T(s, o), where T:S×O→∆(S)
is the transition function. Finally, γ∈[0,1]is the discount factor. For an example of a principal-agent
MDP, see Figure 1. In the main text, we focus on MDPs with a finite time horizon T. We assume
w.l.o.g. that each state is uniquely associated with a time step (see Appendix B.4).
We analyze the principal-agent MDP as a stochastic game G(can be seen as extensive-form when
the horizon is finite), where two players maximize their long-term payoffs. The game progresses
as follows. At each timestep t, the principal observes the state stof the MDP and constructs a
contract bt∈Baccording to its policy ρ:S→∆(B). Then, the agent observes the pair (st, bt)
and chooses an action at∈Aaccording to its policy π:S×B→∆(A). After this, the MDP
transitions, and the interaction repeats. Both players maximize their value functions: the principal’s
value function, Vρ(π), of a policy ρgiven the agent’s policy πis defined in a state sbyVρ(s|π) =
E[P
tγtRp(st, bt, ot)|s0=s]; likewise, the agent’s value function Vπ(ρ)is defined in a state sand
given a contract bbyVπ(s, b|ρ) =E[P
tγtR(st, at, bt, ot)|s0=s, b0=b]. Players’ utilities in
the game are their values in the initial state. Additionally, define the players’ Q-value functions Qρ(π)
andQπ(ρ)byQρ(s, b|π) =Vρ(s|b0=b, π)andQπ((s, b), a|ρ) =Vπ(s, b|a0=a, ρ).
A special case of the principal-agent MDP trivializes hidden actions by making the outcome function
deterministic and bijective; the resulting observed-action model is similar to Ben-Porat et al. [3]. For
an explicit comparison of the two models with each other and with standard MDPs, see Appendix B.
3 Purely Economic Setting
In this section, we define our solution concept for principal-agent stochastic games (Section 3.1) and
introduce a meta-algorithm that finds this solution (Section 3.2). We assume full access to the MDP
model (including transition and reward functions) and address the learning setting in the next section.
3.1 Subgame-Perfect Equilibrium (SPE)
In what follows let Gbe a principal-agent stochastic game. Let a subgame ofGin state s∈Sbe a
gameG′defined by replacing s0withs, and Swith a subset of states that can be reached from s.
Observation 3.1. Fixing one player’s policy in Gdefines a (standard) MDP for another player. In
particular, a principal’s policy defines the agent’s MDP by modifying the reward function through
contracts; likewise, an agent’s policy defines the principal’s MDP by modifying the transition and
4
Algorithm 1 Meta-algorithm for finding SPE
1:Initialize the principal’s policy ρarbitrarily ▷e.g.,∀s∈S:ρ(s) =0
2:while ρnot converged do ▷Inner-outer optimization loop
3: Solve the agent’s MDP: find π:=π∗(ρ) ▷Inner optimization level
4: Solve the principal’s MDP: find ρ:=ρ∗(π) ▷Outer optimization level
5:return (ρ, π)
reward functions through the agent’s responses to contracts. For exact formulations of these MDPs,
see Appendix B.2. The optimal policies in both MDPs can be assumed w.l.o.g. to be deterministic (in
single-agent setting), and can be found with any suitable dynamic programming or RL algorithm [ 75].
Agent’s perspective. In the agent’s MDP defined by ρ, refer to the optimal policy as best-responding
toρ(where ties are broken in favor of the principal, as is standard in contract design). Define
a function π∗that maps a principal’s policy ρto the best-responding policy π∗(ρ). Denote the
action prescribed by π∗(ρ)in state sgiven contract bbyπ∗(s, b|ρ)≡π∗(ρ)(s, b). Note that the
best-responding policy is defined in sfor any b∈Band is not limited to the principal’s action ρ(s).
Principal’s perspective. Similarly, in the principal’s MDP defined by π, refer to the optimal policy as
subgame-perfect against π. Define a function ρ∗that maps an agent’s policy πto the subgame-perfect
policy ρ∗(π). Denote the contract prescribed by ρ∗(π)in state sbyρ∗(s|π)≡ρ∗(π)(s). In all
states, this policy satisfies: ρ∗(s|π)∈arg maxbQ∗(s, b|π), where Q∗(s, b|π)≡Qρ∗(π)(s, b|π)
– that is, in each subgame, the principal takes the optimal action.
Definition 3.2. Asubgame-perfect equilibrium (SPE) ofGis a pair of policies (ρ, π), where the
principal’s policy ρ≡ρ∗(π)is subgame-perfect against an agent that best-responds with π≡π∗(ρ).
SPE is a standard solution concept for extensive-form games [ 55]. It always exists and is essentially
unique (see Lemma B.11 for completeness). Compared to non-subgame-perfect solutions like the
well–studied Stackelberg equilibrium, SPE can lose utility for the principal. However, it disallows
threats that are non-credible , i.e., require playing a suboptimal contract in a subgame. We demonstrate
the difference on our example in Appendix B.1. Furthermore, Gerstgrasser and Parkes [24] show
that learning a Stackelberg equilibrium necessitates the principal to go through long episodes with
observations of the learning dynamics of the followers, and with only sparse rewards (see also Brero
et al. [5]). SPE, in contrast, naturally fits RL, as both players’ policies solve the respective MDPs.
3.2 Meta-Algorithm for Finding SPE
Algorithm 1 presents a general pipeline for finding SPE in a principal-agent stochastic game. It can be
seen as an inner-outer (bilevel) optimization loop, with agent and principal optimization respectively
constituting the inner and outer levels. We refer to this as a meta-algorithm, as we do not yet specify
how to perform the optimization (in Lines 3 and 4). Superficially, this approach resembles the use of
bilevel optimization for learning optimal reward shaping [ 72,33,7,78,6,49]. The crucial difference
of that setting is that the two levels optimize the same downstream task rather than distinct and
possibly conflicting objectives of principal and agent.
It is well-known that SPE of an extensive-form game can be found with backward induction (e.g., see
Section 5.6 of Osborne [55]). Theorem 3.3 states that the proposed meta-algorithm also finds SPE.
The proof, provided in Appendix B.4, essentially shows that it performs backward induction implicitly.
That is, each iteration of the meta-algorithm, the players’ policies reach SPE in an expanding set of
subgames, starting from terminal states and ending with the initial state. The proof does not rely on
the specifics of our model and applies to any game where players move sequentially, and the agent
observes and can respond to anyprincipal’s action in a state.
Theorem 3.3. Given a principal-agent stochastic game Gwith a finite horizon T, the meta-algorithm
finds SPE in at most T+ 1iterations.
The meta-algorithm has several unique advantages. First, as we discuss in Section 4, both inner and
outer optimization tasks can be instantiated with Q-learning. This removes the need to know the
model of the MDP and allows handling of large-scale MDPs by utilizing deep learning. Second, it
can also be seen as iteratively applying a contraction operator, which we formulate as a theorem:
5
Table 1: Correctness of the meta-algorithm in different scenarios
finite horizon T infinite horizon
hidden action finds SPE in T+ 1iterations (Theorem 3.3) may diverge (Appendix B.6)
observed action finds SPE that is also Stackelberg in 1 iteration (Appendix B.7)
Theorem 3.4. Given a principal-agent finite-horizon stochastic game G, each iteration of the meta-
algorithm applies to the principal’s Q-function an operator that is a contraction in the sup-norm.
The proof is provided in Appendix B.5. This property implies that each iteration of the meta-algorithm
monotonically improves the principal’s policy in terms of its Q-function converging. This has a
practical advantage: if meta-algorithm is terminated early, the policies still partially converge to SPE.
As an independent observation, Theorem 3.3 complements the theoretical results of Gerstgrasser
and Parkes [24]. Specifically, their Theorem 2 presents an example where RL fails to converge to a
Stackelberg equilibrium if the agent ‘immediately’ best responds. This procedure is our Algorithm 1,
with agent optimization solved by an oracle and principal optimization performed with RL. Our
Theorem 3.3 complements their negative result by showing that such a procedure converges to SPE.
Finally, while we focus on finite-horizon hidden-action MDPs in the main text, we also analyze the
other scenarios in the Appendix. Our findings are summarized in Table 1.
4 Learning Setting
In this section, we develop an RL approach to principal-agent MDPs by solving both inner and
outer optimization tasks of the meta-algorithm with Q-learning. These tasks correspond to finding
optimal policies in the respective agent’s and principal’s MDPs defined in Observation 3.1. We
operate in a standard model-free RL setting, where learning is performed through interactions with a
black-box MDP. For both principal and agent, we introduce modified Q-functions, which we formally
derive as fixed points of contraction operators in Appendix B.3. We detail deep implementations in
Appendix D. Our approach consists of the following two-phase setup:
1.Training: Principal’s policy is trained ‘for free’ in simulated interactions with agent and
MDP. Principal has access to the learning agent and essentially controls it.
2.Execution / Validation: Trained principal’s policy can be executed or validated against a
black-box (possibly learning) agent.
This is in contrast with the online setup where the principal interacts with an actual black-box agent
during learning, incurring losses from payments in the process [ 31,92]. On the other hand, this setup
is one step ahead of the MARL literature adjacent to our application in Section 5, where the analysis
is typically limited to the training phase.
Agent’s perspective. Consider the agent’s MDP defined by principal’s policy ρ. The best-responding
agent’s Q-function in a state s,Q∗((s, b), a|ρ), depends on the observed contract b– particularly on
the expected payment. This effect can be isolated by applying Bellman optimality operator:
Q∗((s, b), a|ρ) =Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ), (1)
where Q∗(s, a|ρ) = [r(s, a)+γEmax a′Q∗((s′, ρ(s′)), a′|ρ)]is the truncated optimal Q-function,
which represents agent’s expected long-term utility barring the immediate payment. Our approach to
training the agent (solving inner optimization) is to learn the truncated Q-function and compute the
Q-function through (1). This way, the Q-function is defined for any b∈Bins, under an assumption
that the principal plays according to ρin future (e.g., ρ(s′)in the next state). From the agent’s
perspective, this is justified in SPE, where ρis optimal for the principal in all future subgames. Note
that computing the expected payment requires the outcome distribution – if unknown, it can be
approximated as a probabilistic classifier (more on this in Appendix D.1).
Principal’s perspective. Consider the principal’s MDP defined by a best-responding agent π∗(ρ)for
an arbitrary ρ. The basic idea is to divide the principal’s learning problem into two parts: 1) learn the
6
agent’s policy that the principal wants to implement ( recommends to the agent), and 2) compute the
optimal contracts that implement it (the minimal implementation ) using Linear Programming (LP).
Essentially, this extends the classic LP approach from static contract design described in Section 2.1.
To approach the first subproblem, we need an analogue of the principal’s Q-function that is a function
of an agent’s action. To this end, we define the contractual Q-function q∗(π∗(ρ)) :S×A→Rby
q∗(s, ap|π∗(ρ)) = max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)), (2)
which can be interpreted in sas the maximal principal’s Q-value that can be achieved by implementing
ap∈A. To compute the optimal contract arg maxbQ∗(s, b|ρ)using q∗(π∗(ρ)), we can select
the optimal action to implement as arg maxapq∗(s, ap|π∗(ρ)), and then find the corresponding
contract as solution to the conditional maximization in (2). This conditional maximization is the
second subproblem defined above. We solve it as LP (for details, see Appendix B.8):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(3)
Solving this LP requires access to the agent’s truncated Q-function Q∗. Although this requirement
is in line with the training phase of our setup, it can be alleviated, e.g., by approximating optimal
contracts with deep learning [ 79]. We do not explore this direction, so as to not conflate the distinct
learning problems originating from our MDP formulation and the agent being black-box.
Practical concerns. The above instantiation of the meta-algorithm assumes that Q-learning is
run until convergence to precisely solve both inner and outer optimization tasks. In practice, one
has to terminate early and approximate; in case of using deep RL, function approximation also
contributes to the error. In our model, even a small error can have a devastating effect because the
principal’s Q-function is discontinuous : a misestimation of the optimal contract (however slight) may
change the agent’s action, resulting in a worse outcome (see also [ 79]). We empirically validate the
robustness of our implementation to this effect: In Appendix D.1, we apply it to solve toy tree MDPs
(generalizations of Figure 1). Furthermore, our multi-agent experiments in Section 5.3 are validated
in a complex and highly combinatorial sequential social dilemma. We report additional multi-agent
experiments in Appendix D.2, where we apply a form of nudging the agents to desirable behaviour
through extra payments, which helps counteract the degrading effect of approximation errors.
5 Extension to Multi-Agent RL
In this section, we explore an extension to multiple agents. We state the formal model in Section 5.1.
We introduce sequential social dilemmas (SSDs) and the Coin Game (in Section 5.2). We present
experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a | Section not found | Section not found | Section not found | conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this appendix, we provide formal proofs and derivations for the results in Sections 3 and 4.
Appendix B.1 provides additional intuition on the differences between the solution concepts of
Stackelberg and Subgame-Perfect Equilibria. Appendix B.2 supplements Observation 3.1 and defines
the principal’s and agent’s MDPs. Appendix B.3 defines contraction operators useful for succeeding
proofs and connects these operators to the modified Q-functions defined in Section 4. Appendices
B.4 and B.5 present the respective proofs of Theorems 3.3 and 3.4. While the theory in the main
text focuses on the finite-horizon hidden-action scenario, we also discuss the infinite-horizon and
observed-action scenarios in appendices B.6 and B.7, respectively. Finally, the linear program
formulated in Section 4 is derived and described in more detail in Appendix B.8.
Table 2 summarizes the differences between standard MDPs and Principal-Agent MDPs with and
without hidden actions.
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited)
First, consider the SPE notion: At the left subgame, the principal incentivizes the agent to take
noisy-left by choosing a contract that pays 1for outcome Land0otherwise. This way, both actions
yield the same value for the agent, 0.9·1 + 0 .1·0−0.8 = 0 .1·1 + 0 .9·0 = 0 .1, and the
agent chooses aLby tie-breaking in favour of the principal. So the principal’s value in state sLis
0.9(rp(sL, L)−1) = 0 .9(14
9−1) = 0 .5. By the same logic, the principal offers the same contract
insRand its value equals 0.5(and the agent’s value equals 0.1). Then, in s0, the agent is indifferent
between transitioning to sLandsR, so the principal has to offer the same contract again. The
principal’s value in s0(given that the agent chooses aL) is0.5 + 0 .9·0.5 + 0 .1·0.5 = 1 , and the
agent’s value is 0.1 + 0 .9·0.1 + 0 .1·0.1 = 0 .2. These are estimated by considering utilities in sL
andsRwithout discounting (using γ= 1). Note that in this analysis, we found SPE using backward
induction: we first analyzed the terminal states, then the root state.
18
Compare this with Stackelberg: If non-credible threats were allowed, the principal could threaten to
act suboptimally in the right subgame by always paying the agent 0. Both principal and agent then
value sRat0. InsL, the contract is the same as in SPE. Knowing this, the agent values sLoversR
(0.1>0), which would drive it to choose the noisy-left action at the root state even if the principal
pays only 1−0.1 = 0 .9for outcome L. By paying less, the principal’s utility (value in s0) would be
higher compared to SPE, (14
9−0.9 + 0 .5)·0.9 = 1 .04>1.
This illustrates how Stackelberg equilibrium may produce more utility for the principal, but the
surplus comes at the cost of the inability to engage in mutually beneficial contractual agreements
in certain subgames, even if these subgames are reached by pure chance and despite the agent’s
best efforts. On the one hand, Stackelberg requires more commitment power from the principal.
Whereas in SPE the agent can be certain that the principal sticks to its policy in future states because
it is optimal in any subgame, in Stackelberg, the principal has to preemptively commit to inefficient
contracts and ignore potential beneficial deviations. On the other hand, Stackelberg is not robust to
mistakes: if the agent mistakenly chooses the wrong action, it might be punished by the principal,
losing utility for both players. This is especially concerning in the context of learning, where mistakes
can happen due to approximation errors, or even due to the agent exploring (in online setups). SPE is
hence a more practical solution concept.
B.2 Principal’s and Agent’s MDPs (Observation 3.1)
A (standard) MDP is a tuple (S, S 0, A,R,T, γ), where Sis a set of states, S0∈Sis a set of
possible initial states, Ais a set of actions, T:S×A→∆(S)is a stochastic transition function,
R:S×A×S→ P(R)is a stochastic reward function ( R(s, a, s′)is a distribution and may depend
on the next state s′),γis an (optional) discounting factor. Assume finite horizon (as in Section 2).
Consider a hidden-action principal-agent MDP M= (S, s 0, A, B, O, O,R,Rp,T, γ)as defined in
Section 2. First, consider the agent’s perspective. Let the principal’s policy be some ρ. This defines
a standard MDP (Sa, Sa
0, A,Ra,Ta, γ)that we call the agent’s MDP, where: The set of states is
Sa=S×B(infinite unless Bis discretized). The set of initial states is S0={s0} ×B. The set of
actions is A.
The transition function Ta:Sa×A→∆(Sa)defines distributions over next state-contract pairs
(s′, ρ(s′)), where s′∼ T(s, o∼ O(s, a)). Note that the next state s′is sampled from a distribution
that is a function of state-action pairs (s, a)marginalized over outcomes, and the next contract ρ(s′)
is given by the principal’s policy. Informally, the agent expects the principal to stick to its policy
in any future state. At the same time, since the state space Sais defined over the set of contracts
B, the agent may adapt its policy to any immediate contract in the current state, and thus its policy
π:Sa→∆(A)is defined by π(s, b)for any b∈B.
The reward function is a bit cumbersome to formalize because it should not depend on outcomes,
while both OandTcan be stochastic. Specifically, the new reward function has to be stochastic
w.r.t. outcomes: Ra((s, b), a, s′) = [ r(s, a) +b(o)|o∼P(o|s, a, s′)], where the conditional
distribution of outcomes is given by P(o|s, a, s′) =P(O(s,a)=o)P(T(s,o)=s′)P
o∗P(O(s,a)=o∗)P(T(s,o∗)=s′).
Next, consider the principal’s perspective. Let the agent’s policy be some π. This defines a standard
MDP (S,{s0}, B,Rp,Tp, γ)that we call the principal’s MDP, where: the set of states is S; the set
of initial states is {s0}; the set of actions is B(infinite unless discretized); the transition function is
defined by Tp(s, b) =T(s, o∼ O(s, a∼π(s, b))); the reward function is defined similarly to the
agent’s MDP by Rp(s, b, s′) = [r(s, o)−b(o)|o∼P(o|s, a, s′)].
Thus, the optimization task of the principal (agent) given a fixed policy of the agent (principal) can be
cast as a standard single-agent MDP. In both players’ MDPs, the other player’s presence is implicit,
embedded into transition and reward functions. Note that our definition of standard MDP allows for
stochastic reward functions that depend on the next state, as well as a set of initial states that is not
a singleton. The same generalizations can be made in our Principal-Agent MDP definition, and in
particular, the above derivations would still hold, but we decided to slightly specify our model for
brevity.
19
B.3 Contraction Operators and their Fixed Points
Our meta-algorithm iteratively solves a sequence of principal’s and agent’s MDPs as defined in
Appendix B.2. Both tasks can be performed with Q-learning and interpreted as finding fixed points
of the Bellman optimality operator in the respective MDPs. Furthermore, our learning approach in
Section 4 makes use of modified Q-functions, which are also fixed points of contraction operators.
For convenience, we define all four operators below. Where necessary, we prove the operators being
contractions and define their fixed points.
B.3.1 Optimality operators in the agent’s MDP
Here we assume some fixed principal’s policy ρthat defines an agent’s MDP.
Bellman optimality operator. Consider the agent’s optimization task (line 3 of the meta-algorithm).
Solving it implies finding a fixed point of an operator Sρ, which is the Bellman optimality operator in
the agent’s MDP defined by a principal’s policy ρ.
Definition B.1. Given an agent’s MDP defined by a principal’s policy ρ, the Bellman optimality
operator Sρis defined by
(SρQ)((s, b), a) =Eo∼O(s,a),s′∼T(s,o)h
R(s, a, b, o ) +γmax
a′Q((s′, ρ(s′)), a′)i
, (6)
whereR(s, a, b, o ) =r(s, a) +b(o),Qis an element of a vector space QSBA={S×B×A→R},
and subscript ρdenotes conditioning on the principal’s policy ρ.
This operator is a contraction and admits a unique fixed point Q∗(ρ)that satisfies:
V∗(s, b|ρ) = max
aQ∗((s, b), a|ρ), (7)
Q∗((s, b), a|ρ) =Eh
R(s, a, b, o ) +γmax
a′Q∗((s′, ρ(s′)), a′|ρ)i
. (8)
The policy corresponding to the fixed point is called the best-responding policy π∗(ρ):
∀s∈S, b∈B:π∗(s, b|ρ) = arg max
aQ∗((s, b), a|ρ),
where ties are broken in favour of the principal.
Truncated Bellman optimality operator. Here we show that the truncated Q-function Q∗(ρ)
defined in the main text (1)is a fixed point of a contraction operator and thus can be found with
Q-learning.
Definition B.2. Given an agent’s MDP defined by principal’s policy ρ, the truncated Bellman
optimality operator Sρis defined by
(SρQ)(s, a) =r(s, a) +γEo∼O(s,a),s′∼T(s,o)max
a′
Eo′∼O(s′,a′)ρ(s′)(o′) +Q(s′, a′)
,(9)
where Qis an element of a vector space QSA={S×A→R}.
Lemma B.3. Operator Sρis a contraction in the sup-norm.7
Proof. LetQ1,Q2∈ QSA,γ∈[0,1). The operator Sρis a contraction in the sup-norm if it satisfies
∥SρQ1−SρQ2∥∞≤γ∥Q1−Q2∥∞. This inequality holds because:
7In lemmas B.3 and B.6, we show for a case that includes finite- and infinite-horizon MDPs, but requires
γ < 1. For γ= 1and finite-horizon MDPs, per-timestep operators can be shown to be contractions, similar to
the Bellman operator in chapter 4.3 of Puterman [60].
20
∥SρQ1−SρQ2∥∞= max
s,aγEo,s′
max
a′(Eo′ρ(s′)(o′) +Q1(s′, a′))−
max
a′(Eo′ρ(s′)(o′) +Q2(s′, a′))
+r(s, a)−r(s, a)≤
max
s,aγEo,s′max
a′Eo′
ρ(s′)(o′) +Q1(s′, a′)−ρ(s′)(o′)−Q2(s′, a′)=
max
s,aγEo,s′max
a′
Q1(s′, a′)−Q2(s′, a′)≤
max
s,aγmax
s′,a′Q1(s′, a′)−Q2(s′, a′)=γ∥Q1−Q2∥∞.
Because Sρis a contraction as shown in Lemma B.3, by the Banach theorem, it admits a unique fixed
point Q∗
ρs.t.∀s, a:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a). We now show that this fixed point is the truncated
Q-function. Define Qρ((s, b), a) =Eo∼O(s,a)b(o) +Q∗
ρ(s, a). Notice that the fixed point satisfies:
∀s∈S, a∈A:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a)(Eq. 9)=
r(s, a) +γEo,s′max
a′
Eo′ρ(s′)(o′) +Q∗
ρ(s′, a′)
=
r(s, a) +γEo,s′max
a′Qρ((s′, ρ(s′)), a′).
At the same time, by definition:
∀s∈S, a∈A:Q∗
ρ(s, a) =Qρ((s, b), a)−Eo∼O(s,a)b(o).
Combining the above two equations and swapping terms:
∀s∈S, a∈A:Qρ((s, b), a) =r(s, a) +Eo,s′[b(o) +γmax
a′Qρ((s′, ρ(s′)), a′)].
Notice that the last equation shows that Qρis the fixed point of the Bellman optimality operator
Sρ(6), i.e., Qρ=Q∗(ρ), as it satisfies the optimality equations (8). It follows that Q∗((s, b), a|
ρ) =Eob(o) +Q∗
ρ(s, a), and thus Q∗
ρsatisfies the definition of the truncated Q-function (1), i.e.,
Q∗
ρ=Q∗(ρ). The truncated Q-function is then a fixed point of a contraction operator and can be
found with Q-learning. It can also be used to compute the best-responding policy: π∗(s, b|ρ) =
arg maxa[Eob(o) +Q∗(s, a|ρ)].
B.3.2 Optimality operators in the principal’s MDP
Here we assume some fixed best-responding agent’s policy π∗(ρ)that defines a principal’s MDP.
While we could instead assume an arbitrary policy π, we are only interested in solving the principal’s
MDP as the outer level of the meta-algorithm, which always follows the inner level that outputs an
agent’s policy π∗(ρ)best-responding to some ρ.
Bellman optimality operator. Consider the principal’s optimization level (line 4 of the meta-
algorithm). Solving it implies finding a fixed point of an operator Bρ, which is the Bellman optimality
operator in the principal’s MDP defined by the agent’s policy π∗(ρ)is best-responding to some ρ.
Definition B.4. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the Bellman optimality operator Bρis defined by
(BρQ)(s, b) =Eo∼O(s,a),s′∼T(s,o)h
Rp(s, b, o ) +γmax
b′Q(s′, b′)
|a=π∗(s, b|ρ)i
,(10)
where Rp(s, b, o ) =rp(s, o)−b(o),Qis an element of a vector space QSB={S×B→R}, and
subscript ρdenotes conditioning on the agent’s best-responding policy π∗(ρ).
21
This operator is a contraction and admits a unique fixed point Q∗(π∗(ρ))that satisfies optimality
equations:
V∗(s|π∗(ρ)) = max
bQ∗(s, b|π∗(ρ)), (11)
Q∗(s, b|π∗(ρ)) =Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))
|a=π∗(s, b|ρ)i
.(12)
The policy corresponding to the fixed point is called the subgame-perfect policy ρ∗(π∗(ρ)):
∀s∈S:ρ∗(s|π∗(ρ)) = arg max
bQ∗(s, b|π∗(ρ)).
Contractual Bellman optimality operator. Here we show that the contractual Q-function
q∗(π∗(ρ))defined in the main text (2)is a fixed point of a contraction operator and thus can be found
with Q-learning.
Definition B.5. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the contractual Bellman optimality operator Hρis defined by
(Hρq)(s, ap) = max
{b|π∗(s,b|ρ)=ap}Eo∼O(s,ap),s′∼T(s,o)h
Rp(s, b, o ) +γmax
a′q(s′, a′)i
, (13)
where qis an element of a vector space QSA={S×A→R}, and ap∈Adenotes the principal’s
recommended action.
Lemma B.6. Operator Hρis a contraction in the sup-norm.
Proof. Letq1, q2∈ QSA,γ∈[0,1). The operator Hρis a contraction in the sup-norm if it satisfies
∥Hρq1− H ρq2∥∞≤γ∥q1−q2∥∞. This inequality holds because:
∥Hρq1− H ρq2∥∞= max
s,a max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q1(s′, a′)
−
max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q2(s′, a′)=
max
s,aγE[max
a′q1(s′, a′)−max
a′q2(s′, a′)]≤
max
s,aγEmax
a′q1(s′, a′)−max
a′q2(s′, a′)≤
max
s,aγEmax
a′|q1(s′, a′)−q2(s′, a′)| ≤
max
s,aγmax
s′,a′|q1(s′, a′)−q2(s′, a′)|=γ∥q1−q2∥∞.
Because Hρis a contraction as shown in Lemma B.6, by the Banach theorem, it admits a unique fixed
point q∗
ρs.t.∀s, ap:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap). We now show that this fixed point is the contractual
Q-function. Notice that the fixed point satisfies:
∀s∈S: max
apq∗
ρ(s, ap) = max
ap(Hρq∗
ρ)(s, ap)(Eq. 13)=
max
b(Hρq∗
ρ)(s, π∗(s, b|ρ)) = max
b(Hρ(Hρq∗
ρ))(s, π∗(s, b|ρ)) =···=
max
bEX
th
γtRp(st, bt, ot)|s0=s, b0=b, π∗(ρ)i
= max
bQ∗(s, b|π∗(ρ)),(14)
22
and:
∀s∈S, ap∈A:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap)(Eq. 13)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
a′q∗
ρ(s′, a′)i(Eq. 14)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))i(Eq. 12)=
max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)).(15)
Thus, q∗
ρsatisfies the definition of the contractual Q-function (2), i.e., q∗
ρ=q∗(ρ). The contractual
Q-function is then a fixed point of a contraction operator and can be found with Q-learning. The
contractual Q-function can also be used to compute the subgame-perfect principal’s policy as ρ∗(s) =
arg maxb(Hρq∗
ρ)(s, π∗(s, b|ρ)) = arg maxbQ∗(s, b|π∗(ρ)). We address computing the arg max
in Appendix B.8 using Linear Programming.
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3)
Observation B.7. A principal-agent stochastic game Gis in SPE if and only if every subgame of G
is in SPE.
Observation B.7 will be useful for the proofs in this section.
LetSt⊆Sdenote the set of all possible states at time step t. For example, S0={s0}. States in ST
are terminal by definition. We assume that sets Stare disjoint. This is without loss of generality, as
we can always redefine the state space of a finite-horizon MDP such that the assumption holds; e.g.,
by concatenating the time step to a state as snew
t= (st, t). In other words, any finite-horizon MDP
can be represented as a directed acyclic graph.
The next lemma is a precursor to proving the convergence of Algorithm 1 and concerns its single
iteration. Given a pair of policies that form an SPE in all subgames but the original game, it states
that performing one additional iteration of the algorithm (update the agent, then the principal) yields
an SPE in the game. This is because the agent observes the contract offered in a state and adapts
its action, in accordance with our definition of the agent’s MDP in Appendix B.2. In particular,
the agent’s best-responding policy is defined as π∗(s, b|ρ)foranypair(s, b), so in s0, the agent
best-responds with π∗(s0, b|ρ)for any bregardless of the principal’s policy ρ(s0).
Lemma B.8. Given a finite-horizon principal-agent stochastic game Gand a principal’s policy
ρ, if(ρ, π∗(ρ))is an SPE in all subgames with a possible exception of G(i.e., all subgames in
s∈S\ {s0}), then (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G.
Proof. Ins0, the agent observes the principal’s action. Consequently and because the agent best-
responds to ρ, it also best-responds to any {ρ′| ∀s∈S\ {s0}:ρ′(s) =ρ(s)}regardless of the
offered contract ρ′(s0), including the subgame-perfect ρ∗(π∗(ρ))(that only differs from ρins0, as
subgames in other states are in SPE already). Thus, (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G, as well as in
all subgames of G(by Observation B.7).
Corollary B.9. Given Gwith a single subgame ( S={s0}),(ρ∗(π∗(ρ)), π∗(ρ))is an SPE in Gfor
anyρ.
This corollary concerns MDPs with a single state, which could also be interpreted as stateless. This
covers static contract design problems, as well as subgames in terminal states in our model.
By using Lemma B.8, we can now show that each iteration of the algorithm expands the set of
subgames that are in SPE, as long as some subgames satisfy the conditions of the lemma for an
arbitrarily initialized ρ. This is always the case for finite-horizon MDPs, as the subgames in terminal
states have a single subgame (itself), and thus Corollary B.9 applies. This reasoning is used to prove
Theorem 3.3.
Proof of Theorem 3.3. Denote the policy initialized at line 1 as ρ0. Denote the best-responding policy
toρ0asπ1≡π∗(ρ0)and the subgame-perfect policy against π1asρ1≡ρ∗(π1). Likewise, πiand
23
ρirespectively denote the best-responding policy to ρi−1and the subgame-perfect policy against πi,
where iis an iteration of the algorithm.
By Corollary B.9, (ρ1, π1)forms an SPE in all subgames in terminal states, including s∈ST.
Applying Lemma B.8, as well as our assumption that sets Stare disjoint, (ρ2, π2)is an SPE in all
subgames in ST∪ST−1. By induction, (ρi, πi)is an SPE in all subgames in s∈ST∪ST−1··· ∪
ST−i+1. Thus, (ρT+1, πT+1)is an SPE in all subgames in s∈ST∪ ··· ∪ S0=S, and thus in the
gameG(by Observation B.7).
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4)
Consider the principal’s optimization task (line 4 of the meta-algorithm). As we discuss in Ap-
pendix B.3, solving this task can be interpreted as finding the fixed point of a contraction operator Bρ
defined in (10). By definition of contraction, this fixed point can be found by iteratively applying the
operator until convergence, which we denote as H∗=Bρ(Bρ(Bρ...Q(s, b))).
Observation B.10. H∗is a composition of linear operators and thus is a linear operator.
ForH∗to be a contraction, its fixed point has to be unique. Since its iterative application (the
meta-algorithm, Algorithm 1) converges to an SPE, we next prove the uniqueness of Q-functions in
SPE.
Lemma B.11. Given a finite-horizon principal-agent stochastic game G, the principal’s Q-function
is equal in all SPE for any state-action; the same holds for the agent’s Q-function.
Proof. Consider a principal’s policy ρthat forms SPE with any best-responding agent’s policy π∗(ρ).
Anyπ∗(ρ)solves the agent’s MDP and thus all such policies define a unique agent’s Q-function
(which is the fixed point of the Bellman optimality operator). Furthermore, by the assumption that
the agent breaks ties in favor of the principal, all best-responding policies also uniquely define the
principal’s Q-function (in other words, any policy that solves the agent’s MDP but does not maximize
the principal’s Q-function when breaking ties in some state is not a best-responding policy by the
assumed tie-breaking). Thus, for any pair of SPE with non-equal Q-functions, the principal’s policies
must also differ.
Consider two principal’s policies, ρxandρy, that form SPE with any respective best-responding
agents’ policies, π∗(ρx)andπ∗(ρy). By the above argument, the choice of π∗(ρx)andπ∗(ρy)is
inconsequential, so we can assume those to be unique (e.g. by adding lexicographic tie-breaking if
the principal-favored tie-breaking does not break all ties).
Forρxandρyto differ, there must be a state s∈Stsuch that 1) all subgames in states “after” t,
i.e.,{St′}t′>t, are in unique SPE given by some ρandπ∗(ρ)(e.g., this holds in a terminal state)
and 2) the subgame in shas two contracts, bx=ρx(s)andby=ρy(s), that both maximize the
principal’s utility, i.e., Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)). Denote the agent’s actions in s
asax=π∗(s, bx|ρ)anday=π∗(s, by|ρ). We now show that the choice between bxandbyis
inconsequential as both contracts also yield the same utility for the agent.
Assume the agent prefers bxtoby, i.e., Q∗((s, bx), ax|ρ)> Q∗((s, by), ay|ρ). First, use
the observed-action notation. Applying the Bellman optimality operator and using the defi-
nition of R, we have E[r(s, ax) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +bx(ax)>E[r(s, ay) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +by(ay). Observe that the principal may simply decrease the
payment bx(ax)by the difference of the agent’s Q-values (so that the inequality becomes equality),
increasing the principal’s utility. So, the assumption that the agent prefers bxtobymeans that neither
contract maximizes the principal’s utility in the subgame, leading to a contradiction.
The same can be shown in the hidden-action model. The agent preferring bxtoby
would mean E[r(s, ax) +bx(o) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)]>E[r(s, ay) +by(o) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)], and the principal would be able to adjust bxin order to decrease the
expected payment E[bx(o)]relatively to E[by(o)], e.g., by decreasing each non-zero payment bx(o)
by a constant. Again, this leads to a contradiction.
We thus have shown that the choice between bxandbyinsis inconsequential for the value functions
of both principal and agent in s:V∗(s|π∗(ρx)) = Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)) =
V∗(s|π∗(ρy))andV∗(s, bx|ρ) =Q∗((s, bx), ax|ρ) =Q∗((s, by), ay|ρ) =V∗(s, by|ρ). By
Bellman optimality equations ( (7)and(8)for the agent, (11) and(12) for the principal), it is also
24
inconsequential for the players’ Q-functions in all states “before” t, i.e.,{St′}t′<t. For states “after”
t, the choice also has no effect by the MDP being finite-horizon (and our w.l.o.g. assumption about
the uniqueness of states). This holds for any such bxandbyin any s. Thus, for any SPE (ρ, π∗(ρ)),
each player’s Q-function is identical in all SPE for any state-action.
Proof of Theorem 3.4. By Observation B.10, H∗is a linear operator. Moreover, as Algorithm 1
converges to SPE by Theorem 3.3 and the payoffs in SPE are unique by Lemma B.11, the iterative
application of H∗converges to a unique fixed point. By using a converse of the Banach theorem
(Theorem 1 in Daskalakis et al. [13]), this operator is a contraction under any norm that forms a
complete and proper metric space. This includes the sup-norm.
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs
Here we present an example of a hidden-action infinite-horizon principal-agent MDP where the
meta-algorithm diverges by getting stuck in a cycle. To solve the principal’s and agent’s optimization
tasks, we specifically developed exact solvers for principal’s and agent’s MDPs.
The MDP consists of two states, s1ands2. In each state, the agent has two actions, a1anda2, which
determine probabilities of sampling one of two outcomes, o1ando2. When agent chooses a1in any
states, outcomes are sampled with respective probabilities O(o1|s, a 1) = 0 .9andO(o2|s, a 1) =
0.1. Vice versa, choosing a2in any state ssamples an outcome with probabilities O(o1|s, a 2) = 0 .1
andO(o2|s, a 2) = 0 .9. After sampling an outcome oi, the MDP deterministically transitions to si
(e.g., if o1is sampled, the MDP transitions to s1regardless of the old state and the agent’s action).
Choosing an action that is more likely to change the state of the MDP (so, a2ins1anda1ins2)
requires effort from the agent, respectively costing c(s1, a2) = 1 andc(s2, a1) = 2 . The other action
is free for the agent: c(s1, a1) = 0 andc(s2, a2) = 0 . Other things equal, the principal prefers the
agent to invest an effort: it only enjoys a reward whenever the MDP transitions to a different state,
equal to rp(s1, o2) =rp(s2, o1) = 1 .5. The discount factor is set to γ= 0.9.
We now describe several iterations of the meta-algorithm, showing that it oscillates between two pairs
of players’ policies. We report the agent’s truncated Q-function (1)and the principal’s contractual
Q-function (2)at each iteration of the algorithm (rounded to three decimals). We also verify that
these Q-functions are indeed fixed points of respective operators and thus solve the respective MDPs,
but only do so in (s1, a2)as derivations in other state-action pairs are identical.
Initialization
Initialize the principal with a policy ρ0that does not offer any payments, i.e., ρ0(s1) =ρ0(s2) =
(0,0), where we denote a contract by a tuple b= (b(o1), b(o2)).
Iteration 1: agent
The agent’s best-responding policy π1simply minimizes costs by never investing an effort:
π1(s1, ρ0(s1)) =a1,π1(s2, ρ0(s2)) =a2. This corresponds to the following truncated Q-function:
Qπ1(s1, a1) =Qπ1(s2, a2) = 0 ,Qπ1(s1, a2) =−c(s1, a2) =−1andQπ1(s2, a1) =−c(s2, a1) =
−2.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−1 =Qπ1(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1·0 + 0 .9·0] =−1.
In the absence of contracts, the agent’s truncated Q-function is equal to its Q-function under the
principal’s policy: Qπ1((s, ρ 0(s)), a) =Qπ1(s, a).
Iteration 1: principal
The principal’s subgame-perfect policy ρ1attempts to incentivize effort in s1and offers the following
contracts: ρ1(s1) = (0 ,1.25),ρ1(s2) = (0 ,0). This corresponds to the following contractual Q-
function: qρ1(s1, a1) = 1 .991,qρ1(s1, a2) = 2 .048,qρ1(s2, a1) = 1 .391, and qρ1(s2, a2) = 2 .023.
25
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
2.048 = qρ1(s1, a2) =Eo,s′[−ρ1(s1)(o) +rp(s1, o) +γmax
a′qρ1(s′, a′)] =
0.1(0 + 0 + 0 .9·2.048) + 0 .9(−1.25 + 1 .5 + 0 .9·2.023) = 2 .048.
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .5,0), which is not worth it for the
principal, as evidenced by qρ1(s2, a1)< qρ1(s2, a2).
Iteration 2: agent
The principal ρ1underestimated the payment required to incentivize effort, and the agent’s best-
responding policy π2still never invests an effort: π2(s1, ρ1(s1)) = a1,π2(s2, ρ1(s2)) = a2. This
corresponds to the following truncated Q-function: Qπ2(s1, a1) = 0 .723,Qπ2(s1, a2) =−0.598,
Qπ2(s2, a1) =−1.277, and Qπ2(s2, a2) = 0 .402.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−0.598 = Qπ2(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1(0.9(0 + 0 .723) + 0 .1(1.25 + 0 .402))+
0.9(0.1(0 + 0 .723) + 0 .9(0 + 0 .402))] = −0.598.
Given the contracts from the principal’s policy ρ1, we can compute the agent’s Q-values using (1):
Qπ2((s1, ρ1(s1)), a1) = 0 .848,Qπ2((s1, ρ1(s1)), a2) = 0 .527,Qπ2((s2, ρ1(s2)), a1) =−1.277,
andQπ2((s2, ρ1(s2)), a2) = 0 .402. Observe that indeed, the agent still prefers not to invest an effort
ins1, as evidenced by Qπ2((s1, ρ1(s1)), a1)> Qπ2((s1, ρ1(s1)), a2).
Iteration 2: principal
The principal gives up on incentivizing effort and once again offers no contracts: ρ2(s1) = (0 ,0),
ρ2(s2) = (0 ,0). This corresponds to the following contractual Q-function: qρ2(s1, a1) = 1 .661,
qρ2(s1, a2) = 1 .503,qρ2(s2, a1) = 1 .422, and qρ2(s2, a2) = 1 .839.
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, to incentivize a2in
s1, the principal has to offer a contract ρ(s1) = (0 ,1.652) , which gives us:
1.503 = qρ2(s1, a2) =Eo,s′[−ρ2(s2)(o) +rp(s1, o) +γmax
a′qρ2(s′, a′)] =
0.1(0 + 0 + 0 .9·1.661) + 0 .9(−1.652 + 1 .5 + 0 .9·1.839) = 1 .503,
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .098,0), which is still not worth it for
the principal, as evidenced by qρ2(s2, a1)< qρ2(s2, a2).
Subsequent iterations
Because the principal’s subgame-perfect policy ρ2repeats the policy ρ0from a previous iteration, the
meta-algorithm is now stuck in a cycle where iterations 1 and 2 repeat infinitely. In other words, the
meta-algorithm diverges.
B.7 Meta-Algorithm in the Observed-Action Model
In the special case where the agent’s actions are observed (defined in Section 2.2 and summarized
in Table 2), the meta-algorithm can be shown to find SPE in a single (rather than T+ 1) iteration,
as we show in Theorem B.12. This property is based on the observation that the agent is indifferent
between an MDP without a principal and an MDP augmented with a subgame-perfect principal;
similar observation has been made in contemporaneous work [ 3]. Consequently, evaluating minimal
implementation only requires access to the agent’s optimal Q-function in the absence of the principal.
26
Is is also easy to show that SPE coincides with Stackelberg equilibrium in the observed-action
scenario (Lemma B.14), and consequently the meta-algorithm finds Stackelberg equilibrium.
Theorem B.12. Given a principal-agent stochastic game, G, with observed actions and either finite
or infinite horizon, if the principal’s policy is initialized to offer zero-vectors as contracts in all states,
the meta-algorithm finds SPE in one iteration.
Proof of Theorem B.12. Use the same notations of ρiandπias in the proof of Theorem 3.3 in
Appendix B.4.
After initializing ρ0(that always offers 0) and finding the best-responding agent π1, consider the
optimal payments found at the outer optimization level of Algorithm 1. Given a state s∈S, denote
the agent’s action as
a∗= arg max
aQ∗((s,0), a|ρ0).
For now, let contracts in states other than sremain 0; we will omit the conditioning of Q∗onρ0for
brevity. The optimal contract in s, denoted as b∗, reimburses the agent for taking a suboptimal action,
paying exactly
b∗(s, ap) =Q∗((s,0), a∗)−Q∗((s,0), ap)
if the agent selects ap, and pays 0otherwise. Note that b∗=0ifap=a∗. This contract makes the
agent indifferent between apanda∗because
Q∗((s, b∗), ap) =Q∗((s,0), ap) +b∗(s, ap) =Q∗((s,0), a∗),
changing the agent’s action in stoap(according to tie-breaking). However, the agent’s value function
remains unchanged:
V∗(s, b∗) =Q∗((s, b∗), ap) =Q∗((s,0), a∗) =V∗(s,0).
Thus, the Bellman optimality equations (7)and(8)still hold in all states after replacing 0withb∗in
s, and π1still best-responds to the updated principal. This replacement of zero-vectors for optimal
contracts b∗is performed in all states during the update of the principal at the outer optimization
level, yielding a principal’s policy ρ1subgame-perfect against π1. At the same time, π1remains
best-responding against ρ1. Thus, (ρ1, π1)is an SPE.
Remark B.13 .Unlike our general Theorem 3.3, the above proof relies on the specifics of our model
such as the principal’s action set and the players’ reward functions.
Lemma B.14. Given a principal-agent stochastic game, G, with observed actions, any SPE is a
Stackelberg equilibrium.
Proof. Consider an SPE. As discussed in the above proof, the contracts in SPE exactly reimburse the
agent for choosing suboptimal actions, and the agent’s value function when offered such a contract in
some state sremains the same as in the absence of the contract. Additionally, notice that the principal
may never decrease the agent’s value in any state below the value it gets in the absence of contracts
(since payments are non-negative). Thus, the principal may not deviate from SPE by decreasing
the agent’s value in any of the future states through suboptimal contracts in order to incentivize a
suboptimal action apwhile paying less in s.
On the other hand, consider the principal trying to pay less in some state sby increasing the agent’s
value in some future states. If transition function is determenistic, then in order to decrease the
payment in sby some v < b∗(ap)while still incentivizing ap, the principal must, for example,
increase the payment in s′=T(s,O(s, ap))byv/γ– which is inconsequential for the principal’s
value in s(in our model, the discount factor is the same for the principal and the agent). In case
of a stochastic transition function, the increase of payments in future states required to balance the
decrease of the payment in sbyvmay even decrease the principal’s value in scompared to SPE.
Thus, the principal may not deviate from an SPE (commit to non-credible threats) to increase its
value in the initial state, and therefore any SPE is a Stackelberg equilibrium.
27
B.8 Deriving the Linear Program (Section 4)
In Section 4, we describe an RL approach to solving the principal’s MDP that involves two interde-
pendent tasks of 1) learning a policy that the principal wants to implement and 2) computing the
contracts that do so optimally. The former is solved by learning the contractual Q-function (2), which
we derive as a fixed point of a contraction operator Hρ(13) in Appendix B.3. The latter (which is
required as a subroutine to apply Hρ) we solve using Linear Programming, akin to how the static
principal-agent problems are typically solved (as mentioned in Section 2.1).
Given a state s∈Sand an action to recommend ap∈A, rewrite the right-hand side of Hρas the
following constrained optimization problem:
max
b∈BEo∼O(s,ap),s′∼T(s,o)h
rp(s, o)−b(o) +γmax
a′q(s′, a′)i
s.t.
∀a∈A:Q∗((s, b), ap|ρ)≥Q∗((s, b), a|ρ),(16)
where the constraints explicitly require the recommended action apto be at least as ‘good’ for the
agent as any other action a. Note that rp(s, o)andq(s′, a′)are constants with respect to band can
be omitted from the objective. To see that the constraints are linear, apply the Bellman optimality
operator to the agent’s Q-function, and rewrite constraints through the truncated Q-function using (1):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(17)
Because both the objective and the conditions are linear, the problem (17) is an LP.
As discussed in Section 4, our approach to solving the agent’s optimization problem is to learn the
truncated Q-function Q∗(ρ)and transform it into the Q-function by adding the expected payment.
Note that this representation of the agent’s Q-function is used in the constraints of the above LP. The
requirement of the principal having access to the agent’s (truncated) Q-function can be seen as a
limitation of the outlined approach. A potential remedy is to instead parameterize the principal’s
Q-function Q∗(π)with a discontinuous neural network able to efficiently approximate the Q-function
and the solutions to LPs without requiring access to the agent’s private information [ 79]. Of course,
one could also directly learn Q∗(π)with simpler approaches, e.g., by discretizing the contract space
or employing deep RL methods for continuous action spaces (such as Deep Deterministic Policy
Gradient or Soft Actor-Critic).
Solving the LP also requires access to the outcome function O; we discuss in Appendix D.1 how
this can be circumvented by parameterizing the outcome function with an additional neural network,
trained as a probabilistic outcome classifier.
In the special case of the observed-action model, the LP has a simple solution if the agent best-
responds to a specific principal that always offers a zero-vector 0as a contract. In this solution, the
principal exactly reimburses the agent for choosing a (suboptimal) recommended action ap, and pays
0if agent chooses any other action a̸=ap. Similar observation has been made in contemporaneous
work, see end of Section 3.1 in Wu et al. [82].
C Principal-Multi-Agent Example: Prisoner’s Dilemma
Below we illustrate the multi-agent model from Section 5.1 on the example of a simple matrix game.
Consider a standard one-step Prisoner’s Dilemma with the payoff matrix as in Table 3a. Here, the
only equilibrium is mutual defection (DD), despite cooperation (CC) being mutually beneficial. How
should a benevolent principal change the matrix through payments to incentivize cooperation?
One answer is that CC should become an equilibrium through minimal payments in CC. In one of
the payment schemes that achieve this, the principal pays a unit of utility to both players for the
28
Table 3: Prisoner’s Dilemma as a principal-multi-agent game. ‘Def’ denotes ‘Defect’ and ‘Coop’
denotes ‘Cooperate’. Blue highlights principal’s changes of agents’ payoffs.
(a) no payments (b) arbitrary payments in SPE (c) IC payments in SPE
Def Coop
Def 2, 2 4, 0
Coop 0, 4 3, 3Def Coop
Def 2, 2 4, 0
Coop 0, 4 4, 4Def Coop
Def 2, 2 4, 2
Coop 2, 4 4, 4
CC outcome, resulting in the payoff matrix as in Table 3b.8However, note that DD remains an
equilibrium for the agents. In fact, the new payoff matrix is also a social dilemma known as the Stag
Hunt. In the context of (decentralized) learning, there is no reason to expect the agents to converge
to CC instead of DD, and convergence to suboptimal equilibria has been observed empirically in
generalized Stag Hunt games [58].
As a more robust approach, the principal can make action C dominant. This is stronger than just
making CC an equilibrium because each agent will prefer action C regardless of the actions of others.
To achieve this, in addition to paying a unit of utility to both agents in CC, the principal pays two units
of utility to the cooperating agent in CD and DC, resulting in the payoff matrix as in Table 3c. This is
the kind of solution we implement in our application to SSDs, where we formulate the principal’s
objective as learning a social welfare maximizing strategy profile and its minimal implementation.
Importantly, in the context of our principal-agent model, the minimal implementation is consistent
with SPE in that the principal minimizes payments when agents best-respond by following recom-
mendations (CC in our example). So the IC property is an additional constraint, which specifies
an otherwise ambiguous objective of finding the principal’s policy in SPE, and which only requires
additional payments in equilibrium.
Note that in our example, the payment to each agent for the same action depends on the other agent’s
action (e.g., the row agent receives +2 in CD and +1 in CC). This dependence on other agents is
even more pronounced in stochastic games, where payments of a minimal implementation condition
on the policies of others – not only on their immediate actions in the current state but also on their
actions in all possible future states.9For this reason, learning the precise minimal implementation
is generally impractical: consider a neural network used for contract estimation for some agent
explicitly conditioning on the parameters of neural networks of all other agents, or on their actions in
all states of the MDP.
As a tractable alternative, we use a simple approximation that performs well in our experiments.
Specifically, we train the principal assuming that each agent sticks to one of two policies: either
always follow the principal’s recommendations and get paid, or ignore them and act independently as
if there is no principal. In equilibrium, both policies maximize the agent’s welfare, which justifies the
assumption. For | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | implementation details of this approximation, see Appendix D.2.
D Experiments
D.1 Experiments in Tree MDPs
In this section, we empirically test the convergence of Algorithm 1 towards SPE in hidden-action
MDPs. We experiment with a small variation on the algorithm, which expedites convergence: the
agent and principal policies are updated simultaneously instead of iteratively. This can be seen as
terminating inner and outer tasks early, after one update, leading to approximately optimal policies.
Environment. In these experiments, we simulate a multi-stage project in which the principal offers
contracts at intermediate stages, influencing the agent’s choice of effort. Specifically, we model an
MDP that is a complete binary tree, where the agent’s decisions at each state are binary, representing
8Unlike the single-agent model, the optimal payment scheme here is ambiguous. Any payment scheme that
gives a unit of utility to both agents in CC and no utility to a defecting agent in DC and CD forms an SPE when
coupled with best-responding agents: CC becomes an equilibrium, the payments in which are minimized.
9Here we refer to the dependence of value functions on π−iin the IC constraints (5).
29
Algorithm 2 A deep Q-learning implementation of Algorithm 1 in the single-agent setting
Require: principal’s Q-network θ, agent’s Q-network ϕ, target networks θ′andϕ′, replay buffer RB
1:Initialize buffer RBwith random transitions, networks θandϕwith random parameters
2:fornumber of updates do ▷Training loop
3: fornumber of interactions per update do ▷Interact with the MDP
4: Select an action to recommend, ap, with qθ(s, a)viaϵ-greedy
5: Sample o∼ O(s, a),ra=r(s, a),rp=rp(s, o), transition the MDP to s′∼ T(s, o)
6: Add the transition (s, ap, ra, rp, o, d, s′)to the buffer RB
7: Ifd= 1, reset the MDP ▷ dis a binary ‘done’ variable indicating termination
8: Sample a mini-batch of transitions mb∼RB
9: for(s, ap, ra, rp, o, d, s′)∈mbdo ▷Estimate target variables to update θandϕ
10: ap′= arg maxa′qθ(s′, a′) ▷Select the next action for Q-learning updates
11: Find optimal contracts b∗(s, ap)andb∗(s′, ap′)by solving LP (17)
12: yp(s, ap) =rp−b∗(s, ap, o) +γ(1−d)qθ′(s′, ap′)
13: ya(s, ap) =ra+γ(1−d)(Eo′∼O(s′,ap′)b∗(s′, ap′, o′) +Qϕ′
(s′, ap′))
14: Minimize L(θ) =P
mb
qθ(s, ap)−yp(s, ap)2▷Update θas DQN
15: Minimize L(ϕ) =P
mb
Qϕ(s, ap)−ya(s, ap)2
▷Update ϕas DQN
high or low effort, and correspond to good or bad outcomes with different probabilities. This is an
intentionally simple environment, allowing us to compare with precise ground truth.
The MDP is represented by a complete binary decision tree with depth 10, resulting in 1023 states.
In each state, the agent may take two actions, a0anda1, which may result in two outcomes, o0and
o1. The action a0results in the outcome o0with probability 0.9in all states; likewise, a1results in o1
with probability 0.9. The tree transitions to the left subtree after outcome o0and to the right subtree
after outcome o1.
The action a0yields no cost for the agent, i.e., ∀s:r(s, a 0) = 0 ; and the outcome o0yields no
reward for the principal, i.e. ∀s:rp(s, o 0) = 0 . Conversely, the action a1is always costly and
the outcome o1is always rewarding, with values randomly sampled. Specifically, let Udenote
one-dimensional uniform distribution, U1=U[0,1]andU2=U[0,2]. Then, the agent’s reward
is generated as r(s, a 1) =−(u∼U[0,1−(v∼U1)]), and the principal’s reward is generated as
rp(s, o 1) = (u∼U[0,2−(v∼U2)])Note that the principal’s reward is on average higher than the
agent’s cost. Using this reward function sampling method, the principal’s policy ρ∗in SPE offers
non-trivial contracts that incentivize a1in about 60% of states.
Experimental procedure. We generate three instances of the Tree MDP, each with randomly
sampled reward functions, and used five trials of our algorithm on each Tree MDP. We also use
backward induction to find the exact policies in SPE (π∗, ρ∗)and the corresponding optimal utilities,
which we adopt as the ground truth. By comparing with ground truth directly, our two-phase procedure
from Section 4 becomes somewhat redundant, so we defer it to our multi-agent experiments in a
significantly more complex MDP.
Implementation details. We parameterize the principal’s and the agent’s Q-functions as Deep
Q-Networks [51] respectively denoted by θandϕ. The input to both networks is a state s, and both
networks approximate Q-values for all actions a∈A. Specifically, the principal’s network estimates
the contractual optimal Q-values qθ(s, a), representing its payoffs when optimally incentivizing the
agent to take action ain state s; and the agent’s network estimates the truncated optimal Q-values
Qϕ(s, a), representing its payoffs minus the expected immediate payment.
Algorithm 2 describes our Deep Q-learning-based implementation of Algorithm 1 for the single-agent
MDPs. The overall pipeline is standard, with a few notable details.
First, unlike the iterative convergence of the principal and the agent in Algorithm 1, the two policies
are trained simultaneously.
30
(a) Principal’s utility
(b) Agent’s utility
(c) Accuracy of Principal Action
Figure 3: Results in Tree MDPs. Solid lines are learning curves of DQNs trained with Algorithm 2.
Dashed lines represent ‘optimal’ utilities in SPE obtained with dynamic programming. Different
colors represent three distinct instances of the tree environment. For each, we use five trials of the
algorithm (shaded regions represent standard errors).
Second, the outcome function Ois assumed to be known. If not, it can be parameterized as an
additional neural network ξand trained as a probabilistic classifier with sampled outcomes used
as ground truth; the resulting loss function would be L(ξ) =P
mbCE[Oξ(s, ap), o], where CE
denotes cross-entropy, mbdenotes a mini-batch, and Oξ(s, ap)denotes the predicted probabilities of
outcomes as a function of state-action. We implemented this in our single-agent experiments with O
constant across states and found no difference from having access to O, although this might change
in more complex scenarios.
Third, when updating the agent’s network ϕ, the target variable yϕ′(s, ap)is estimated based on the
contract in the next state s′rather than the current state s. Since payment is a part of reward, the
target variable is effectively estimated as a mixture of parts of rewards in sands′. This is required so
that the truncated rather than the standard Q-function is learned.
Hyperparameters. The neural networks have 2hidden fully connected layers, each consisting
of256neurons and followed by a ReLU activation. The networks are trained for 20000 iterations,
each iteration including 8environment interactions and a single gradient update on a mini-batch
with128transitions, sampled from the replay buffer. Every 100iterations, the target networks are
updated by copying the parameters of the online networks. The learning rate is initialized at 0.001
and is exponentially annealed to 0.0001 throughout the training. Similarly, the exploration rate ϵis
initialized at 1and is linearly annealed to 0throughout the training. Rewards are not discounted, i.e.,
γ= 1.
Results. The results are presented in Figure 3. From Figure 3a, we observe that our algorithm
attains a principal’s utility of just 2%below the optimal utility in SPE. On the other hand, Figure 3b
shows that the agent’s utility can exhibit similar (in absolute terms) deviations from SPE in either
direction. The ’accuracy’ metric in Figure 3c indicates that the principal recommends the action
prescribed by the optimal policy in approximately 90% of the states.
The small underperformance in the principal’s utility and the biases in the agent’s utility can be
partially attributed to the 10% of the non-optimal principal’s actions. That around 90% of correct
actions amount to around 98% of the principal’s utility suggests errors likely occur in rarely visited
states or states where actions result in similar payoffs. effectiveness in approximating the SPE. The
minor discrepancies in utility, coupled with the learning dynamics, underscore the complex interplay
between the principal and the agent as they adapt to each other throughout training.
D.2 Experiments in the Coin Game
Implementation details. Algorithm 3 describes our Deep Q-learning-based implementation of
Algorithm 1 for the multi-agent MDPs with self-interested agents, often referred to as “sequential
social dilemmas”. The experimental procedure consists of two phases: training and validation.
In the training phase, for each agent i, the principal’s objective is to find a policy to recommend
by learning the contractual Q-function, qθ
i, as well as its minimal implementation by learning the
agent’s Q-function in the absence of the principal, Qϕ
i. In Section 5.1, we additionally require the
31
(a) Social welfare
(b) Social welfare, nudging
(c) Proportion of social welfare paid
(d) Accuracy
(e) Convergence to SPE?
(f) Incentive-Compatible contracts?
Figure 4: Learning curves in the Coin Game with a 3×3grid and each episode lasting for 20
time steps. The structure is the same as in Figure 2, with the addition of the top middle plot. The
definition of the plots is as follows: a) total return of the two agents (without payments); b) same,
but our algorithm and constant baseline additionally pay 10% of social welfare to the agents; c) a
ratio of the total payment by the principal to what the agents would effectively be paid if directly
maximizing social welfare; d) the proportion of the principal’s recommendations followed by the
validation agents; r) a ratio between the utilities of an agent’s policy at a given iteration and the
recommended policy, with the opponent using the recommended policy; f) same ratio, but with the
opponent’s policy at a given iteration. Each experiment is repeated 5 times, and each measurement is
averaged over 80 episodes.
minimal implementation to be in dominant strategies. Learning such an implementation requires
conditioning Qϕ
ion the inter-agent policies π−i, which is intractable. As a tractable approximation,
given that rational agents will only deviate from recommendations if their expected payoffs are
not compromised, we simplify each agent’s strategy space to two primary strategies: cooperation
(following the principal’s recommendations) or rational deviation (default optimal policy disregarding
contracts, which gives the same utility). We encapsulate this behavior in a binary variable fi∈ {0,1},
indicating whether agent ifollows the recommendation ap. Then, Qϕ
iis conditioned on the joint f−i
variable of the other agents, indicating both the immediate outcome and the agents’ future behavior.
The efficacy of this simplification is validated through our | experimental results in Section 5.3.
5.1 Problem Setup
Both our principal-agent model and our theory for the meta-algorithm can be extended to multi-agent
MDPs. First, we formulate an analogous principal-multi-agent MDP, where a principal offers a
contract to each agent, and payments are determined by the joint action of all agents. We treat joint
actions as outcomes and omit hidden actions. Then, the theory extends by viewing all agents as a
centralized super-agent that selects an equilibrium joint policy (in the multi-agent MDP defined by the
principal). Finally, we address the issue of multiple equilibria by imposing an additional constraint
on incentive-compatibility of contracts, making our approach more robust to deviations. See also
Appendix C, where we illustrate the multi-agent model on Prisoner’s Dilemma.
Aprincipal-multi-agent MDP is a tuple MN= (S, s 0, N,(Ai)i∈N, B,T,(Ri)i∈N,Rp, γ). The
notation is as before, with the introduction of a set of kagents, N, and the corresponding changes: Ai
is the action set of agent i∈Nwithnielements; ANis the joint action set with m=Q
inielements,
defined as a Cartesian product of sets Ai;B⊂Rm
≥0is a set of contracts the principal may offer to an
agent; bidenotes a contract offered to agent i, and bi(a)denotes a payment to idetermined by joint
action a∈AN;T:S×AN→∆(S)is the transition function; Ri:S×AN×B→Ris the reward
function of agent idefined by Ri(s,a, bi) =ri(s,a) +bi(a)for some ri;Rp:S×AN×Bk→R
is the principal’s reward function defined by Rp(s,a,b) =rp(s,a)−P
ibi(a). In our application,
7
the principal’s objective is to maximize agents’ social welfare through minimal payments, so we
define its reward by rp(s,a) =1
αP
iri(s,a), where 0< α < 1is a hyperparameter that ensures
that payment minimization is a secondary criterion and does not hurt social welfare (we use α= 0.1).
Additionally, ρ:S→Bkis the principal’s policy, and πi:S×B→∆(Ai)is an agent’s policy.
Because Bgrows exponentially with the number of agents k, in our implementation, the principal
gives an action recommendation to each agent, and the payments are determined after agents act.
Analogously to Observation 3.1, a fixed principal’s policy ρdefines a multi-agent MDP by changing
the agents’ reward functions. Importantly, this MDP can itself be analyzed as a Markov game between
the agents [ 47]. In this game, we use a basic solution concept called Markov Perfect Equilibrium
(MPE) [50], defined as a tuple of agents’ policies π∗(ρ)such that the following holds:
∀s, bi, i, π i:Vπ∗
i(ρ)
i (s, bi|π∗
−i(ρ), ρ)≥Vπi
i(s, bi|π∗
−i(ρ), ρ). (4)
Here,π∗
−i(ρ)denotes equilibrium policies of agents other than i, and Vπi
i(· |π−i, ρ)is the value
function of agent iplaying πigiven that other agents play π−iand principal plays ρ. In MPE, no
agent has a beneficial, unilateral deviation in any state.
Call MPE π∗(ρ)abest-responding joint policy ; in case there are multiple, assume that agents break
ties in favor of the principal. This assumption allows agents to freely coordinate the joint action,
similarly to the equilibrium oracle of Gerstgrasser and Parkes [24]. The principal’s subgame-perfect
policy is defined by ρ∗(s|π)∈arg maxbQ∗(s, b|π), and an SPE is defined as a pair of policies
(ρ,π∗(ρ))that are respectively subgame-perfect and best-responding against each other.
With this, our theory in Section 3 can be extended to the multi-agent model. Particularly, convergence
proofs of Algorithm 1 apply with the swap of notation and the new definition of best-responding policy
π∗(ρ). However, implementing this theory is problematic because of how strong the tie-breaking
assumption is. In practice, there is no reason to assume that decentralized learning agents will
converge to any specific equilibrium. For example, even in simple games such as Iterated Prisoner’s
Dilemma, RL agents typically fail to converge to cooperative Tit-for-Tat equilibrium [23, 81].
To provide additional robustness, we specify the principal’s policy ρin SPE by requiring that it
implements MPE π∗(ρ)in dominant strategies . Specifically, ρmust additionally satisfy:
∀s, bi, i, π i,π−i:Vπ∗
i(ρ)
i (s, bi|π−i, ρ)≥Vπi
i(s, bi|π−i, ρ). (5)
This way, an agent prefers π∗
i(ρ)regardless of other players’ policies. We refer to contracts that
make a strategy profile dominant as Incentive-Compatible (IC) , and to the IC contracts that minimize
payments as a minimal implementation . In these terms, the principal’s objective is to learn a social
welfare maximizing strategy profile and its minimal implementation. This solution concept is inspired
by the k-implementation of Monderer and Tennenholtz [52].
5.2 A Sequential Social Dilemma: The Coin Game
In this section, we augment a multi-agent MDP known as the Coin Game [23] with a principal and
conduct a series of experiments. These experiments complement our theoretical results by empirically
demonstrating the convergence of our algorithm to SPE in a complex multi-agent setting. On the
other hand, we find a minimal implementation of a strategy profile that maximizes social welfare in a
complex SSD, which is a novel result of independent interest, as discussed in the Introduction.
Environment. The Coin Game is a standard benchmark in Multi-Agent RL that models an SSD
with two self-interested players that, if trained independently, fail to engage in mutually beneficial
cooperation. This environment is highly combinatorial and complex due to a large state space and
the inherent non-stationarity of simultaneously acting and learning agents. Each player is assigned a
color, red or blue, and collects coins that spawn randomly on a grid. Players earn +1for collecting a
coin of their color and +0.2for other coins.6Our experiments are carried out on a 7×7grid with
each episode lasting for 50time steps; results on a smaller grid are provided in Appendix D.2.
Experimental procedure. Given the complexity of the Coin Game, comparing with exact solutions
is infeasible. Instead, we implement the two-phase approach described in Section 4. First, we
parameterize principal’s and agent’s Q-functions as deep Q-networks, θandϕ, and train them
6We use the rllib code but remove the penalty a player incurs if its coin is picked up by the other player.
8
(a) Social welfare
(b) Proportion of social welfare paid
(c) Accuracy
(d) Convergence to SPE?
(e) Incentive-Compatible contracts?
Figure 2: Learning curves in the Coin Game. See Section 5.3 for plot explanations. Shaded regions
represent standard errors in the top plots and min-max ranges in the bottom plots.
centrally using VDN [ 74] and parameter sharing. Then, the trained principal’s policy is validated by
training from scratch new, black-box agents. For details and pseudocode, see Appendix D.2.
For baselines, we compare against a heuristic that distributes a constant proportion of social welfare.
For a fair comparison, this proportion is set to be exactly equal to the proportion that our method ends
up paying after the validation phase. This heuristic is at the core of approaches that improve social
welfare through contractual agreements between agents (Christoffersen et al. [8], see Appendix A).
We also include a selfish baseline with self-interested agents in the absence of contracts, and an
optimal baseline where agents are fully cooperative and directly maximize social welfare. These are
instances of the constant proportion baseline with the proportion set to 0and1, respectively.
5.3 Experimental Results
The results are presented in Figure 2. The social welfare metric (Fig. 2a) shows a gap between the
performances of selfish and optimal baselines, confirming the presence of a conflict of interests.
During training, our algorithm finds a joint policy that matches the optimal performance, and is
implemented with an average payment of just above 30% of social welfare, substantially reducing
the intervention into the agents’ rewards compared to the optimal baseline (Fig. 2b).
After the validation phase, the social welfare and the proportion paid to agents closely match the
corresponding metrics in training. Furthermore, the agents follow the principal’s recommendations in
around 80% to90% of states in an average episode (Fig. 2c). These results suggest that the principal
closely approximated the SPE, as agents deviate only rarely and in states where it does not hurt
social welfare. Given the challenges of convergence of independent RL agents to mutually beneficial
equilibria, we find this success quite surprising, and attribute it to the IC property of the principal.
From the perspective of an agent, there could be other optimal policies against different opponents,
but following the principal’s recommendations is robust against anyopponent.
We also see that the constant proportion baseline is much less effective than our algorithm when
given the same amount of budget. The heuristic scheme overpays in some states while underpaying
in others—incentivizing agents to selfishly deviate from a welfare-optimizing policy.
These results suggest the algorithm’s convergence to SPE and the IC property of contracts. To further
verify this, we collect additional metrics throughout the validation phase. Consider the perspective
of the blue agent (Blue). At a given iteration, we fix the red agent’s (Red’s) policy, estimate Blue’s
utilities (average returns) under its policy and the recommended policy, and compare their ratio. In
this scenario, if Red follows a recommended policy, then a utility ratio exceeding 1would mean
that there is a better policy for Blue than the recommended one, indicating a violation of the SPE
condition (4)ins0. We report this ratio in Figure 2d. Although agents occasionally discover slightly
9
more profitable policies, the average utility ratio hovers around 1, indicating an approximate SPE. In
the same scenario, if instead, Red acts according to its own policy, then a utility ratio exceeding 1for
Blue would indicate a violation of the IC conditions (5)ins0. We report this ratio in Figure 2e. It
behaves similarly, in that the average ratio again hovers around 1. We conclude that the principal is
finding a good approximation to a minimal implementation that maximizes social welfare.
6 Conclusion
In this work, we take an automated design approach to delegated single- and multi-agent RL problems.
In addition to providing a formal definition of such problems, we give a simple algorithmic blueprint
for solving these games through contracts, and show convergence to SPE. We offer a deep RL
implementation, and empirically validate the guarantees of our algorithms. We also explore an
application of the contract-driven approach to sequential social dilemmas, showing how they can
be an effective tool for maximizing social welfare with minimal intervention. Our research, and
particularly the application to SSDs, opens the door to many exciting follow-up questions. While the
Coin Game presents a challenging setup, it would be interesting to further scale our algorithms to
even more complex environments. Partially-observable settings could be of particular interest due to
the potential information asymmetry between the principal and the agents. Additionally, allowing the
principal to randomize contracts could enhance its ability to coordinate agents. Overall, we hope this
study will make the field of contract design more accessible to the RL community, as well as allow
contract design to scale to previously infeasible problems.
References
[1]N. Ananthakrishnan, S. Bates, M. Jordan, and N. Haghtalab. Delegating data collection in
decentralized machine learning. In International Conference on Artificial Intelligence and
Statistics , pages 478–486. PMLR, 2024.
[2]T. Baumann, T. Graepel, and J. Shawe-Taylor. Adaptive mechanism design: Learning to
promote cooperation. In 2020 International Joint Conference on Neural Networks (IJCNN) ,
pages 1–7. IEEE, 2020.
[3]O. Ben-Porat, Y . Mansour, M. Moshkovitz, and B. Taitler. Principal-agent reward shaping in
mdps. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 38, pages
9502–9510, 2024.
[4]L. Biewald. Experiment tracking with weights and biases, 2020. URL https://www.wandb.
com/ . Software available from wandb.com.
[5]G. Brero, A. Eden, D. Chakrabarti, M. Gerstgrasser, V . Li, and D. C. Parkes. Learning stackel-
berg equilibria and applications to economic design games. arXiv preprint arXiv:2210.03852 ,
2022.
[6]S. Chakraborty, A. S. Bedi, A. Koppel, D. Manocha, H. Wang, M. Wang, and F. Huang. Parl: A
unified framework for policy alignment in reinforcement learning. In The Twelfth International
Conference on Learning Representations , 2023.
[7]S. Chen, D. Yang, J. Li, S. Wang, Z. Yang, and Z. Wang. Adaptive model design for Markov
decision process. In International Conference on Machine Learning , pages 3679–3700. PMLR,
2022.
[8]P. J. Christoffersen, A. A. Haupt, and D. Hadfield-Menell. Get it in writing: Formal con-
tracts mitigate social dilemmas in multi-agent RL. In Proceedings of the 2023 International
Conference on Autonomous Agents and Multiagent Systems , pages 448–456, 2023.
[9]V . Conitzer and N. Garera. Learning algorithms for online principal-agent problems (and selling
goods online). In Proceedings of the 23rd international conference on Machine learning , pages
209–216, 2006.
[10] V . Conitzer and T. Sandholm. Complexity of mechanism design. In Proceedings of the
Eighteenth conference on Uncertainty in artificial intelligence , pages 103–110, 2002.
10
[11] V . Conitzer and T. Sandholm. Automated mechanism design: Complexity results stemming
from the single-agent setting. In Proceedings of the 5th international conference on Electronic
commerce , pages 17–24, 2003.
[12] V . Conitzer and T. Sandholm. Self-interested automated mechanism design and implications
for optimal combinatorial auctions. In Proceedings of the 5th ACM Conference on Electronic
Commerce , pages 132–141, 2004.
[13] C. Daskalakis, C. Tzamos, and M. Zampetakis. A converse to Banach’s fixed point theorem and
its CLS-completeness. In Proceedings of the 50th Annual ACM SIGACT Symposium on Theory
of Computing , pages 44–50, 2018.
[14] Z. Duan, J. Tang, Y . Yin, Z. Feng, X. Yan, M. Zaheer, and X. Deng. A context-integrated
transformer-based neural network for auction design. In International Conference on Machine
Learning . PMLR, 2022.
[15] Z. Duan, H. Sun, Y . Chen, and X. Deng. A scalable neural network for DSIC affine maximizer
auction design. In Thirty-seventh Conference on Neural Information Processing Systems , 2023.
URL https://openreview.net/forum?id=cNb5hkTfGC .
[16] I. Durugkar, E. Liebman, and P. Stone. Balancing individual preferences and shared objectives
in multiagent reinforcement learning. Good Systems-Published Research , 2020.
[17] P. Dütting, F. Fischer, P. Jirapinyo, J. K. Lai, B. Lubin, and D. C. Parkes. Payment rules through
discriminant-based classifiers. ACM Transactions on Economics and Computation , 3(1), 2015.
[18] P. Dütting, Z. Feng, H. Narasimhan, D. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning. In International Conference on Machine Learning , pages 1706–1715.
PMLR, 2019.
[19] P. Dütting, T. Roughgarden, and I. Talgam-Cohen. Simple versus optimal contracts. In
Proceedings of the 2019 ACM Conference on Economics and Computation, EC 2019, Phoenix,
AZ, USA, June 24-28, 2019 , pages 369–387, 2019.
[20] P. Dütting, T. Exra, M. Feldman, and T. Kesselheim. Multi-agent contracts. In ACM STOC
2023 , pages 1311–1324, 2023.
[21] P. Dütting, Z. Feng, H. Narasimhan, D. C. Parkes, and S. S. Ravindranath. Optimal auctions
through deep learning: Advances in differentiable economics. Journal of the ACM , 71(1):1–53,
2024.
[22] T. Eccles, E. Hughes, J. Kramár, S. Wheelwright, and J. Z. Leibo. Learning reciprocity in
complex sequential social dilemmas. arXiv preprint arXiv:1903.08082 , 2019.
[23] J. Foerster, R. Y . Chen, M. Al-Shedivat, S. Whiteson, P. Abbeel, and I. Mordatch. Learning
with opponent-learning awareness. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 122–130, 2018.
[24] M. Gerstgrasser and D. C. Parkes. Oracles & followers: Stackelberg equilibria in deep multi-
agent reinforcement learning. In International Conference on Machine Learning , pages 11213–
11236. PMLR, 2023.
[25] N. Golowich, H. Narasimhan, and D. C. Parkes. Deep learning for multi-facility location
mechanism design. In IJCAI , pages 261–267, 2018.
[26] S. J. Grossman and O. D. Hart. An analysis of the principal-agent problem. Econometrica , 51
(1):7–45, 1983.
[27] J. K. Gupta, M. Egorov, and M. Kochenderfer. Cooperative multi-agent control using deep
reinforcement learning. In International conference on autonomous agents and multiagent
systems , pages 66–83. Springer, 2017.
11
[28] B. Guresti, A. Vanlioglu, and N. K. Ure. Iq-flow: Mechanism design for inducing cooperative
behavior to self-interested agents in sequential social dilemmas. In Proceedings of the 2023
International Conference on Autonomous Agents and Multiagent Systems , pages 2143–2151,
2023.
[29] G. Guruganesh, Y . Kolumbus, J. Schneider, I. Talgam-Cohen, E.-V . Vlatakis-Gkaragkounis, J. R.
Wang, and S. M. Weinberg. Contracting with a learning agent. arXiv preprint arXiv:2401.16198 ,
2024.
[30] C. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. J. Artif. Intell. Res. , 55:317–359,
2016.
[31] C.-J. Ho, A. Slivkins, and J. W. Vaughan. Adaptive contract design for crowdsourcing markets:
Bandit algorithms for repeated principal-agent problems. In Proceedings of the fifteenth ACM
conference on Economics and computation , pages 359–376, 2014.
[32] B. Holmström. Moral hazard and observability. The Bell Journal of Economics , 10:74–91,
1979.
[33] Y . Hu, W. Wang, H. Jia, Y . Wang, Y . Chen, J. Hao, F. Wu, and C. Fan. Learning to utilize shaping
rewards: A new approach of reward shaping. Advances in Neural Information Processing
Systems , 33:15931–15941, 2020.
[34] E. Hughes, J. Z. Leibo, M. Phillips, K. Tuyls, E. Dueñez-Guzman, A. García Castañeda,
I. Dunning, T. Zhu, K. McKee, R. Koster, et al. Inequity aversion improves cooperation in
intertemporal social dilemmas. Advances in neural information processing systems , 31, 2018.
[35] D. Ivanov, V . Egorov, and A. Shpilman. Balancing rational and other-regarding preferences in
cooperative-competitive environments. In Proceedings of the 20th International Conference on
Autonomous Agents and MultiAgent Systems , pages 1536–1538, 2021.
[36] D. Ivanov, I. Safiulin, I. Filippov, and K. Balabaeva. Optimal-er auctions through attention.
Advances in Neural Information Processing Systems , 35:34734–34747, 2022.
[37] D. Ivanov, I. Zisman, and K. Chernyshev. Mediated multi-agent reinforcement learning. In
Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent
Systems , pages 49–57, 2023.
[38] N. Jaques, A. Lazaridou, E. Hughes, C. Gulcehre, P. Ortega, D. Strouse, J. Z. Leibo, and
N. De Freitas. Social influence as intrinsic motivation for multi-agent deep reinforcement
learning. In International conference on machine learning , pages 3040–3049. PMLR, 2019.
[39] J. Jiang and Z. Lu. Learning fairness in multi-agent systems. Advances in Neural Information
Processing Systems , 32, 2019.
[40] J. M. Kleinberg and M. Raghavan. How do classifiers induce agents to invest effort strategically?
ACM Trans. Economics and Comput. , 8(4):19:1–19:23, 2020.
[41] S. Lahaie. A kernel-based iterative combinatorial auction. In Proceedings of the AAAI Confer-
ence on Artificial Intelligence , volume 25, pages 695–700, 2011.
[42] J. Z. Leibo, V . Zambaldi, M. Lanctot, J. Marecki, and T. Graepel. Multi-agent reinforcement
learning in sequential social dilemmas. In Proceedings of the 16th Conference on Autonomous
Agents and MultiAgent Systems , pages 464–473, 2017.
[43] W. D. Li, N. Immorlica, and B. Lucier. Contract design for afforestation programs. In WINE
2021 , pages 113–130, 2021.
[44] E. Liang, R. Liaw, R. Nishihara, P. Moritz, R. Fox, K. Goldberg, J. Gonzalez, M. Jordan, and
I. Stoica. Rllib: Abstractions for distributed reinforcement learning. In International conference
on machine learning , pages 3053–3062. PMLR, 2018.
[45] A. Likhodedov, T. Sandholm, et al. Approximating revenue-maximizing combinatorial auctions.
InAAAI , volume 5, pages 267–274, 2005.
12
[46] Y . Lin, W. Li, H. Zha, and B. Wang. Information design in multi-agent reinforcement learning.
Advances in Neural Information Processing Systems , 36, 2024.
[47] M. L. Littman. Markov games as a framework for multi-agent reinforcement learning. In
Machine learning proceedings 1994 , pages 157–163. Elsevier, 1994.
[48] X. Liu, C. Yu, Z. Zhang, Z. Zheng, Y . Rong, H. Lv, D. Huo, Y . Wang, D. Chen, J. Xu, et al.
Neural auction: End-to-end learning of auction mechanisms for e-commerce advertising. In
Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery & Data Mining ,
pages 3354–3364, 2021.
[49] S. Lu. Bilevel optimization with coupled decision-dependent distributions. In International
Conference on Machine Learning , pages 22758–22789. PMLR, 2023.
[50] E. Maskin and J. Tirole. Markov perfect equilibrium: I. observable actions. Journal of Economic
Theory , 100(2):191–219, 2001.
[51] V . Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves,
M. Riedmiller, A. K. Fidjeland, G. Ostrovski, et al. Human-level control through deep rein-
forcement learning. Nature , 518(7540):529–533, 2015.
[52] D. Monderer and M. Tennenholtz. k-implementation. In Proceedings of the 4th ACM conference
on Electronic Commerce , pages 19–28, 2003.
[53] H. Narasimhan, S. B. Agarwal, and D. C. Parkes. Automated mechanism design without money
via machine learning. In Proceedings of the 25th International Joint Conference on Artificial
Intelligence , 2016.
[54] C. Oesterheld, J. Treutlein, R. B. Grosse, V . Conitzer, and J. N. Foerster. Similarity-based
cooperative equilibrium. In Thirty-seventh Conference on Neural Information Processing
Systems , 2023.
[55] M. J. Osborne. An introduction to game theory , volume 3. Oxford university press New York,
2004.
[56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin,
N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning
library. Advances in neural information processing systems , 32, 2019.
[57] A. Peysakhovich and A. Lerer. Consequentialist conditional cooperation in social dilemmas
with imperfect information. In International Conference on Learning Representations , 2018.
[58] A. Peysakhovich and A. Lerer. Prosocial learning agents solve generalized stag hunts better
than selfish ones. In Proceedings of the 17th International Conference on Autonomous Agents
and MultiAgent Systems , pages 2043–2044. International Foundation for Autonomous Agents
and Multiagent Systems, 2018.
[59] T. Phan, F. Sommer, P. Altmann, F. Ritz, L. Belzner, and C. Linnhoff-Popien. Emergent
cooperation from mutual acknowledgment exchange. In Proceedings of the 21st International
Conference on Autonomous Agents and Multiagent Systems , pages 1047–1055, 2022.
[60] M. L. Puterman. Markov decision processes: discrete stochastic dynamic programming . John
Wiley & Sons, 2014.
[61] A. Raffin, A. Hill, A. Gleave, A. Kanervisto, M. Ernestus, and N. Dormann. Stable-baselines3:
Reliable reinforcement learning implementations. Journal of Machine Learning Research , 22
(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html .
[62] J. Rahme, S. Jelassi, J. Bruna, and S. M. Weinberg. A permutation-equivariant neural network
architecture for auction design. In Proceedings of the AAAI conference on artificial intelligence ,
volume 35, pages 5664–5672, 2021.
[63] S. S. Ravindranath, Z. Feng, S. Li, J. Ma, S. D. Kominers, and D. C. Parkes. Deep learning for
two-sided matching. arXiv preprint arXiv:2107.03427 , 2021.
13
[64] S. S. Ravindranath, Y . Jiang, and D. C. Parkes. Data market design through deep learning. In
Thirty-seventh Conference on Neural Information Processing Systems , 2023.
[65] P. Renner and K. Schmedders. Discrete-time dynamic principal–agent models: Contraction
mapping theorem and computational treatment. Quantitative Economics , 11(4):1215–1251,
2020.
[66] W. P. Rogerson. Repeated moral hazard. Econometrica , 53:69–76, 1985.
[67] E. Saig, I. Talgam-Cohen, and N. Rosenfeld. Delegated classification. In Conference on Neural
Information Processing Systems NeurIPS , 2023. https://doi.org/10.48550/arXiv.2306.
11475 .
[68] T. Sandholm and A. Likhodedov. Automated design of revenue-maximizing combinatorial
auctions. Operations Research , 63(5):1000–1025, 2015.
[69] T. Schaul, J. Quan, I. Antonoglou, and D. Silver. Prioritized experience replay. arXiv preprint
arXiv:1511.05952 , 2015.
[70] A. Scheid, D. Tiapkin, E. Boursier, A. Capitaine, E. M. E. Mhamdi, É. Moulines, M. I.
Jordan, and A. Durmus. Incentivized learning in principal-agent bandit games. arXiv preprint
arXiv:2403.03811 , 2024.
[71] S. E. Spear and S. Srivastava. On repeated moral hazard with discounting. The Review of
Economic Studies , 54:599–617, 1987.
[72] B. Stadie, L. Zhang, and J. Ba. Learning intrinsic rewards as a bi-level optimization problem.
InConference on Uncertainty in Artificial Intelligence , pages 111–120. PMLR, 2020.
[73] X. Sun, D. Crapis, M. Stephenson, and J. Passerat-Palmbach. Cooperative ai via decentralized
commitment devices. In Multi-Agent Security Workshop@ NeurIPS’23 , 2023.
[74] P. Sunehag, G. Lever, A. Gruslys, W. M. Czarnecki, V . Zambaldi, M. Jaderberg, M. Lanctot,
N. Sonnerat, J. Z. Leibo, K. Tuyls, et al. Value-decomposition networks for cooperative multi-
agent learning based on team reward. In Proceedings of the 17th International Conference on
Autonomous Agents and MultiAgent Systems , pages 2085–2087, 2018.
[75] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction . MIT press, 2018.
[76] M. Towers, J. K. Terry, A. Kwiatkowski, J. U. Balis, G. d. Cola, T. Deleu, M. Goulão,
A. Kallinteris, A. KG, M. Krimmel, R. Perez-Vicente, A. Pierré, S. Schulhoff, J. J. Tai, A. T. J.
Shen, and O. G. Younis. Gymnasium, Mar. 2023. URL https://zenodo.org/record/
8127025 .
[77] J. X. Wang, E. Hughes, C. Fernando, W. M. Czarnecki, E. A. Duéñez-Guzmán, and J. Z. Leibo.
Evolving intrinsic motivations for altruistic behavior. In Proceedings of the 18th International
Conference on Autonomous Agents and MultiAgent Systems , pages 683–692. International
Foundation for Autonomous Agents and Multiagent Systems, 2019.
[78] L. Wang, Z. Wang, and Q. Gong. Bi-level optimization method for automatic reward shaping
of reinforcement learning. In International Conference on Artificial Neural Networks , pages
382–393. Springer, 2022.
[79] T. Wang, P. Dütting, D. Ivanov, I. Talgam-Cohen, and D. C. Parkes. Deep contract design via
discontinuous networks. In NeurIPS , 2023. forthcoming.
[80] T. Willi, A. H. Letcher, J. Treutlein, and J. Foerster. COLA: Consistent learning with opponent-
learning awareness. In International Conference on Machine Learning , pages 23804–23831.
PMLR, 2022.
[81] R. Willis, Y . Du, J. Z. Leibo, and M. Luck. Resolving social dilemmas with minimal reward
transfer. arXiv preprint arXiv:2310.12928 , 2023.
[82] J. Wu, S. Chen, M. Wang, H. Wang, and H. Xu. Contractual reinforcement learning: Pulling
arms with invisible hands. arXiv preprint arXiv:2407.01458 , 2024.
14
[83] J. Yang, A. Li, M. Farajtabar, P. Sunehag, E. Hughes, and H. Zha. Learning to incentivize other
learning agents. Advances in Neural Information Processing Systems , 33:15208–15219, 2020.
[84] G. Yu and C. Ho. Environment design for biased decision makers. In Proceedings of the
Thirty-First International Joint Conference on Artificial Intelligence, IJCAI , pages 592–598,
2022.
[85] G. Yu and C.-J. Ho. Environment design for biased decision makers. In IJCAI 2022 , 2022.
[86] B. H. Zhang, G. Farina, I. Anagnostides, F. Cacciamani, S. M. McAleer, A. A. Haupt, A. Celli,
N. Gatti, V . Conitzer, and T. Sandholm. Steering no-regret learners to a desired equilibrium.
arXiv preprint arXiv:2306.05221 , 2023.
[87] H. Zhang and D. C. Parkes. Value-based policy teaching with active indirect elicitation. In
AAAI , volume 8, pages 208–214, 2008.
[88] H. Zhang, Y . Chen, and D. Parkes. A general approach to environment design with one agent.
InProceedings of the 21st International Joint Conference on Artificial Intelligence , pages
2002–2008, 2009.
[89] H. Zhang, D. C. Parkes, and Y . Chen. Policy teaching through reward function learning. In
Proceedings of the 10th ACM conference on Electronic commerce , pages 295–304, 2009.
[90] S. Zhao, C. Lu, R. B. Grosse, and J. N. Foerster. Proximal learning with opponent-learning
awareness. Advances in Neural Information Processing Systems , 35, 2022.
[91] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation,
EC 2023, London, United Kingdom, July 9-12, 2023 , page 1188, 2023.
[92] B. Zhu, S. Bates, Z. Yang, Y . Wang, J. Jiao, and M. I. Jordan. The sample complexity of online
contract design. In Proceedings of the 24th ACM Conference on Economics and Computation ,
pages 1188–1188, 2023.
[93] M. Zimmer, C. Glanois, U. Siddique, and P. Weng. Learning fair policies in decentralized
cooperative multi-agent reinforcement learning. In International Conference on Machine
Learning , pages 12967–12978. PMLR, 2021.
15
Appendix
Table of Contents
A Related Work 16
A.1 Automated Mechanism Design . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.2 Algorithmic Contract Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A.3 Multi-Agent RL (MARL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
B Proofs and Derivations (Sections 3 and 4) 18
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited) . 18
B.2 Principal’s and Agent’s MDPs (Observation 3.1) . . . . . . . . . . . . . . . . . 19
B.3 Contraction Operators and their Fixed Points . . . . . . . . . . . . . . . . . . . 20
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3) . . . . . . . . . . . . . . . . 23
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4) . . . . . . . . . . . 24
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs . . . . . . . . . . . . . 25
B.7 Meta-Algorithm in the Observed-Action Model . . . . . . . . . . . . . . . . . . 26
B.8 Deriving the Linear Program (Section 4) . . . . . . . . . . . . . . . . . . . . . 28
C Principal-Multi-Agent Example: Prisoner’s Dilemma 28
D Experiments 29
D.1 Experiments in Tree MDPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
D.2 Experiments in the Coin Game . . . . . . . . . . . . . . . . . . . . . . . . . . 31
D.3 Compute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
A Related Work
A.1 Automated Mechanism Design
Our study concerns finding an optimal way to influence the behavior of one or multiple agents in
an environment through optimization, it can thus be attributed to the automated mechanism design
literature. The field was pioneered by Conitzer and Sandholm [10,11,12]; the early approaches
mostly concerned optimal auctions and relied on classic optimization and machine learning algorithms
[45,41,68,17,53]. The field has received a surge of interest with the introduction of RegretNet [ 18]
– a deep learning based approach to approximately incentive-compatible optimal auction design. This
inspired multiple other algorithms for auction design [ 62,14,36,15], as well as applications of deep
learning to other economic areas such as multi-facility location [ 25], two-sided matching markets
[63], E-commerce advertising [48], and data markets [64].
Notably, a deep learning approach to contract design has been recently proposed by Wang et al.
[79] as a viable alternative to linear programming in problems with a high number of actions and
outcomes. Since our investigation focuses on scenarios where the primary source of complexity
comes from large state spaces rather than action or outcome spaces, we do not use their approximation
technique. At the heart of their approach is a novel neural network architecture specifically designed
to approximate discontinuous functions. Given that the principal’s Q-function, Qρ(s, b|π), in our
setting is discontinuous with respect to b, this architecture holds potential to bring further scalability
and practicality to our approach; we leave this direction as future work.
A.2 Algorithmic Contract Design
A body of work studies repeated principal-agent interactions in games either stateless or with states
unobserved by the principal (such as agent types). Depending on the model, learning an optimal
16
payment scheme can be formalized as a bandit problem with arms representing discretized contracts
[9,31,92] or as a constrained dynamic programming problem [ 65]. Scheid et al. [70] extend the
bandit formulation to a linear contextual setting and propose a learning algorithm that is near-optimal
in terms of principal’s regret. Zhang et al. [86] formulate a so-called steering problem where a
mediator can pay no-regret learners throughout repeated interactions and wishes to incentivize some
desirable predetermined equilibrium while satisfying budget constraints. Similarly, Guruganesh
et al. [29] study a repeated principal-agent interaction in a canonical contract setting, with the
agent applying no-regret learning over the course of interactions. Li et al. [43] study contracts for
afforestation with an underlying Markov chain; they do not extend to MDPs and do not apply learning.
There is also work on policy teaching , which can be seen as the earliest examples of contract design
in MDPs. Zhang et al. [89] study a problem of implementing a specific policy through contracts and
solve it with linear programming. Zhang and Parkes [87] additionally aim to find the policy itself,
which they show to be NP-hard and solve through mixed integer programming. Contemperaneously
with the present work, Ben-Porat et al. [3]extend these results by offering polynomial approximation
algorithms for two special instances of MDPs. These, as well as our work, can be seen as instances
of a more general environment design problem [ 88]. Crucially, these works focus on MDPs of up
to a hundred states. By employing deep RL, we extend to much larger MDPs. Our approach also
generalizes to hidden-action and multi-agent MDPs.
Monderer and Tennenholtz [52] propose k-implementation , which can be seen as contract design
applied to normal-form games. Specifically, the principal wants to implement (incentivize) some desir-
able outcome and can pay for the joint actions of the agents. The goal is to find the k-implementation
(we call it a minimal implementation), i.e., such payment scheme that the desirable outcome is
dominant-strategy incentive compatible for all agents, while the realized payment kfor this outcome
is minimal. Our multi-agent problem setup can be seen as learning a minimal implementation of a
social welfare maximizing strategy profile in a Markov game.
Related to algorithmic contract design is a problem of delegating learning tasks in the context of
incentive-aware machine learning [ 1,67]. These studies concern a principal properly incentivizing
agent(s) through contracts to collect data or train an ML model in a one-shot interaction.
A.3 Multi-Agent RL (MARL)
In our applications, we focus on general-sum Markov games where naively trained agents fail to
engage in mutually beneficial cooperation – colloquially known as “Sequential Social Dilemmas”
or SSDs [ 42]. The solution concepts can be divided into two broad categories. The majority of
studies take a purely computational perspective, arbitrarily modifying the agents’ reward functions
[57,58,34,38,77,22,39,16,83,35,93,59] or training procedures [ 27,23,80,90] in order to
maximize the aggregate reward. Alternative solutions view the problem as aligning the players’
incentives by modifying the rules of the game to induce better equilibria. Examples include enabling
agents to delegate their decision making to a mediator [ 37], allowing agents to review each others’
policies prior to decision making [ 54], and adding a cheap-talk communication channel between
agents [ 46]. Our work should be attributed to the second category as we model the principal-agents
interaction as a game. While the principal effectively modifies agents’ reward functions, the payments
are costly. The question is then how to maximize social welfare through minimal intervention, which
is an open research question.
The works on adaptive mechanism design [ 2,28] can be seen as precursors of contract design for
SSDs. These consider augmenting the game with a principal-like planning agent that learns to
distribute additional rewards and penalties, the magnitude of which is either limited heuristically or
handcoded. Importantly, the planning agent is not considered a player, and thus the equilibria are not
analyzed.
Most relevant to us, Christoffersen et al. [8]consider a contracting augmentation of SSDs. Before
an episode begins, one of the agents proposes a zero-sum reward redistribution scheme that triggers
according to predetermined conditions. Then, the other agents vote on accepting it, depending
on which the episode proceeds with the original or modified rewards. Because the conditions are
handcoded based on domain knowledge, the contract design problem reduces to finding a one-
dimensional parameter from a discretized interval that optimizes the proposal agent’s welfare, and by
the symmetry of contracts, the social welfare. Besides the technicality that the principal in our setting
17
Table 2: Comparison of standard and Principal-Agent MDPs
MDP Principal-Agent MDP
observed action hidden action
States S S S
Agent’s actions ( nelements) A A A
Outcomes ( melements) – – O
Principal’s actions — B⊂Rn
≥0 B⊂Rm
≥0
MDP transitioning s′∼ T(s, a)s′∼ T(s, a) o∼ O(s, a), s′∼ T(s, o)
Agent’s reward r(s, a) r(s, a) +b(a) r(s, a) +b(o)
Principal’s reward — rp(s, a)−b(a)rp(s, o)−b(o)
Agent’s policy π(s) π(s, b) π(s, b)
Principal’s policy — ρ(s) ρ(s)
Agent’s value Vπ(s) Vπ(s, b|ρ) Vπ(s, b|ρ)
Principal’s value — Vρ(s|π) Vρ(s|π)
is external to the environment, a crucial distinction is that we employ contracts in full generality,
allowing the conditions for payments to emerge from learning. We empirically verify that this
may result in a performance gap. To adapt this approach to the Coin Game and relax the domain
knowledge assumption, we 1) duplicate parts of rewards rather than redistribute them, which can also
be interpreted as payments by an external principal, and 2) allow each agent to immediately share the
duplicated part of its reward with the other agent, rather than a constant value every time a handcoded
condition is met. In experiments, we refer to this as a ‘constant proportion baseline’.
This work only covers fully observable environments, but our method could potentially be extended
to partial observability, limiting the information available to the principal and the agents to local
observations. In this regard, our method may be considered as having decentralized execution. While
the presence of a principal as a third party may be considered a centralized element, even this could
be alleviated through the use of cryptography [73].
B Proofs and Derivations (Sections 3 and 4)
In this appendix, we provide formal proofs and derivations for the results in Sections 3 and 4.
Appendix B.1 provides additional intuition on the differences between the solution concepts of
Stackelberg and Subgame-Perfect Equilibria. Appendix B.2 supplements Observation 3.1 and defines
the principal’s and agent’s MDPs. Appendix B.3 defines contraction operators useful for succeeding
proofs and connects these operators to the modified Q-functions defined in Section 4. Appendices
B.4 and B.5 present the respective proofs of Theorems 3.3 and 3.4. While the theory in the main
text focuses on the finite-horizon hidden-action scenario, we also discuss the infinite-horizon and
observed-action scenarios in appendices B.6 and B.7, respectively. Finally, the linear program
formulated in Section 4 is derived and described in more detail in Appendix B.8.
Table 2 summarizes the differences between standard MDPs and Principal-Agent MDPs with and
without hidden actions.
B.1 Stackelberg vs Subgame-Perfect Equilibrium (Example in Figure 1, Revisited)
First, consider the SPE notion: At the left subgame, the principal incentivizes the agent to take
noisy-left by choosing a contract that pays 1for outcome Land0otherwise. This way, both actions
yield the same value for the agent, 0.9·1 + 0 .1·0−0.8 = 0 .1·1 + 0 .9·0 = 0 .1, and the
agent chooses aLby tie-breaking in favour of the principal. So the principal’s value in state sLis
0.9(rp(sL, L)−1) = 0 .9(14
9−1) = 0 .5. By the same logic, the principal offers the same contract
insRand its value equals 0.5(and the agent’s value equals 0.1). Then, in s0, the agent is indifferent
between transitioning to sLandsR, so the principal has to offer the same contract again. The
principal’s value in s0(given that the agent chooses aL) is0.5 + 0 .9·0.5 + 0 .1·0.5 = 1 , and the
agent’s value is 0.1 + 0 .9·0.1 + 0 .1·0.1 = 0 .2. These are estimated by considering utilities in sL
andsRwithout discounting (using γ= 1). Note that in this analysis, we found SPE using backward
induction: we first analyzed the terminal states, then the root state.
18
Compare this with Stackelberg: If non-credible threats were allowed, the principal could threaten to
act suboptimally in the right subgame by always paying the agent 0. Both principal and agent then
value sRat0. InsL, the contract is the same as in SPE. Knowing this, the agent values sLoversR
(0.1>0), which would drive it to choose the noisy-left action at the root state even if the principal
pays only 1−0.1 = 0 .9for outcome L. By paying less, the principal’s utility (value in s0) would be
higher compared to SPE, (14
9−0.9 + 0 .5)·0.9 = 1 .04>1.
This illustrates how Stackelberg equilibrium may produce more utility for the principal, but the
surplus comes at the cost of the inability to engage in mutually beneficial contractual agreements
in certain subgames, even if these subgames are reached by pure chance and despite the agent’s
best efforts. On the one hand, Stackelberg requires more commitment power from the principal.
Whereas in SPE the agent can be certain that the principal sticks to its policy in future states because
it is optimal in any subgame, in Stackelberg, the principal has to preemptively commit to inefficient
contracts and ignore potential beneficial deviations. On the other hand, Stackelberg is not robust to
mistakes: if the agent mistakenly chooses the wrong action, it might be punished by the principal,
losing utility for both players. This is especially concerning in the context of learning, where mistakes
can happen due to approximation errors, or even due to the agent exploring (in online setups). SPE is
hence a more practical solution concept.
B.2 Principal’s and Agent’s MDPs (Observation 3.1)
A (standard) MDP is a tuple (S, S 0, A,R,T, γ), where Sis a set of states, S0∈Sis a set of
possible initial states, Ais a set of actions, T:S×A→∆(S)is a stochastic transition function,
R:S×A×S→ P(R)is a stochastic reward function ( R(s, a, s′)is a distribution and may depend
on the next state s′),γis an (optional) discounting factor. Assume finite horizon (as in Section 2).
Consider a hidden-action principal-agent MDP M= (S, s 0, A, B, O, O,R,Rp,T, γ)as defined in
Section 2. First, consider the agent’s perspective. Let the principal’s policy be some ρ. This defines
a standard MDP (Sa, Sa
0, A,Ra,Ta, γ)that we call the agent’s MDP, where: The set of states is
Sa=S×B(infinite unless Bis discretized). The set of initial states is S0={s0} ×B. The set of
actions is A.
The transition function Ta:Sa×A→∆(Sa)defines distributions over next state-contract pairs
(s′, ρ(s′)), where s′∼ T(s, o∼ O(s, a)). Note that the next state s′is sampled from a distribution
that is a function of state-action pairs (s, a)marginalized over outcomes, and the next contract ρ(s′)
is given by the principal’s policy. Informally, the agent expects the principal to stick to its policy
in any future state. At the same time, since the state space Sais defined over the set of contracts
B, the agent may adapt its policy to any immediate contract in the current state, and thus its policy
π:Sa→∆(A)is defined by π(s, b)for any b∈B.
The reward function is a bit cumbersome to formalize because it should not depend on outcomes,
while both OandTcan be stochastic. Specifically, the new reward function has to be stochastic
w.r.t. outcomes: Ra((s, b), a, s′) = [ r(s, a) +b(o)|o∼P(o|s, a, s′)], where the conditional
distribution of outcomes is given by P(o|s, a, s′) =P(O(s,a)=o)P(T(s,o)=s′)P
o∗P(O(s,a)=o∗)P(T(s,o∗)=s′).
Next, consider the principal’s perspective. Let the agent’s policy be some π. This defines a standard
MDP (S,{s0}, B,Rp,Tp, γ)that we call the principal’s MDP, where: the set of states is S; the set
of initial states is {s0}; the set of actions is B(infinite unless discretized); the transition function is
defined by Tp(s, b) =T(s, o∼ O(s, a∼π(s, b))); the reward function is defined similarly to the
agent’s MDP by Rp(s, b, s′) = [r(s, o)−b(o)|o∼P(o|s, a, s′)].
Thus, the optimization task of the principal (agent) given a fixed policy of the agent (principal) can be
cast as a standard single-agent MDP. In both players’ MDPs, the other player’s presence is implicit,
embedded into transition and reward functions. Note that our definition of standard MDP allows for
stochastic reward functions that depend on the next state, as well as a set of initial states that is not
a singleton. The same generalizations can be made in our Principal-Agent MDP definition, and in
particular, the above derivations would still hold, but we decided to slightly specify our model for
brevity.
19
B.3 Contraction Operators and their Fixed Points
Our meta-algorithm iteratively solves a sequence of principal’s and agent’s MDPs as defined in
Appendix B.2. Both tasks can be performed with Q-learning and interpreted as finding fixed points
of the Bellman optimality operator in the respective MDPs. Furthermore, our learning approach in
Section 4 makes use of modified Q-functions, which are also fixed points of contraction operators.
For convenience, we define all four operators below. Where necessary, we prove the operators being
contractions and define their fixed points.
B.3.1 Optimality operators in the agent’s MDP
Here we assume some fixed principal’s policy ρthat defines an agent’s MDP.
Bellman optimality operator. Consider the agent’s optimization task (line 3 of the meta-algorithm).
Solving it implies finding a fixed point of an operator Sρ, which is the Bellman optimality operator in
the agent’s MDP defined by a principal’s policy ρ.
Definition B.1. Given an agent’s MDP defined by a principal’s policy ρ, the Bellman optimality
operator Sρis defined by
(SρQ)((s, b), a) =Eo∼O(s,a),s′∼T(s,o)h
R(s, a, b, o ) +γmax
a′Q((s′, ρ(s′)), a′)i
, (6)
whereR(s, a, b, o ) =r(s, a) +b(o),Qis an element of a vector space QSBA={S×B×A→R},
and subscript ρdenotes conditioning on the principal’s policy ρ.
This operator is a contraction and admits a unique fixed point Q∗(ρ)that satisfies:
V∗(s, b|ρ) = max
aQ∗((s, b), a|ρ), (7)
Q∗((s, b), a|ρ) =Eh
R(s, a, b, o ) +γmax
a′Q∗((s′, ρ(s′)), a′|ρ)i
. (8)
The policy corresponding to the fixed point is called the best-responding policy π∗(ρ):
∀s∈S, b∈B:π∗(s, b|ρ) = arg max
aQ∗((s, b), a|ρ),
where ties are broken in favour of the principal.
Truncated Bellman optimality operator. Here we show that the truncated Q-function Q∗(ρ)
defined in the main text (1)is a fixed point of a contraction operator and thus can be found with
Q-learning.
Definition B.2. Given an agent’s MDP defined by principal’s policy ρ, the truncated Bellman
optimality operator Sρis defined by
(SρQ)(s, a) =r(s, a) +γEo∼O(s,a),s′∼T(s,o)max
a′
Eo′∼O(s′,a′)ρ(s′)(o′) +Q(s′, a′)
,(9)
where Qis an element of a vector space QSA={S×A→R}.
Lemma B.3. Operator Sρis a contraction in the sup-norm.7
Proof. LetQ1,Q2∈ QSA,γ∈[0,1). The operator Sρis a contraction in the sup-norm if it satisfies
∥SρQ1−SρQ2∥∞≤γ∥Q1−Q2∥∞. This inequality holds because:
7In lemmas B.3 and B.6, we show for a case that includes finite- and infinite-horizon MDPs, but requires
γ < 1. For γ= 1and finite-horizon MDPs, per-timestep operators can be shown to be contractions, similar to
the Bellman operator in chapter 4.3 of Puterman [60].
20
∥SρQ1−SρQ2∥∞= max
s,aγEo,s′
max
a′(Eo′ρ(s′)(o′) +Q1(s′, a′))−
max
a′(Eo′ρ(s′)(o′) +Q2(s′, a′))
+r(s, a)−r(s, a)≤
max
s,aγEo,s′max
a′Eo′
ρ(s′)(o′) +Q1(s′, a′)−ρ(s′)(o′)−Q2(s′, a′)=
max
s,aγEo,s′max
a′
Q1(s′, a′)−Q2(s′, a′)≤
max
s,aγmax
s′,a′Q1(s′, a′)−Q2(s′, a′)=γ∥Q1−Q2∥∞.
Because Sρis a contraction as shown in Lemma B.3, by the Banach theorem, it admits a unique fixed
point Q∗
ρs.t.∀s, a:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a). We now show that this fixed point is the truncated
Q-function. Define Qρ((s, b), a) =Eo∼O(s,a)b(o) +Q∗
ρ(s, a). Notice that the fixed point satisfies:
∀s∈S, a∈A:Q∗
ρ(s, a) = (SρQ∗
ρ)(s, a)(Eq. 9)=
r(s, a) +γEo,s′max
a′
Eo′ρ(s′)(o′) +Q∗
ρ(s′, a′)
=
r(s, a) +γEo,s′max
a′Qρ((s′, ρ(s′)), a′).
At the same time, by definition:
∀s∈S, a∈A:Q∗
ρ(s, a) =Qρ((s, b), a)−Eo∼O(s,a)b(o).
Combining the above two equations and swapping terms:
∀s∈S, a∈A:Qρ((s, b), a) =r(s, a) +Eo,s′[b(o) +γmax
a′Qρ((s′, ρ(s′)), a′)].
Notice that the last equation shows that Qρis the fixed point of the Bellman optimality operator
Sρ(6), i.e., Qρ=Q∗(ρ), as it satisfies the optimality equations (8). It follows that Q∗((s, b), a|
ρ) =Eob(o) +Q∗
ρ(s, a), and thus Q∗
ρsatisfies the definition of the truncated Q-function (1), i.e.,
Q∗
ρ=Q∗(ρ). The truncated Q-function is then a fixed point of a contraction operator and can be
found with Q-learning. It can also be used to compute the best-responding policy: π∗(s, b|ρ) =
arg maxa[Eob(o) +Q∗(s, a|ρ)].
B.3.2 Optimality operators in the principal’s MDP
Here we assume some fixed best-responding agent’s policy π∗(ρ)that defines a principal’s MDP.
While we could instead assume an arbitrary policy π, we are only interested in solving the principal’s
MDP as the outer level of the meta-algorithm, which always follows the inner level that outputs an
agent’s policy π∗(ρ)best-responding to some ρ.
Bellman optimality operator. Consider the principal’s optimization level (line 4 of the meta-
algorithm). Solving it implies finding a fixed point of an operator Bρ, which is the Bellman optimality
operator in the principal’s MDP defined by the agent’s policy π∗(ρ)is best-responding to some ρ.
Definition B.4. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the Bellman optimality operator Bρis defined by
(BρQ)(s, b) =Eo∼O(s,a),s′∼T(s,o)h
Rp(s, b, o ) +γmax
b′Q(s′, b′)
|a=π∗(s, b|ρ)i
,(10)
where Rp(s, b, o ) =rp(s, o)−b(o),Qis an element of a vector space QSB={S×B→R}, and
subscript ρdenotes conditioning on the agent’s best-responding policy π∗(ρ).
21
This operator is a contraction and admits a unique fixed point Q∗(π∗(ρ))that satisfies optimality
equations:
V∗(s|π∗(ρ)) = max
bQ∗(s, b|π∗(ρ)), (11)
Q∗(s, b|π∗(ρ)) =Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))
|a=π∗(s, b|ρ)i
.(12)
The policy corresponding to the fixed point is called the subgame-perfect policy ρ∗(π∗(ρ)):
∀s∈S:ρ∗(s|π∗(ρ)) = arg max
bQ∗(s, b|π∗(ρ)).
Contractual Bellman optimality operator. Here we show that the contractual Q-function
q∗(π∗(ρ))defined in the main text (2)is a fixed point of a contraction operator and thus can be found
with Q-learning.
Definition B.5. Given a principal’s MDP defined by the agent’s policy π∗(ρ)best-responding to
some ρ, the contractual Bellman optimality operator Hρis defined by
(Hρq)(s, ap) = max
{b|π∗(s,b|ρ)=ap}Eo∼O(s,ap),s′∼T(s,o)h
Rp(s, b, o ) +γmax
a′q(s′, a′)i
, (13)
where qis an element of a vector space QSA={S×A→R}, and ap∈Adenotes the principal’s
recommended action.
Lemma B.6. Operator Hρis a contraction in the sup-norm.
Proof. Letq1, q2∈ QSA,γ∈[0,1). The operator Hρis a contraction in the sup-norm if it satisfies
∥Hρq1− H ρq2∥∞≤γ∥q1−q2∥∞. This inequality holds because:
∥Hρq1− H ρq2∥∞= max
s,a max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q1(s′, a′)
−
max
{b∈B|π∗(s,b|ρ)=a}E
Rp(s, b, o ) +γmax
a′q2(s′, a′)=
max
s,aγE[max
a′q1(s′, a′)−max
a′q2(s′, a′)]≤
max
s,aγEmax
a′q1(s′, a′)−max
a′q2(s′, a′)≤
max
s,aγEmax
a′|q1(s′, a′)−q2(s′, a′)| ≤
max
s,aγmax
s′,a′|q1(s′, a′)−q2(s′, a′)|=γ∥q1−q2∥∞.
Because Hρis a contraction as shown in Lemma B.6, by the Banach theorem, it admits a unique fixed
point q∗
ρs.t.∀s, ap:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap). We now show that this fixed point is the contractual
Q-function. Notice that the fixed point satisfies:
∀s∈S: max
apq∗
ρ(s, ap) = max
ap(Hρq∗
ρ)(s, ap)(Eq. 13)=
max
b(Hρq∗
ρ)(s, π∗(s, b|ρ)) = max
b(Hρ(Hρq∗
ρ))(s, π∗(s, b|ρ)) =···=
max
bEX
th
γtRp(st, bt, ot)|s0=s, b0=b, π∗(ρ)i
= max
bQ∗(s, b|π∗(ρ)),(14)
22
and:
∀s∈S, ap∈A:q∗
ρ(s, ap) = (Hρq∗
ρ)(s, ap)(Eq. 13)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
a′q∗
ρ(s′, a′)i(Eq. 14)=
max
{b|π∗(s,b|ρ)=ap}Eh
Rp(s, b, o ) +γmax
b′Q∗(s′, b′|π∗(ρ))i(Eq. 12)=
max
{b|π∗(s,b|ρ)=ap}Q∗(s, b|π∗(ρ)).(15)
Thus, q∗
ρsatisfies the definition of the contractual Q-function (2), i.e., q∗
ρ=q∗(ρ). The contractual
Q-function is then a fixed point of a contraction operator and can be found with Q-learning. The
contractual Q-function can also be used to compute the subgame-perfect principal’s policy as ρ∗(s) =
arg maxb(Hρq∗
ρ)(s, π∗(s, b|ρ)) = arg maxbQ∗(s, b|π∗(ρ)). We address computing the arg max
in Appendix B.8 using Linear Programming.
B.4 Meta-Algorithm finds SPE (Proof of Theorem 3.3)
Observation B.7. A principal-agent stochastic game Gis in SPE if and only if every subgame of G
is in SPE.
Observation B.7 will be useful for the proofs in this section.
LetSt⊆Sdenote the set of all possible states at time step t. For example, S0={s0}. States in ST
are terminal by definition. We assume that sets Stare disjoint. This is without loss of generality, as
we can always redefine the state space of a finite-horizon MDP such that the assumption holds; e.g.,
by concatenating the time step to a state as snew
t= (st, t). In other words, any finite-horizon MDP
can be represented as a directed acyclic graph.
The next lemma is a precursor to proving the convergence of Algorithm 1 and concerns its single
iteration. Given a pair of policies that form an SPE in all subgames but the original game, it states
that performing one additional iteration of the algorithm (update the agent, then the principal) yields
an SPE in the game. This is because the agent observes the contract offered in a state and adapts
its action, in accordance with our definition of the agent’s MDP in Appendix B.2. In particular,
the agent’s best-responding policy is defined as π∗(s, b|ρ)foranypair(s, b), so in s0, the agent
best-responds with π∗(s0, b|ρ)for any bregardless of the principal’s policy ρ(s0).
Lemma B.8. Given a finite-horizon principal-agent stochastic game Gand a principal’s policy
ρ, if(ρ, π∗(ρ))is an SPE in all subgames with a possible exception of G(i.e., all subgames in
s∈S\ {s0}), then (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G.
Proof. Ins0, the agent observes the principal’s action. Consequently and because the agent best-
responds to ρ, it also best-responds to any {ρ′| ∀s∈S\ {s0}:ρ′(s) =ρ(s)}regardless of the
offered contract ρ′(s0), including the subgame-perfect ρ∗(π∗(ρ))(that only differs from ρins0, as
subgames in other states are in SPE already). Thus, (ρ∗(π∗(ρ)), π∗(ρ))is an SPE in G, as well as in
all subgames of G(by Observation B.7).
Corollary B.9. Given Gwith a single subgame ( S={s0}),(ρ∗(π∗(ρ)), π∗(ρ))is an SPE in Gfor
anyρ.
This corollary concerns MDPs with a single state, which could also be interpreted as stateless. This
covers static contract design problems, as well as subgames in terminal states in our model.
By using Lemma B.8, we can now show that each iteration of the algorithm expands the set of
subgames that are in SPE, as long as some subgames satisfy the conditions of the lemma for an
arbitrarily initialized ρ. This is always the case for finite-horizon MDPs, as the subgames in terminal
states have a single subgame (itself), and thus Corollary B.9 applies. This reasoning is used to prove
Theorem 3.3.
Proof of Theorem 3.3. Denote the policy initialized at line 1 as ρ0. Denote the best-responding policy
toρ0asπ1≡π∗(ρ0)and the subgame-perfect policy against π1asρ1≡ρ∗(π1). Likewise, πiand
23
ρirespectively denote the best-responding policy to ρi−1and the subgame-perfect policy against πi,
where iis an iteration of the algorithm.
By Corollary B.9, (ρ1, π1)forms an SPE in all subgames in terminal states, including s∈ST.
Applying Lemma B.8, as well as our assumption that sets Stare disjoint, (ρ2, π2)is an SPE in all
subgames in ST∪ST−1. By induction, (ρi, πi)is an SPE in all subgames in s∈ST∪ST−1··· ∪
ST−i+1. Thus, (ρT+1, πT+1)is an SPE in all subgames in s∈ST∪ ··· ∪ S0=S, and thus in the
gameG(by Observation B.7).
B.5 Meta-Algorithm applies Contraction (Proof of Theorem 3.4)
Consider the principal’s optimization task (line 4 of the meta-algorithm). As we discuss in Ap-
pendix B.3, solving this task can be interpreted as finding the fixed point of a contraction operator Bρ
defined in (10). By definition of contraction, this fixed point can be found by iteratively applying the
operator until convergence, which we denote as H∗=Bρ(Bρ(Bρ...Q(s, b))).
Observation B.10. H∗is a composition of linear operators and thus is a linear operator.
ForH∗to be a contraction, its fixed point has to be unique. Since its iterative application (the
meta-algorithm, Algorithm 1) converges to an SPE, we next prove the uniqueness of Q-functions in
SPE.
Lemma B.11. Given a finite-horizon principal-agent stochastic game G, the principal’s Q-function
is equal in all SPE for any state-action; the same holds for the agent’s Q-function.
Proof. Consider a principal’s policy ρthat forms SPE with any best-responding agent’s policy π∗(ρ).
Anyπ∗(ρ)solves the agent’s MDP and thus all such policies define a unique agent’s Q-function
(which is the fixed point of the Bellman optimality operator). Furthermore, by the assumption that
the agent breaks ties in favor of the principal, all best-responding policies also uniquely define the
principal’s Q-function (in other words, any policy that solves the agent’s MDP but does not maximize
the principal’s Q-function when breaking ties in some state is not a best-responding policy by the
assumed tie-breaking). Thus, for any pair of SPE with non-equal Q-functions, the principal’s policies
must also differ.
Consider two principal’s policies, ρxandρy, that form SPE with any respective best-responding
agents’ policies, π∗(ρx)andπ∗(ρy). By the above argument, the choice of π∗(ρx)andπ∗(ρy)is
inconsequential, so we can assume those to be unique (e.g. by adding lexicographic tie-breaking if
the principal-favored tie-breaking does not break all ties).
Forρxandρyto differ, there must be a state s∈Stsuch that 1) all subgames in states “after” t,
i.e.,{St′}t′>t, are in unique SPE given by some ρandπ∗(ρ)(e.g., this holds in a terminal state)
and 2) the subgame in shas two contracts, bx=ρx(s)andby=ρy(s), that both maximize the
principal’s utility, i.e., Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)). Denote the agent’s actions in s
asax=π∗(s, bx|ρ)anday=π∗(s, by|ρ). We now show that the choice between bxandbyis
inconsequential as both contracts also yield the same utility for the agent.
Assume the agent prefers bxtoby, i.e., Q∗((s, bx), ax|ρ)> Q∗((s, by), ay|ρ). First, use
the observed-action notation. Applying the Bellman optimality operator and using the defi-
nition of R, we have E[r(s, ax) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +bx(ax)>E[r(s, ay) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)] +by(ay). Observe that the principal may simply decrease the
payment bx(ax)by the difference of the agent’s Q-values (so that the inequality becomes equality),
increasing the principal’s utility. So, the assumption that the agent prefers bxtobymeans that neither
contract maximizes the principal’s utility in the subgame, leading to a contradiction.
The same can be shown in the hidden-action model. The agent preferring bxtoby
would mean E[r(s, ax) +bx(o) +γmax a′Q∗((s′, ρ(s′)), a′|ρ)]>E[r(s, ay) +by(o) +
γmax a′Q∗((s′, ρ(s′)), a′|ρ)], and the principal would be able to adjust bxin order to decrease the
expected payment E[bx(o)]relatively to E[by(o)], e.g., by decreasing each non-zero payment bx(o)
by a constant. Again, this leads to a contradiction.
We thus have shown that the choice between bxandbyinsis inconsequential for the value functions
of both principal and agent in s:V∗(s|π∗(ρx)) = Q∗(s, bx|π∗(ρx)) = Q∗(s, by|π∗(ρy)) =
V∗(s|π∗(ρy))andV∗(s, bx|ρ) =Q∗((s, bx), ax|ρ) =Q∗((s, by), ay|ρ) =V∗(s, by|ρ). By
Bellman optimality equations ( (7)and(8)for the agent, (11) and(12) for the principal), it is also
24
inconsequential for the players’ Q-functions in all states “before” t, i.e.,{St′}t′<t. For states “after”
t, the choice also has no effect by the MDP being finite-horizon (and our w.l.o.g. assumption about
the uniqueness of states). This holds for any such bxandbyin any s. Thus, for any SPE (ρ, π∗(ρ)),
each player’s Q-function is identical in all SPE for any state-action.
Proof of Theorem 3.4. By Observation B.10, H∗is a linear operator. Moreover, as Algorithm 1
converges to SPE by Theorem 3.3 and the payoffs in SPE are unique by Lemma B.11, the iterative
application of H∗converges to a unique fixed point. By using a converse of the Banach theorem
(Theorem 1 in Daskalakis et al. [13]), this operator is a contraction under any norm that forms a
complete and proper metric space. This includes the sup-norm.
B.6 Meta-Algorithm may diverge in Infinite-Horizon MDPs
Here we present an example of a hidden-action infinite-horizon principal-agent MDP where the
meta-algorithm diverges by getting stuck in a cycle. To solve the principal’s and agent’s optimization
tasks, we specifically developed exact solvers for principal’s and agent’s MDPs.
The MDP consists of two states, s1ands2. In each state, the agent has two actions, a1anda2, which
determine probabilities of sampling one of two outcomes, o1ando2. When agent chooses a1in any
states, outcomes are sampled with respective probabilities O(o1|s, a 1) = 0 .9andO(o2|s, a 1) =
0.1. Vice versa, choosing a2in any state ssamples an outcome with probabilities O(o1|s, a 2) = 0 .1
andO(o2|s, a 2) = 0 .9. After sampling an outcome oi, the MDP deterministically transitions to si
(e.g., if o1is sampled, the MDP transitions to s1regardless of the old state and the agent’s action).
Choosing an action that is more likely to change the state of the MDP (so, a2ins1anda1ins2)
requires effort from the agent, respectively costing c(s1, a2) = 1 andc(s2, a1) = 2 . The other action
is free for the agent: c(s1, a1) = 0 andc(s2, a2) = 0 . Other things equal, the principal prefers the
agent to invest an effort: it only enjoys a reward whenever the MDP transitions to a different state,
equal to rp(s1, o2) =rp(s2, o1) = 1 .5. The discount factor is set to γ= 0.9.
We now describe several iterations of the meta-algorithm, showing that it oscillates between two pairs
of players’ policies. We report the agent’s truncated Q-function (1)and the principal’s contractual
Q-function (2)at each iteration of the algorithm (rounded to three decimals). We also verify that
these Q-functions are indeed fixed points of respective operators and thus solve the respective MDPs,
but only do so in (s1, a2)as derivations in other state-action pairs are identical.
Initialization
Initialize the principal with a policy ρ0that does not offer any payments, i.e., ρ0(s1) =ρ0(s2) =
(0,0), where we denote a contract by a tuple b= (b(o1), b(o2)).
Iteration 1: agent
The agent’s best-responding policy π1simply minimizes costs by never investing an effort:
π1(s1, ρ0(s1)) =a1,π1(s2, ρ0(s2)) =a2. This corresponds to the following truncated Q-function:
Qπ1(s1, a1) =Qπ1(s2, a2) = 0 ,Qπ1(s1, a2) =−c(s1, a2) =−1andQπ1(s2, a1) =−c(s2, a1) =
−2.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−1 =Qπ1(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1·0 + 0 .9·0] =−1.
In the absence of contracts, the agent’s truncated Q-function is equal to its Q-function under the
principal’s policy: Qπ1((s, ρ 0(s)), a) =Qπ1(s, a).
Iteration 1: principal
The principal’s subgame-perfect policy ρ1attempts to incentivize effort in s1and offers the following
contracts: ρ1(s1) = (0 ,1.25),ρ1(s2) = (0 ,0). This corresponds to the following contractual Q-
function: qρ1(s1, a1) = 1 .991,qρ1(s1, a2) = 2 .048,qρ1(s2, a1) = 1 .391, and qρ1(s2, a2) = 2 .023.
25
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
2.048 = qρ1(s1, a2) =Eo,s′[−ρ1(s1)(o) +rp(s1, o) +γmax
a′qρ1(s′, a′)] =
0.1(0 + 0 + 0 .9·2.048) + 0 .9(−1.25 + 1 .5 + 0 .9·2.023) = 2 .048.
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .5,0), which is not worth it for the
principal, as evidenced by qρ1(s2, a1)< qρ1(s2, a2).
Iteration 2: agent
The principal ρ1underestimated the payment required to incentivize effort, and the agent’s best-
responding policy π2still never invests an effort: π2(s1, ρ1(s1)) = a1,π2(s2, ρ1(s2)) = a2. This
corresponds to the following truncated Q-function: Qπ2(s1, a1) = 0 .723,Qπ2(s1, a2) =−0.598,
Qπ2(s2, a1) =−1.277, and Qπ2(s2, a2) = 0 .402.
To verify that this Q-function is a fixed point of the truncated Bellman optimality operator (9), observe
that the optimality equations hold in all state-action pairs. For example, in (s1, a2)we have:
−0.598 = Qπ2(s1, a2) =−c(s1, a2) +γEo,s′,o′[ρ(s′)(o′) + max
a′Qπ1(s′, a′)] =
−1 + 0 .9[0.1(0.9(0 + 0 .723) + 0 .1(1.25 + 0 .402))+
0.9(0.1(0 + 0 .723) + 0 .9(0 + 0 .402))] = −0.598.
Given the contracts from the principal’s policy ρ1, we can compute the agent’s Q-values using (1):
Qπ2((s1, ρ1(s1)), a1) = 0 .848,Qπ2((s1, ρ1(s1)), a2) = 0 .527,Qπ2((s2, ρ1(s2)), a1) =−1.277,
andQπ2((s2, ρ1(s2)), a2) = 0 .402. Observe that indeed, the agent still prefers not to invest an effort
ins1, as evidenced by Qπ2((s1, ρ1(s1)), a1)> Qπ2((s1, ρ1(s1)), a2).
Iteration 2: principal
The principal gives up on incentivizing effort and once again offers no contracts: ρ2(s1) = (0 ,0),
ρ2(s2) = (0 ,0). This corresponds to the following contractual Q-function: qρ2(s1, a1) = 1 .661,
qρ2(s1, a2) = 1 .503,qρ2(s2, a1) = 1 .422, and qρ2(s2, a2) = 1 .839.
To verify that this Q-function is a fixed point of the contractual Bellman optimality operator (13),
observe that the optimality equations hold in all state-action pairs. For example, to incentivize a2in
s1, the principal has to offer a contract ρ(s1) = (0 ,1.652) , which gives us:
1.503 = qρ2(s1, a2) =Eo,s′[−ρ2(s2)(o) +rp(s1, o) +γmax
a′qρ2(s′, a′)] =
0.1(0 + 0 + 0 .9·1.661) + 0 .9(−1.652 + 1 .5 + 0 .9·1.839) = 1 .503,
Incentivizing a1ins2requires offering a contract ρ(s2) = (2 .098,0), which is still not worth it for
the principal, as evidenced by qρ2(s2, a1)< qρ2(s2, a2).
Subsequent iterations
Because the principal’s subgame-perfect policy ρ2repeats the policy ρ0from a previous iteration, the
meta-algorithm is now stuck in a cycle where iterations 1 and 2 repeat infinitely. In other words, the
meta-algorithm diverges.
B.7 Meta-Algorithm in the Observed-Action Model
In the special case where the agent’s actions are observed (defined in Section 2.2 and summarized
in Table 2), the meta-algorithm can be shown to find SPE in a single (rather than T+ 1) iteration,
as we show in Theorem B.12. This property is based on the observation that the agent is indifferent
between an MDP without a principal and an MDP augmented with a subgame-perfect principal;
similar observation has been made in contemporaneous work [ 3]. Consequently, evaluating minimal
implementation only requires access to the agent’s optimal Q-function in the absence of the principal.
26
Is is also easy to show that SPE coincides with Stackelberg equilibrium in the observed-action
scenario (Lemma B.14), and consequently the meta-algorithm finds Stackelberg equilibrium.
Theorem B.12. Given a principal-agent stochastic game, G, with observed actions and either finite
or infinite horizon, if the principal’s policy is initialized to offer zero-vectors as contracts in all states,
the meta-algorithm finds SPE in one iteration.
Proof of Theorem B.12. Use the same notations of ρiandπias in the proof of Theorem 3.3 in
Appendix B.4.
After initializing ρ0(that always offers 0) and finding the best-responding agent π1, consider the
optimal payments found at the outer optimization level of Algorithm 1. Given a state s∈S, denote
the agent’s action as
a∗= arg max
aQ∗((s,0), a|ρ0).
For now, let contracts in states other than sremain 0; we will omit the conditioning of Q∗onρ0for
brevity. The optimal contract in s, denoted as b∗, reimburses the agent for taking a suboptimal action,
paying exactly
b∗(s, ap) =Q∗((s,0), a∗)−Q∗((s,0), ap)
if the agent selects ap, and pays 0otherwise. Note that b∗=0ifap=a∗. This contract makes the
agent indifferent between apanda∗because
Q∗((s, b∗), ap) =Q∗((s,0), ap) +b∗(s, ap) =Q∗((s,0), a∗),
changing the agent’s action in stoap(according to tie-breaking). However, the agent’s value function
remains unchanged:
V∗(s, b∗) =Q∗((s, b∗), ap) =Q∗((s,0), a∗) =V∗(s,0).
Thus, the Bellman optimality equations (7)and(8)still hold in all states after replacing 0withb∗in
s, and π1still best-responds to the updated principal. This replacement of zero-vectors for optimal
contracts b∗is performed in all states during the update of the principal at the outer optimization
level, yielding a principal’s policy ρ1subgame-perfect against π1. At the same time, π1remains
best-responding against ρ1. Thus, (ρ1, π1)is an SPE.
Remark B.13 .Unlike our general Theorem 3.3, the above proof relies on the specifics of our model
such as the principal’s action set and the players’ reward functions.
Lemma B.14. Given a principal-agent stochastic game, G, with observed actions, any SPE is a
Stackelberg equilibrium.
Proof. Consider an SPE. As discussed in the above proof, the contracts in SPE exactly reimburse the
agent for choosing suboptimal actions, and the agent’s value function when offered such a contract in
some state sremains the same as in the absence of the contract. Additionally, notice that the principal
may never decrease the agent’s value in any state below the value it gets in the absence of contracts
(since payments are non-negative). Thus, the principal may not deviate from SPE by decreasing
the agent’s value in any of the future states through suboptimal contracts in order to incentivize a
suboptimal action apwhile paying less in s.
On the other hand, consider the principal trying to pay less in some state sby increasing the agent’s
value in some future states. If transition function is determenistic, then in order to decrease the
payment in sby some v < b∗(ap)while still incentivizing ap, the principal must, for example,
increase the payment in s′=T(s,O(s, ap))byv/γ– which is inconsequential for the principal’s
value in s(in our model, the discount factor is the same for the principal and the agent). In case
of a stochastic transition function, the increase of payments in future states required to balance the
decrease of the payment in sbyvmay even decrease the principal’s value in scompared to SPE.
Thus, the principal may not deviate from an SPE (commit to non-credible threats) to increase its
value in the initial state, and therefore any SPE is a Stackelberg equilibrium.
27
B.8 Deriving the Linear Program (Section 4)
In Section 4, we describe an RL approach to solving the principal’s MDP that involves two interde-
pendent tasks of 1) learning a policy that the principal wants to implement and 2) computing the
contracts that do so optimally. The former is solved by learning the contractual Q-function (2), which
we derive as a fixed point of a contraction operator Hρ(13) in Appendix B.3. The latter (which is
required as a subroutine to apply Hρ) we solve using Linear Programming, akin to how the static
principal-agent problems are typically solved (as mentioned in Section 2.1).
Given a state s∈Sand an action to recommend ap∈A, rewrite the right-hand side of Hρas the
following constrained optimization problem:
max
b∈BEo∼O(s,ap),s′∼T(s,o)h
rp(s, o)−b(o) +γmax
a′q(s′, a′)i
s.t.
∀a∈A:Q∗((s, b), ap|ρ)≥Q∗((s, b), a|ρ),(16)
where the constraints explicitly require the recommended action apto be at least as ‘good’ for the
agent as any other action a. Note that rp(s, o)andq(s′, a′)are constants with respect to band can
be omitted from the objective. To see that the constraints are linear, apply the Bellman optimality
operator to the agent’s Q-function, and rewrite constraints through the truncated Q-function using (1):
max
b∈BEo∼O(s,ap)[−b(o)]s.t.
∀a∈A:Eo∼O(s,ap)[b(o)] +Q∗(s, ap|ρ)≥Eo∼O(s,a)[b(o)] +Q∗(s, a|ρ).(17)
Because both the objective and the conditions are linear, the problem (17) is an LP.
As discussed in Section 4, our approach to solving the agent’s optimization problem is to learn the
truncated Q-function Q∗(ρ)and transform it into the Q-function by adding the expected payment.
Note that this representation of the agent’s Q-function is used in the constraints of the above LP. The
requirement of the principal having access to the agent’s (truncated) Q-function can be seen as a
limitation of the outlined approach. A potential remedy is to instead parameterize the principal’s
Q-function Q∗(π)with a discontinuous neural network able to efficiently approximate the Q-function
and the solutions to LPs without requiring access to the agent’s private information [ 79]. Of course,
one could also directly learn Q∗(π)with simpler approaches, e.g., by discretizing the contract space
or employing deep RL methods for continuous action spaces (such as Deep Deterministic Policy
Gradient or Soft Actor-Critic).
Solving the LP also requires access to the outcome function O; we discuss in Appendix D.1 how
this can be circumvented by parameterizing the outcome function with an additional neural network,
trained as a probabilistic outcome classifier.
In the special case of the observed-action model, the LP has a simple solution if the agent best-
responds to a specific principal that always offers a zero-vector 0as a contract. In this solution, the
principal exactly reimburses the agent for choosing a (suboptimal) recommended action ap, and pays
0if agent chooses any other action a̸=ap. Similar observation has been made in contemporaneous
work, see end of Section 3.1 in Wu et al. [82].
C Principal-Multi-Agent Example: Prisoner’s Dilemma
Below we illustrate the multi-agent model from Section 5.1 on the example of a simple matrix game.
Consider a standard one-step Prisoner’s Dilemma with the payoff matrix as in Table 3a. Here, the
only equilibrium is mutual defection (DD), despite cooperation (CC) being mutually beneficial. How
should a benevolent principal change the matrix through payments to incentivize cooperation?
One answer is that CC should become an equilibrium through minimal payments in CC. In one of
the payment schemes that achieve this, the principal pays a unit of utility to both players for the
28
Table 3: Prisoner’s Dilemma as a principal-multi-agent game. ‘Def’ denotes ‘Defect’ and ‘Coop’
denotes ‘Cooperate’. Blue highlights principal’s changes of agents’ payoffs.
(a) no payments (b) arbitrary payments in SPE (c) IC payments in SPE
Def Coop
Def 2, 2 4, 0
Coop 0, 4 3, 3Def Coop
Def 2, 2 4, 0
Coop 0, 4 4, 4Def Coop
Def 2, 2 4, 2
Coop 2, 4 4, 4
CC outcome, resulting in the payoff matrix as in Table 3b.8However, note that DD remains an
equilibrium for the agents. In fact, the new payoff matrix is also a social dilemma known as the Stag
Hunt. In the context of (decentralized) learning, there is no reason to expect the agents to converge
to CC instead of DD, and convergence to suboptimal equilibria has been observed empirically in
generalized Stag Hunt games [58].
As a more robust approach, the principal can make action C dominant. This is stronger than just
making CC an equilibrium because each agent will prefer action C regardless of the actions of others.
To achieve this, in addition to paying a unit of utility to both agents in CC, the principal pays two units
of utility to the cooperating agent in CD and DC, resulting in the payoff matrix as in Table 3c. This is
the kind of solution we implement in our application to SSDs, where we formulate the principal’s
objective as learning a social welfare maximizing strategy profile and its minimal implementation.
Importantly, in the context of our principal-agent model, the minimal implementation is consistent
with SPE in that the principal minimizes payments when agents best-respond by following recom-
mendations (CC in our example). So the IC property is an additional constraint, which specifies
an otherwise ambiguous objective of finding the principal’s policy in SPE, and which only requires
additional payments in equilibrium.
Note that in our example, the payment to each agent for the same action depends on the other agent’s
action (e.g., the row agent receives +2 in CD and +1 in CC). This dependence on other agents is
even more pronounced in stochastic games, where payments of a minimal implementation condition
on the policies of others – not only on their immediate actions in the current state but also on their
actions in all possible future states.9For this reason, learning the precise minimal implementation
is generally impractical: consider a neural network used for contract estimation for some agent
explicitly conditioning on the parameters of neural networks of all other agents, or on their actions in
all states of the MDP.
As a tractable alternative, we use a simple approximation that performs well in our experiments.
Specifically, we train the principal assuming that each agent sticks to one of two policies: either
always follow the principal’s recommendations and get paid, or ignore them and act independently as
if there is no principal. In equilibrium, both policies maximize the agent’s welfare, which justifies the
assumption. For implementation details of this approximation, see Appendix D.2.
D Experiments
D.1 Experiments in Tree MDPs
In this section, we empirically test the convergence of Algorithm 1 towards SPE in hidden-action
MDPs. We experiment with a small variation on the algorithm, which expedites convergence: the
agent and principal policies are updated simultaneously instead of iteratively. This can be seen as
terminating inner and outer tasks early, after one update, leading to approximately optimal policies.
Environment. In these experiments, we simulate a multi-stage project in which the principal offers
contracts at intermediate stages, influencing the agent’s choice of effort. Specifically, we model an
MDP that is a complete binary tree, where the agent’s decisions at each state are binary, representing
8Unlike the single-agent model, the optimal payment scheme here is ambiguous. Any payment scheme that
gives a unit of utility to both agents in CC and no utility to a defecting agent in DC and CD forms an SPE when
coupled with best-responding agents: CC becomes an equilibrium, the payments in which are minimized.
9Here we refer to the dependence of value functions on π−iin the IC constraints (5).
29
Algorithm 2 A deep Q-learning implementation of Algorithm 1 in the single-agent setting
Require: principal’s Q-network θ, agent’s Q-network ϕ, target networks θ′andϕ′, replay buffer RB
1:Initialize buffer RBwith random transitions, networks θandϕwith random parameters
2:fornumber of updates do ▷Training loop
3: fornumber of interactions per update do ▷Interact with the MDP
4: Select an action to recommend, ap, with qθ(s, a)viaϵ-greedy
5: Sample o∼ O(s, a),ra=r(s, a),rp=rp(s, o), transition the MDP to s′∼ T(s, o)
6: Add the transition (s, ap, ra, rp, o, d, s′)to the buffer RB
7: Ifd= 1, reset the MDP ▷ dis a binary ‘done’ variable indicating termination
8: Sample a mini-batch of transitions mb∼RB
9: for(s, ap, ra, rp, o, d, s′)∈mbdo ▷Estimate target variables to update θandϕ
10: ap′= arg maxa′qθ(s′, a′) ▷Select the next action for Q-learning updates
11: Find optimal contracts b∗(s, ap)andb∗(s′, ap′)by solving LP (17)
12: yp(s, ap) =rp−b∗(s, ap, o) +γ(1−d)qθ′(s′, ap′)
13: ya(s, ap) =ra+γ(1−d)(Eo′∼O(s′,ap′)b∗(s′, ap′, o′) +Qϕ′
(s′, ap′))
14: Minimize L(θ) =P
mb
qθ(s, ap)−yp(s, ap)2▷Update θas DQN
15: Minimize L(ϕ) =P
mb
Qϕ(s, ap)−ya(s, ap)2
▷Update ϕas DQN
high or low effort, and correspond to good or bad outcomes with different probabilities. This is an
intentionally simple environment, allowing us to compare with precise ground truth.
The MDP is represented by a complete binary decision tree with depth 10, resulting in 1023 states.
In each state, the agent may take two actions, a0anda1, which may result in two outcomes, o0and
o1. The action a0results in the outcome o0with probability 0.9in all states; likewise, a1results in o1
with probability 0.9. The tree transitions to the left subtree after outcome o0and to the right subtree
after outcome o1.
The action a0yields no cost for the agent, i.e., ∀s:r(s, a 0) = 0 ; and the outcome o0yields no
reward for the principal, i.e. ∀s:rp(s, o 0) = 0 . Conversely, the action a1is always costly and
the outcome o1is always rewarding, with values randomly sampled. Specifically, let Udenote
one-dimensional uniform distribution, U1=U[0,1]andU2=U[0,2]. Then, the agent’s reward
is generated as r(s, a 1) =−(u∼U[0,1−(v∼U1)]), and the principal’s reward is generated as
rp(s, o 1) = (u∼U[0,2−(v∼U2)])Note that the principal’s reward is on average higher than the
agent’s cost. Using this reward function sampling method, the principal’s policy ρ∗in SPE offers
non-trivial contracts that incentivize a1in about 60% of states.
Experimental procedure. We generate three instances of the Tree MDP, each with randomly
sampled reward functions, and used five trials of our algorithm on each Tree MDP. We also use
backward induction to find the exact policies in SPE (π∗, ρ∗)and the corresponding optimal utilities,
which we adopt as the ground truth. By comparing with ground truth directly, our two-phase procedure
from Section 4 becomes somewhat redundant, so we defer it to our multi-agent experiments in a
significantly more complex MDP.
Implementation details. We parameterize the principal’s and the agent’s Q-functions as Deep
Q-Networks [51] respectively denoted by θandϕ. The input to both networks is a state s, and both
networks approximate Q-values for all actions a∈A. Specifically, the principal’s network estimates
the contractual optimal Q-values qθ(s, a), representing its payoffs when optimally incentivizing the
agent to take action ain state s; and the agent’s network estimates the truncated optimal Q-values
Qϕ(s, a), representing its payoffs minus the expected immediate payment.
Algorithm 2 describes our Deep Q-learning-based implementation of Algorithm 1 for the single-agent
MDPs. The overall pipeline is standard, with a few notable details.
First, unlike the iterative convergence of the principal and the agent in Algorithm 1, the two policies
are trained simultaneously.
30
(a) Principal’s utility
(b) Agent’s utility
(c) Accuracy of Principal Action
Figure 3: Results in Tree MDPs. Solid lines are learning curves of DQNs trained with Algorithm 2.
Dashed lines represent ‘optimal’ utilities in SPE obtained with dynamic programming. Different
colors represent three distinct instances of the tree environment. For each, we use five trials of the
algorithm (shaded regions represent standard errors).
Second, the outcome function Ois assumed to be known. If not, it can be parameterized as an
additional neural network ξand trained as a probabilistic classifier with sampled outcomes used
as ground truth; the resulting loss function would be L(ξ) =P
mbCE[Oξ(s, ap), o], where CE
denotes cross-entropy, mbdenotes a mini-batch, and Oξ(s, ap)denotes the predicted probabilities of
outcomes as a function of state-action. We implemented this in our single-agent experiments with O
constant across states and found no difference from having access to O, although this might change
in more complex scenarios.
Third, when updating the agent’s network ϕ, the target variable yϕ′(s, ap)is estimated based on the
contract in the next state s′rather than the current state s. Since payment is a part of reward, the
target variable is effectively estimated as a mixture of parts of rewards in sands′. This is required so
that the truncated rather than the standard Q-function is learned.
Hyperparameters. The neural networks have 2hidden fully connected layers, each consisting
of256neurons and followed by a ReLU activation. The networks are trained for 20000 iterations,
each iteration including 8environment interactions and a single gradient update on a mini-batch
with128transitions, sampled from the replay buffer. Every 100iterations, the target networks are
updated by copying the parameters of the online networks. The learning rate is initialized at 0.001
and is exponentially annealed to 0.0001 throughout the training. Similarly, the exploration rate ϵis
initialized at 1and is linearly annealed to 0throughout the training. Rewards are not discounted, i.e.,
γ= 1.
Results. The results are presented in Figure 3. From Figure 3a, we observe that our algorithm
attains a principal’s utility of just 2%below the optimal utility in SPE. On the other hand, Figure 3b
shows that the agent’s utility can exhibit similar (in absolute terms) deviations from SPE in either
direction. The ’accuracy’ metric in Figure 3c indicates that the principal recommends the action
prescribed by the optimal policy in approximately 90% of the states.
The small underperformance in the principal’s utility and the biases in the agent’s utility can be
partially attributed to the 10% of the non-optimal principal’s actions. That around 90% of correct
actions amount to around 98% of the principal’s utility suggests errors likely occur in rarely visited
states or states where actions result in similar payoffs. effectiveness in approximating the SPE. The
minor discrepancies in utility, coupled with the learning dynamics, underscore the complex interplay
between the principal and the agent as they adapt to each other throughout training.
D.2 Experiments in the Coin Game
Implementation details. Algorithm 3 describes our Deep Q-learning-based implementation of
Algorithm 1 for the multi-agent MDPs with self-interested agents, often referred to as “sequential
social dilemmas”. The experimental procedure consists of two phases: training and validation.
In the training phase, for each agent i, the principal’s objective is to find a policy to recommend
by learning the contractual Q-function, qθ
i, as well as its minimal implementation by learning the
agent’s Q-function in the absence of the principal, Qϕ
i. In Section 5.1, we additionally require the
31
(a) Social welfare
(b) Social welfare, nudging
(c) Proportion of social welfare paid
(d) Accuracy
(e) Convergence to SPE?
(f) Incentive-Compatible contracts?
Figure 4: Learning curves in the Coin Game with a 3×3grid and each episode lasting for 20
time steps. The structure is the same as in Figure 2, with the addition of the top middle plot. The
definition of the plots is as follows: a) total return of the two agents (without payments); b) same,
but our algorithm and constant baseline additionally pay 10% of social welfare to the agents; c) a
ratio of the total payment by the principal to what the agents would effectively be paid if directly
maximizing social welfare; d) the proportion of the principal’s recommendations followed by the
validation agents; r) a ratio between the utilities of an agent’s policy at a given iteration and the
recommended policy, with the opponent using the recommended policy; f) same ratio, but with the
opponent’s policy at a given iteration. Each experiment is repeated 5 times, and each measurement is
averaged over 80 episodes.
minimal implementation to be in dominant strategies. Learning such an implementation requires
conditioning Qϕ
ion the inter-agent policies π−i, which is intractable. As a tractable approximation,
given that rational agents will only deviate from recommendations if their expected payoffs are
not compromised, we simplify each agent’s strategy space to two primary strategies: cooperation
(following the principal’s recommendations) or rational deviation (default optimal policy disregarding
contracts, which gives the same utility). We encapsulate this behavior in a binary variable fi∈ {0,1},
indicating whether agent ifollows the recommendation ap. Then, Qϕ
iis conditioned on the joint f−i
variable of the other agents, indicating both the immediate outcome and the agents’ future behavior.
The efficacy of this simplification is validated through our experimental results.
During the training phase, we randomly sample fifor each agent at the beginning of an episode. For
the episode’s remainder, each agent either follows the recommendations given by qθ
i(iffi= 1) or
acts selfishly according to Qϕ
i(iffi= 0). The experience generated this way is then used to train
bothθandϕ, enhancing exploration and covering the whole space of f.
Given the principal obtained in the training phase, the subsequent validation phase independently
trains selfish agents parameterized by ψifrom scratch in the modified environment. Specifically, each
agent observes an action recommendation when computing Q-values, Qψi
i((s, ap
i), ai), and is paid
by the principal if the recommendation is followed. When estimating payments, fisimply indicates
whether agent ifollowed the recommendation. Other than these changes, we use the standard DQN
training procedure. We also do not assume the principal’s access to the agents’ private information
like Q-values or parameters.
Hyperparameters. The neural networks consist of 1hidden convolutional layer followed by 2
hidden fully connected layers and an output layer. The convolutions have 4×4kernels and transform
the initial 4-channel states into 32channels. The fully connected layers consist of 64neurons. All
hidden layers are followed by ReLU activations. The networks are trained for 1000000 iterations,
each iteration including a single environment interaction and a single gradient update on a mini-batch
with128transitions, sampled from the replay buffer. Every 100iterations, the target networks are
32
updated by copying the parameters of the online networks. The learning rate is initialized at 0.0005
and is exponentially annealed to 0.0001 throughout the training. Similarly, the exploration rate ϵis
initialized at 0.4and is linearly annealed to 0throughout the training. The discounting factor is set at
γ= 0.99. For more efficient training, we use prioritized replay buffers [ 69] with a maximum size of
100000 ,α= 0.4,β= 0, and ϵ= 10−7.
Additional results. In Figure 4, we report results in the Coin Game with a 3×3grid and each
episode lasting for 20time steps. This is a simpler environment than the one in the main text, as the
state space and the horizon are smaller.
During training, our algorithm finds an approximately optimal joint policy (Fig. 4a) and estimates
that about 30% of social welfare is sufficient for an IC implementation (Fig. 4c). Interestingly
and contrary to our previous results, the validation phase does not confirm this: we observe that
the validation agents fall short of the optimal performance, as well as that our algorithm does not
outperform the constant proportion baseline (Fig. 4a). On the one hand, we do not find evidence that
it does not converge to SPE, as in Figure 4e, the utility ratio hovers around 1. On the other hand, a
test on incentive compatibility (Fig. 4f) reveals that the validation agents consistently find policies
that perform 5%to10% better against the opponent DQNs, meaning that the principal fails to learn
IC contracts. For more information on these tests, see the discussion in Section 5.3 We conjecture
that this negative result is due to using the approximation of IC through fivariables during training,
as described in the implementation details.
As an ad-hoc remedy, we attempt to artificially increase the principal’s payments by 10% of the
social welfare; we increase the proportion of the constant baseline accordingly. This is a form of
nudging intended to remedy the performance-degrading effects of approximation errors discussed in
Section 4. The effect of this modification is illustrated in Figure 4b: the performance of our algorithm
reaches that of the optimal baseline, whereas the constant baseline still falls short. Furthermore, the
IC property appears fixed as the utility ratio decreases to around 1(Fig. 4f). The accuracy metric also
improves, raising the frequency of agents following the principal’s recommendation from around
80% to around 90%.
Overall, we believe these results to be positive: our algorithm falls short somewhat predictably given
the practical approximation of IC (and the tie-breaking assumption), and still manages to outperform
the constant baseline while paying the same. As a side note, these results also showcase the usefulness
of our two-step experimental procedure, as opposed to the usual performance comparison during the
training phase, which does not reveal the hidden issues.
D.3 Compute
All experiments were run on a desktop PC with 16 GB RAM, 11th Gen Intel(R) Core i5-11600KF
@3.90GHz processor, and NVIDIA GeForce RTX 2060 GPU. The single-agent experiments were
run using only CPU, and the multi-agent experiments were run using GPU to store and train neural
networks and CPU for everything else. Each run (one algorithm, one random trial) takes thirty
minutes to an hour. The open-source code packages we use are PyTorch (BSD-style license) [ 56],
RLlib (Apache license) [ 44], Stable-Baselines3 (MIT license) [ 61], Gymnasium (MIT license) [ 76],
and W&B (MIT license) [4].
33
Algorithm 3 A deep Q-learning implementation of Algorithm 1 in the multi-agent setting
TRAINING PHASE
Require: principal’s Q-network θ, agents’ Q-network ϕ, target networks θ′,ϕ′, replay buffer RB
1:Initialize buffer RBwith random transitions, networks θandϕwith random parameters
2:Sample a binary vector f= (fi)i∈N▷ fiindicates if ifollows recommendations this episode
3:fornumber of updates do ▷Training loop
4: fornumber of interactions per update do ▷Interact with the MDP
5: fori∈N:fi= 1do: ▷The principal acts for these agents
6: Select a recommended action ap
iwithqθ
i(s, ap
i)viaϵ-greedy, set ai=ap
i
7: fori∈N:fi= 0do: ▷These agents act selfishly ignoring payments
8: Select an agent’s action aiwithQϕ
i((s,f−i), ai)viaϵ-greedy
9: fori∈Ndo: ▷Get rewards from the environment
10: ri=ri(s,a)
11: Transition the MDP to s′∼ T(s,a)
12: Add the transition (s,a,f,r, s′)to the buffer RB
13: Ifd= 1, reset the MDP and resample f
14: Sample a mini-batch of transitions mb∼RB
15: for(s,a,f,r, s′)∈mbdo ▷Estimate target variables to update θandϕ
16: fori∈Ndo
17: b∗
i(s, ai) = max aQϕ
i((s,1), a)−Qϕ
i((s,1), ai) ▷As if awere recommended
18: yp
i(s, ai) =ri−αb∗
i(s, ai) +γmax a′
iqθ′
i(s′, a′
i) ▷we set α= 0.1
19: ya
i(s, ai) =ri+γmax a′
iQϕ′((s′,f−i), a′
i)
20: Minimize L(θ) =P
mb P
iqθ
i(s, ai)−P
iyp
i(s, ai)2▷Update θas VDN
21: Minimize L(ϕ) =P
mbP
i
Qϕ
i((s,f−i), ai)−ya
i(s, ai)2
▷Update ϕas DQN
V ALIDATION PHASE
Require: validation agents’ Q-networks (ψi)i∈N, target networks (ψ′
i), replay buffer RB
22:Initialize buffer RBwith random transitions, networks ψiwith random parameters
23:fornumber of updates do ▷Training loop
24: fornumber of interactions per update do ▷Interact with the MDP
25: fori∈Ndo ▷Agents act selfishly
26: ap
i= arg maxaqθ
i(s, a) ▷Recommended action by θ
27: Select an agent’s action aiwithQψi
i((s, ap
i), ai)via epsilon-greedy
28: Setfi= 1ifai=ap
ielsefi= 0 ▷ fiindicates if ifollowed recommendation in s
29: fori∈Ndo: ▷Get total rewards
30: b∗
i(s, ap
i) = max aQϕ
i((s,f−i), a)−Qϕ
i((s,f−i), ap
i)
31: Ri=ri(s,a) +fib∗
i(s, ap
i) ▷Agent iis only paid if fi= 1
32: Transition the MDP to s′∼ T(s,a)
33: Add the transition (s,a,R, s′)to the buffer RB
34: Ifd= 1, reset the MDP
35: Sample a mini-batch of transitions mb∼RB
36: fori∈Ndo ▷Independently update each Q-network
37: for(s, ai, Ri, s′)∈mbdo ▷Estimate target variables to update ψi
38: ap′
i= arg maxa′qθ
i(s′, a′)
39: yi(s, ai) =Ri+γmax a′
iQψ′
i
i((s′, ap′
i), a′
i)
40: Minimize L(ψi) =P
mb
Qψi
i((s, ap
i), ai)−yi(s, ai)2
▷Update ψias DQN
34 | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found |
2407.18129v1 | http://arxiv.org/pdf/2407.18129v1 | Dallah: A Dialect-Aware Multimodal Large Language Model for Arabic | Fakhraddin Alwajih, Gagan Bhatia, Muhammad Abdul-Mageed | 2024-07-25 | Abstract
Recent advancements have significantly en-
hanced the capabilities of Multimodal Large
Language Models (MLLMs) in generating and
understanding image-to-text content. Despite
these successes, progress is predominantly lim-
ited to English due to the scarcity of high-
quality multimodal resources in other lan-
guages. This limitation impedes the develop-
ment of competitive models in languages such
as Arabic. To alleviate this situation, we intro-
duce an efficient Arabic multimodal assistant,
dubbed Dallah , that utilizes an advanced lan-
guage model based on LLaMA-2 to facilitate
multimodal interactions. Dallah demonstrates
state-of-the-art performance in Arabic MLLMs.
Through fine-tuning six Arabic dialects, Dal-
lahshowcases its capability to handle complex
dialectal interactions incorporating both tex-
tual and visual elements. The model excels in
two benchmark tests: one evaluating its perfor-
mance on Modern Standard Arabic (MSA) and
another specifically designed to assess dialectal
responses. Beyond its robust performance in
multimodal interaction tasks, Dallah has the po-
tential to pave the way for further development
of dialect-aware Arabic MLLMs.
1 | Introduction
Large language models (LLMs) have revolution-
ized how machines understand and generate hu-
man language. Recent developments have signifi-
cantly expanded the scope of these models by in-
tegrating multimodal data, enabling sophisticated
interaction with both textual and visual informa-
tion. Despite these advances, applying NLP in
linguistically diverse environments presents unique
challenges, particularly in processing dialectal vari-
ations of languages and the integration of these
variations within multimodal contexts. These chal-
lenges are especially pronounced in Arabic, a col-
lection of languages and varieties characterized by
a rich tapestry of dialects that vary significantly
Figure 1: Map highlighting the countries targeted by
Dallah for dialectal Arabic dataset construction.
across different regions.
Arabic dialects enrich the cultural landscape and
present complex linguistic variations that standard
NLP models, primarily designed for MSA, often
fail to solve. This linguistic diversity requires the
development of specialized models that can navi-
gate the rich world of dialectal Arabic and its inte-
gration with visual data. Addressing these needs is
crucial for improving user interaction and preserv-
ing linguistic heritage, as many dialects are under-
represented. Some may be at risk of diminishing in
the face of globalization and cultural homogeniza-
tion.
Multi-cultural and multi-modal LLMs (Alwa-
jih et al., 2024; Huang et al., 2023; Sengupta
et al., 2023) are vital against cultural homogeniza-
tion, where globalization tends to favour domi-
nant languages like Arabic. This can potentially
lead to the marginalization or even extinction of
less widely spoken dialects (Barnet and Cavanagh,
2014; Ahmedov and Shaxrizoda, 2024; Fahmi and
Liska, 2024). By including these low-resource di-
alects, we can ensure their continued relevance and
preserve the rich linguistic diversity of the Arabic-
speaking world.
To this end, we introduce a powerful multimodal
language model that specifically targets the unique
aspects of Arabic dialects. Our model, dubbed Dal-
lah, is built on the foundations of LLaV A (Liu et al.,
2023b), an advanced multimodal language modelarXiv:2407.18129v1 [cs.CL] 25 Jul 2024
framework. We enhance LLaV A with the linguistic
capabilities of AraLLaMA (Alwajih et al., 2024),
an LLM proficient in Arabic and English. Dallah
is designed to understand and generate content in
Arabic, navigating the complex interplay between
different dialects and visual information effectively.
The following are the main contributions of our
work:
1.We present Dallah , which combines the ro-
bust multimodal processing power of LLaV A
with the dialectal versatility of AraLLaMA,
creating a model uniquely equipped to handle
the linguistic and visual challenges presented
by Arabic dialects.
2.We introduce a novel data filtering method that
optimizes the selection and usage of training
data, ensuring that Dallah is fine-tuned with
high-quality, relevant multimodal datasets that
reflect the linguistic diversity found within the
Arab world.
3.Dallah supports wide dialectal coverage, suc-
cessfully fine-tuning over six major Arabic
dialects using limited but highly representa-
tive dialectal data.
4.We introduce Dallah-Bench evaluation bench-
mark for Arabic dialects tailored to assess the
efficacy of multimodal language models in
real-world applications that require an under-
standing of dialectal variations.
5.We have also built an understanding of which
model from the set {GPT4, GPT4-Turbo,
Command-R+ }is best suited for evaluating
MSA and dialectal data compared to Human
evaluation.
The remainder of this paper is structured as fol-
lows: In Section 2, we provide an overview of | Section not found | related work. Section 3 details our | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | methodology,
including the processes for Arabic dataset trans-
lation and filtering, construction of dialectal Ara-
bic datasets, the architecture of Dallah , and the
training procedures employed. In Section 4, we
describe our implementation details and the bench-
marks used for evaluation. Section 5 presents our
experimental results, including both quantitative
and qualitative analyses. We conclude in Section 6
with a discussion of our findings and future work.2 Related Work
2.1 Large Language Models
Recent progress in NLP has been driven by ad-
vances in LLMs, starting with the foundational
Transformer model (Vaswani et al., 2017). This
innovation paved the way for language models like
the encoder-based BERT (Devlin et al., 2018), and
the decoder-based Generative Pre-trained Trans-
former (GPT) (Brown et al., 2020), as well as
encoder-decoder-based models like T5 (Raffel
et al., 2020), which have significantly improved
linguistic understanding and performance in com-
plex language processing tasks. The develop-
ment of models such as OPT (Zhang et al., 2022),
LLaMA (Touvron et al., 2023a), LLaMA-2 (Tou-
vron et al., 2023b), GPT-2 (Radford et al., 2019),
GPT-3 (Brown et al., 2020), GPT-4 (Achiam
et al., 2023), and ChatGPT (OpenAI, 2023) Mis-
tral (Jiang et al., 2023), Mixtral (Jiang et al., 2024),
Phi-2 (Javaheripi et al., 2023), Phi-3 (Abdin et al.,
2024), and instruction-tuned variants of LLaMA-2
like Alpaca (Taori et al., 2023) and Vicuna (Chiang
et al., 2023), have demonstrated the rapid evolution
of the field. These models benefit from extensive
training on large datasets and tailored instruction
sets, enhancing their effectiveness.
Arabic LLMs Building on the global momen-
tum, the scope of LLMs has extended into Arabic
language processing. The introduction of Jasmine
(Nagoudi et al., 2023) marked a significant mile-
stone, followed by AceGPT (Huang et al., 2023)
and Jais (Sengupta et al., 2023), which have en-
hanced Arabic conversational AI. Recently, AraL-
LaMA (Alwajih et al., 2024) set a new standard
with its proficiency in the Egyptian Arabic dialect,
showcasing the flexibility of LLMs in handling
linguistically diverse data.
2.2 Multimodal Large Language Models
The integration of computer vision and natural lan-
guage processing has given rise to Visual Language
Models (VLMs). These models merge visual and
linguistic data, enhancing tasks that require visual
perception and language abilities. Models like
CLIP (Radford et al., 2021) bridge the gap between
visual recognition and language tasks, demonstrat-
ing the effectiveness of cross-modal applications.
Recent advancements show that LLMs improve
VLMs. Innovations such as Flamingo (Alayrac
et al., 2022), Blip-2 (Li et al., 2023), and
LLaV A (Liu et al., 2023b) have leveraged large
image-text pair datasets, enhancing cross-modal
coordination and learning efficiency. These mod-
els also employ specialized architectural features
for better integration. For instance, Flamingo
utilizes a perceiver resampler to integrate visual
data, and Blip-2 introduces a Q-Former (Li et al.,
2023) for aligning visual and language modalities.
LLaV A (Liu et al., 2023b) adjusts a linear pro-
jection layer to synchronize vision and language
modalities. Meanwhile, LLaV A1.6 (Liu et al.,
2023a) incorporates extensive instruction tuning
and a high-resolution vision encoder, achieving
outstanding results across multiple benchmarks.
Arabic Multimodal LLMs In Arabic NLP, Pea-
cock (Alwajih et al., 2024) represents the first work
in Arabic-centric MLLM capable of handling Ara-
bic multimodal interaction effectively. Addition-
ally, the multilingual PALO (Maaz et al., 2024)
has demonstrated the ability to process and inte-
grate multiple languages, including Arabic, into
multimodal contexts.
2.3 Multimodal Instruction Tuning Datasets
Development of MLLMs typically involves two
phases. The first phase focuses on aligning vi-
sual and linguistic features, utilizing datasets such
as COCO (Lin et al., 2014), LLaV A-Pretrain (Liu
et al., 2023b), and Laion (Schuhmann et al., 2022).
The subsequent visual instruction fine-tuning phase
enhances the models’ capabilities to follow com-
plex multimodal instructions. This phase often
involves transforming existing datasets into more
conversationally relevant formats using advanced
LLMs such as GPT-4, as seen in models like
LLaV A-Instruct (Liu et al., 2023b) and SVIT (Liu
et al., 2024). Recent works utilized GPT-4V (Ope-
nAI, 2023) to generate new captions and question-
answers, such as in ShareGPT4V (Chen et al.,
2023), LVIS-instruct4v (Wang et al., 2023) and
Allava (Chen et al., 2024). Arabic MLLMs uti-
lized translated versions of LLaV A-Instruct (Alwa-
jih et al., 2024; Maaz et al., 2024) using different
tools for translation.
3 Methodology
3.1 Arabic Dataset Translation and Filtering
In the first step, we aimed to build an Arabic
MLLM using Arabic datasets. A major obstacle
facing Arabic MLLMs is the lack of resources.This lack is largely due to the challenges of sourc-
ing relevant Arabic image-text pairs on a large
scale. To bridge this resource gap, we have imple-
mented a careful translate-and-filter pipeline con-
sisting of a translation stage and a filtering stage
inspired by (Mohamed et al., 2023; Alwajih et al.,
2024). This pipeline converts publicly available,
English-centric image-text and visual instruction
datasets into Arabic while maintaining data quality
and preventing error propagation due to translation.
We utilize the latest version of the Google Trans-
late API (Google Cloud) for the translation stage
which is the best translation method as shown by
(Zhu et al., 2023). We also conducted back trans-
lation as required by the subsequent filtering stage.
During the filtering stage , we ensure the quality
of our translations by employing a sentence em-
bedding model (Meng et al., 2024; Wang et al.,
2024). We assess the quality by calculating the
similarity of embedding between the original and
back-translated sentences for both question and an-
swer pairs, retaining only those translations that
meet our quality standards. Essentially, we keep
examples with questions and answers above a pre-
defined threshold, which we have empirically set
at 80%. Figure 3 illustrates the translation and
filtering process. Unlike the | methods used in (Mo-
hamed et al., 2023; Alwajih et al., 2024), we em-
ploy an English sentence embedding model based
on Mistral-7b (Wang et al., 2024) to calculate the
similarities. This last model is more powerful than
embedding models used in Mohamed et al. (2023);
Alwajih et al. (2024) as shown by MTEB leader-
board (Muennighoff et al., 2022). Refer to Figure 2
for examples illustrating our pipeline’s effective-
ness.
3.2 Dialectal Arabic Dataset Construction
Due to the absence of Arabic dialectal data tailored
for vision tasks, we randomly select six subsets
from our translated LLaV A-instruct 150k dataset.
We aim to ensure that each subset included diverse
content types, such as conversations, complex rea-
soning, and detailed descriptions, from the LLaV A-
instruct dataset. Our goal is to capture the dialects
of Egypt, Mauritania, Morocco, Palestine, Saudi
Arabia, and Yemen. These dialects represent a
broad spectrum of Arabic dialects.
These subsets are then assigned to native profes-
sional translators from the aforementioned coun-
tries in order to translate them from MSA into their
respective dialects. Table 1 displays the number of
What ar e the surf ers holding?Original
ﻣﺎذا ﻳﺤﻤﻞ ﻣﺘﺼﻔﺤﻲ؟Arabic Translation
What does m y browser load?English Back Translation
0.513672 Similarity
The jumper in the image is a
snowboar der.اﻟﻄﺎﺋﺮ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ھﻮ ﻣﺘﺰﻟﺞ ﻋﻠﻰ
اﻟﺠﻠﯿﺪ.The bir d in the photo is an ice skater . 0.549805
Where is the surf er located? أﻳﻦ ﻳﻘﻊ ﻣﻘﺮ ﺳﯿﺮﻓﺮ؟ Where is S erver's headquarters? 0.580566
What is the condi tion of the str eet wher e
the stop sign is located?ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?1.00000
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?0.900391
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻧﻌﻢ، ﺗﻮﺟﺪ ﺗﻌﻠﯿﻘﺎت ﻣﻌﻠﻘﺔ ﻋﻠﻰ اﻟﮫﺎﺗﻒ اﻟﻘﺎﺑﻞ
ﻟﻠﻄﻲ، ﻣﻤﺎ ﻳﻀﯿﻒ ﻟﻤﺴﺔ ﻣﻦ اﻟﺘﺨﺼﯿﺺ
واﻷﻧﺎﻗﺔ إﻟﻰ اﻟﺠﮫﺎز.Yes, ther e are suspensions on the f oldable
phone, adding a touch of personal ization
and elegance to the device.0.800293Figure 2: This figure illustrates the translation and filtering process used in constructing the Arabic dataset for
Dallah . The red rows represent examples that were removed due to low similarity scores between the original
English text and the back-translated English text. The green rows show the retained examples that met the similarity
threshold, ensuring high-quality translations for effective model training.
عA
عACosine Similarity
Raw DataEmbedding Model
Embedding Model
Clean DataTranslation to Arabic
Original EnglishBack Translated English
Threshold filterTranslation back to English
ArabicEnglish
Figure 3: Illustration of the translation and filtering
process for constructing high-quality Arabic multi-
modal datasets. Examples illustrating the results of
this pipeline are in Figure 2.
samples per country, while Figure 1 illustrates the
targeted countries on the map. Refer to A.2 for
more details.
Stage Source #Sample
Pretraining LLaV A-Pretrain LCS (Arabic+English) 800k
Inst. TuningLLaV A-Instruct English 150k
LLaV A-Instruct Arabic 139k
Dialectal TuningEgypt 738
Mauritania 495
Morocco 505
Palestine 853
Saudi Arabia 784
Yemen 604
Total 1.1 M
Table 1: Number of samples used for each stage in the
training of Dallah .3.3 Architecture
The Dallah model follows the structure of
LLaV A1.5 (Liu et al., 2023a) and comprises three
key elements:
1.Vision Encoder: The vision encoder ( Vφ) em-
ploys the CLIP-Large model (Radford et al.,
2021) to process input images ( X) into 576
visual tokens at a resolution of 336x336 with
a patch size of 14, producing a sequence of
patch features V={vj∈Rdx}M
i=j.
2.Projector: A connector ( Pϕ), designed as
a two-layer multi-layer perceptron (MLP),
maps the visual patch sequences {vj}M
j=1to
the text embedding space {hj}M
j=1, allow-
ing for effective integration between the pre-
trained LLM and the vision encoder.
3.Language Model (LLM): The Arabic LLM
(Fθ), based on AraLLaMA (Alwajih et al.,
2024)1processes sequences of text embed-
dings{hi}N−1
i=0in the d-dimensional space,
outputting corresponding next predictions
{hi}N
i=1. A tokenizer and embedding module
maps text sequences {yi}N−1
i=0to the embed-
ding space and back to output text sequences
{yi}N
i=1.
This structure equips the model to handle various
multimodal understanding tasks, taking an image
and instruction text sequence as input and generat-
ing a text sequence as output. Figure 4 illustrates
Dallah architecture.
1AraLLaMA is an enhanced version of LLaMA-2 (Tou-
vron et al., 2023a).
Embedding
SpaceLanguage Model (AraLLaMA 7B)
Vision Encoder
(CLIP ViT-L/336x336px)Vision Language Connector
(MLP) Tokenizer & Embedding
: ﻣﺎ اﻟﺬي ﻳﻤﻜﻦ اﺳﺘﻨﺘﺎﺟﻪ USER
ﻣﻦ اﻟﺼﻮرة؟
Model ResponseFigure 4: Dallah model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide
qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights.
Limitations
We identify a number of limitations for our work,
as follows:
•Representation of Arabic Culture : Vision
models, LLMs, and datasets used in build-
ing MLLMs inadequately represent Arabic
figures, places, and culture. As shown in Fig-
ure 10, Dallah struggles with recognizing Ara-
bic figures, unlike those from the USA. This
highlights the need for more diverse cultural
datasets.
•Hallucination Control :Dallah , like many
LLMs, is prone to hallucinations, generating
inaccurate information. Advanced techniquesand more robust datasets are needed to miti-
gate this issue and ensure reliability.
•Dialect Variation and Mixing : The model
sometimes mixes similar dialects, such as
Yemeni and Saudi, and struggles with di-
alects close to MSA. This can be improved
with more extensive | Section not found | data collection and fine-
tuning.
•Arabic Text Recognition in Images :Dal-
lahcannot effectively recognize Arabic text
within images due to the lack of annotated
datasets. Developing such datasets is essential
to enhance the model’s multimodal capabili-
ties.
Ethics Statement
Energy Efficiency. OurDallah models, like many
large MLLMs, require significant pre-training time
and are not energy-efficient. We acknowledge this
critical issue and support continued research to-
wards developing energy-efficient models.
Data. Our pre-training datasets are translated from
publicly available English data, encompassing di-
verse genres, communities, and varieties. Our Dal-
lahmodels demonstrate potential in applications
involving several Arabic varieties, serving broad
populations.
Human Annotation. The human annotators in-
volved in this project are Arabic native speakers
and well-educated individuals with PhD degrees
and extensive NLP experience. No Institutional
Review Board (IRB) review or approval was re-
quired for this project since we only used publicly
available data, which does not require access to any
social networking account or password.
Applications. While Dallah , like many MLLMs,
can be misused. It also holds promise for bene-
ficial applications in education, health, and more.
Responsible deployment and use are crucial to max-
imizing its positive impact. It would also help keep
Arabic varieties in use in written form in the digital
age.
Acknowledgments
We acknowledge support from Canada Research
Chairs (CRC), the Natural Sciences and Engineer-
ing Research Council of Canada (NSERC; RGPIN-
2018-04267), the Social Sciences and Humanities
Research Council of Canada (SSHRC; 435-2018-
0576; 895-2020-1004; 895-2021-1008), Canadian
Foundation for Innovation (CFI; 37771), Digital
Research Alliance of Canada,6and UBC ARC-
Sockeye.
References
Marah Abdin, Sam Ade Jacobs, Ammar Ahmad Awan,
Jyoti Aneja, Ahmed Awadallah, Hany Awadalla,
Nguyen Bach, Amit Bahree, Arash Bakhtiari, Harki-
rat Behl, et al. 2024. Phi-3 technical report: A highly
capable language model locally on your phone. arXiv
preprint arXiv:2404.14219 .
Josh Achiam, Steven Adler, Sandhini Agarwal, Lama
Ahmad, Ilge Akkaya, Florencia Leoni Aleman,
Diogo Almeida, Janko Altenschmidt, Sam Altman,
Shyamal Anadkat, et al. 2023. Gpt-4 technical report.
arXiv preprint arXiv:2303.08774 .
Azimjon Ahmedov and Xabibullayeva Shaxrizoda.
2024. The english effect. Ta’limning zamonaviy
transformatsiyasi , 7(3):18–23.
Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc,
Antoine Miech, Iain Barr, Yana Hasson, Karel
Lenc, Arthur Mensch, Katherine Millican, Malcolm
Reynolds, et al. 2022. Flamingo: a visual language
model for few-shot learning. Advances in neural
information processing systems , 35:23716–23736.
Fakhraddin Alwajih, El Moatez Billah Nagoudi, Gagan
Bhatia, Abdelrahman Mohamed, and Muhammad
Abdul-Mageed. 2024. Peacock: A family of arabic
multimodal large language models and benchmarks.
Preprint , arXiv:2403.01031.
Richard Barnet and John Cavanagh. 2014. Homoge-
nization of global culture. In The case against the
global economy , pages 169–174. Routledge.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind
Neelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, et al. 2020. Language models are few-shot
learners. Advances in neural information processing
systems , 33:1877–1901.
Guiming Hardy Chen, Shunian Chen, Ruifei Zhang,
Junying Chen, Xiangbo Wu, Zhiyi Zhang, Zhihong
Chen, Jianquan Li, Xiang Wan, and Benyou Wang.
2024. Allava: Harnessing gpt4v-synthesized data
for a lite vision-language model. arXiv preprint
arXiv:2402.11684 .
Lin Chen, Jisong Li, Xiaoyi Dong, Pan Zhang, Con-
ghui He, Jiaqi Wang, Feng Zhao, and Dahua
Lin. 2023. Sharegpt4v: Improving large multi-
modal models with better captions. arXiv preprint
arXiv:2311.12793 .
Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng,
Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan
6https://alliancecan.caZhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion
Stoica, and Eric P. Xing. 2023. Vicuna: An open-
source chatbot impressing gpt-4 with 90%* chatgpt
quality.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. Bert: Pre-training of deep
bidirectional transformers for language understand-
ing.arXiv preprint arXiv:1810.04805 .
Zakaria Fahmi and Dacota Liska. 2024. Promoting ara-
bic as a foreign language in the middle east and north
africa: Host-grounded study abroad discourses. Fron-
tiers: The Interdisciplinary Journal of Study Abroad ,
36(1):384–417.
Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang,
and Weizhu Chen. 2021. Lora: Low-rank adap-
tation of large language models. arXiv preprint
arXiv:2106.09685 .
Huang Huang, Fei Yu, Jianqing Zhu, Xuening Sun, Hao
Cheng, Dingjie Song, Zhihong Chen, Abdulmohsen
Alharthi, Bang An, Ziche Liu, Zhiyi Zhang, Juny-
ing Chen, Jianquan Li, Benyou Wang, Lian Zhang,
Ruoyu Sun, Xiang Wan, Haizhou Li, and Jinchao Xu.
2023. Acegpt, localizing large language models in
arabic. Preprint , arXiv:2309.12053.
Mojan Javaheripi, S ´ebastien Bubeck, Marah Abdin,
Jyoti Aneja, Caio C ´esar Teodoro Mendes, Weizhu
Chen, Allie Del Giorno, Ronen Eldan, Sivakanth
Gopi, Suriya Gunasekar, Piero Kauffmann, Yin Tat
Lee, Yuanzhi Li, Anh Nguyen, Gustavo de Rosa,
Olli Saarikivi, Adil Salim, Shital Shah, Michael San-
tacroce, Harkirat Singh Behl, Adam Taumann Kalai,
Xin Wang, Rachel Ward, Philipp Witte, Cyril Zhang,
and Yi Zhang. 2023. Phi-2: The surprising power of
small language models. Microsoft Research Blog.
Albert Q Jiang, Alexandre Sablayrolles, Arthur Men-
sch, Chris Bamford, Devendra Singh Chaplot, Diego
de las Casas, Florian Bressand, Gianna Lengyel, Guil-
laume Lample, Lucile Saulnier, et al. 2023. Mistral
7b.arXiv preprint arXiv:2310.06825 .
Albert Q Jiang, Alexandre Sablayrolles, Antoine
Roux, Arthur Mensch, Blanche Savary, Chris Bam-
ford, Devendra Singh Chaplot, Diego de las Casas,
Emma Bou Hanna, Florian Bressand, et al. 2024.
Mixtral of experts. arXiv preprint arXiv:2401.04088 .
Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi.
2023. Blip-2: Bootstrapping language-image pre-
training with frozen image encoders and large lan-
guage models. In International conference on ma-
chine learning , pages 19730–19742. PMLR.
Tsung-Yi Lin, Michael Maire, Serge Belongie, James
Hays, Pietro Perona, Deva Ramanan, Piotr Doll ´ar,
and C Lawrence Zitnick. 2014. Microsoft coco:
Common objects in context. In Computer Vision–
ECCV 2014: 13th European Conference, Zurich,
Switzerland, September 6-12, 2014, Proceedings,
Part V 13 , pages 740–755. Springer.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2023a. Improved baselines with visual instruc-
tion tuning.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2024. Improved baselines with visual instruc-
tion tuning. In Proceedings of the IEEE/CVF Con-
ference on Computer Vision and Pattern Recognition ,
pages 26296–26306.
Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae
Lee. 2023b. Visual instruction tuning. In NeurIPS .
Muhammad Maaz, Hanoona Rasheed, Abdelrahman
Shaker, Salman Khan, Hisham Cholakal, Rao M. An-
wer, Tim Baldwin, Michael Felsberg, and Fahad S.
Khan. 2024. Palo: A polyglot large multimodal
model for 5b people. Preprint , arXiv:2402.14818.
Rui Meng, Ye Liu, Shafiq Rayhan Joty, Caiming
Xiong, Yingbo Zhou, and Semih Yavuz. 2024. Sfr-
embedding-mistral:enhance text retrieval with trans-
fer learning.
Abdelrahman Mohamed, Fakhraddin Alwajih,
El Moatez Billah Nagoudi, Alcides Inciarte, and
Muhammad Abdul-Mageed. 2023. Violet: A
vision-language model for Arabic image captioning
with gemini decoder. In Proceedings of ArabicNLP
2023 , pages 1–11, Singapore (Hybrid). Association
for Computational Linguistics.
Niklas Muennighoff, Nouamane Tazi, Lo ¨ıc Magne, and
Nils Reimers. 2022. Mteb: Massive text embedding
benchmark. arXiv preprint arXiv:2210.07316 .
El Moatez Billah Nagoudi, Muhammad Abdul-Mageed,
AbdelRahim Elmadany, Alcides Alcoba Inciarte, and
Md Tawkat Islam Khondaker. 2023. Jasmine: Ara-
bic gpt models for few-shot learning. Preprint ,
arXiv:2212.10755.
OpenAI. 2023. Chatgpt. AI language model. Accessed:
2024-04-30.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya
Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sas-
try, Amanda Askell, Pamela Mishkin, Jack Clark,
et al. 2021. Learning transferable visual models from
natural language supervision. In International confer-
ence on machine learning , pages 8748–8763. PMLR.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan,
Dario Amodei, Ilya Sutskever, et al. 2019. Language
models are unsupervised multitask learners. OpenAI
blog, 1(8):9.
Colin Raffel, Noam Shazeer, Adam Roberts, Katherine
Lee, Sharan Narang, Michael Matena, Yanqi Zhou,
Wei Li, and Peter J Liu. 2020. Exploring the lim-
its of transfer learning with a unified text-to-text
transformer. Journal of machine learning research ,
21(140):1–67.Christoph Schuhmann, Romain Beaumont, Richard
Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti,
Theo Coombes, Aarush Katta, Clayton Mullis,
Mitchell Wortsman, et al. 2022. Laion-5b: An open
large-scale dataset for training next generation image-
text models. Advances in Neural Information Pro-
cessing Systems , 35:25278–25294.
Neha Sengupta, Sunil Kumar Sahu, Bokang Jia,
Satheesh Katipomu, Haonan Li, Fajri Koto, William
Marshall, Gurpreet Gosal, Cynthia Liu, Zhiming
Chen, Osama Mohammed Afzal, Samta Kamboj,
Onkar Pandit, Rahul Pal, Lalit Pradhan, Zain Muham-
mad Mujahid, Massa Baali, Xudong Han, Son-
dos Mahmoud Bsharat, Alham Fikri Aji, Zhiqiang
Shen, Zhengzhong Liu, Natalia Vassilieva, Joel Hes-
tness, Andy Hock, Andrew Feldman, Jonathan Lee,
Andrew Jackson, Hector Xuguang Ren, Preslav
Nakov, Timothy Baldwin, and Eric Xing. 2023.
Jais and jais-chat: Arabic-centric foundation and
instruction-tuned open generative large language
models. Preprint , arXiv:2308.16149.
Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann
Dubois, Xuechen Li, Carlos Guestrin, Percy Liang,
and Tatsunori B. Hashimoto. 2023. Stanford alpaca:
An instruction-following llama model. https://
github.com/tatsu-lab/stanford alpaca .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timoth ´ee Lacroix,
Baptiste Rozi `ere, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Junke Wang, Lingchen Meng, Zejia Weng, Bo He, Zux-
uan Wu, and Yu-Gang Jiang. 2023. To see is to be-
lieve: Prompting gpt-4v for better visual instruction
tuning. arXiv preprint arXiv:2311.07574 .
Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang,
Rangan Majumder, and Furu Wei. 2024. Multilingual
e5 text embeddings: A technical report. Preprint ,
arXiv:2402.05672.
Susan Zhang, Stephen Roller, Naman Goyal, Mikel
Artetxe, Moya Chen, Shuohui Chen, Christopher De-
wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022.
Opt: Open pre-trained transformer language models.
arXiv preprint arXiv:2205.01068 .
Wenhao Zhu, Hongyi Liu, Qingxiu Dong, Jingjing Xu,
Shujian Huang, Lingpeng Kong, Jiajun Chen, and
Lei Li. 2023. Multilingual machine translation with
large language models: Empirical | Section not found | results, including both quantitative
and qualitative analyses. We conclude in Section 6
with a discussion of our | findings and future work.2 Related Work
2.1 Large Language Models
Recent progress in NLP has been driven by ad-
vances in LLMs, starting with the foundational
Transformer model (Vaswani et al., 2017). This
innovation paved the way for language models like
the encoder-based BERT (Devlin et al., 2018), and
the decoder-based Generative Pre-trained Trans-
former (GPT) (Brown et al., 2020), as well as
encoder-decoder-based models like T5 (Raffel
et al., 2020), which have significantly improved
linguistic understanding and performance in com-
plex language processing tasks. The develop-
ment of models such as OPT (Zhang et al., 2022),
LLaMA (Touvron et al., 2023a), LLaMA-2 (Tou-
vron et al., 2023b), GPT-2 (Radford et al., 2019),
GPT-3 (Brown et al., 2020), GPT-4 (Achiam
et al., 2023), and ChatGPT (OpenAI, 2023) Mis-
tral (Jiang et al., 2023), Mixtral (Jiang et al., 2024),
Phi-2 (Javaheripi et al., 2023), Phi-3 (Abdin et al.,
2024), and instruction-tuned variants of LLaMA-2
like Alpaca (Taori et al., 2023) and Vicuna (Chiang
et al., 2023), have demonstrated the rapid evolution
of the field. These models benefit from extensive
training on large datasets and tailored instruction
sets, enhancing their effectiveness.
Arabic LLMs Building on the global momen-
tum, the scope of LLMs has extended into Arabic
language processing. The introduction of Jasmine
(Nagoudi et al., 2023) marked a significant mile-
stone, followed by AceGPT (Huang et al., 2023)
and Jais (Sengupta et al., 2023), which have en-
hanced Arabic conversational AI. Recently, AraL-
LaMA (Alwajih et al., 2024) set a new standard
with its proficiency in the Egyptian Arabic dialect,
showcasing the flexibility of LLMs in handling
linguistically diverse data.
2.2 Multimodal Large Language Models
The integration of computer vision and natural lan-
guage processing has given rise to Visual Language
Models (VLMs). These models merge visual and
linguistic data, enhancing tasks that require visual
perception and language abilities. Models like
CLIP (Radford et al., 2021) bridge the gap between
visual recognition and language tasks, demonstrat-
ing the effectiveness of cross-modal applications.
Recent advancements show that LLMs improve
VLMs. Innovations such as Flamingo (Alayrac
et al., 2022), Blip-2 (Li et al., 2023), and
LLaV A (Liu et al., 2023b) have leveraged large
image-text pair datasets, enhancing cross-modal
coordination and learning efficiency. These mod-
els also employ specialized architectural features
for better integration. For instance, Flamingo
utilizes a perceiver resampler to integrate visual
data, and Blip-2 introduces a Q-Former (Li et al.,
2023) for aligning visual and language modalities.
LLaV A (Liu et al., 2023b) adjusts a linear pro-
jection layer to synchronize vision and language
modalities. Meanwhile, LLaV A1.6 (Liu et al.,
2023a) incorporates extensive instruction tuning
and a high-resolution vision encoder, achieving
outstanding results across multiple benchmarks.
Arabic Multimodal LLMs In Arabic NLP, Pea-
cock (Alwajih et al., 2024) represents the first work
in Arabic-centric MLLM capable of handling Ara-
bic multimodal interaction effectively. Addition-
ally, the multilingual PALO (Maaz et al., 2024)
has demonstrated the ability to process and inte-
grate multiple languages, including Arabic, into
multimodal contexts.
2.3 Multimodal Instruction Tuning Datasets
Development of MLLMs typically involves two
phases. The first phase focuses on aligning vi-
sual and linguistic features, utilizing datasets such
as COCO (Lin et al., 2014), LLaV A-Pretrain (Liu
et al., 2023b), and Laion (Schuhmann et al., 2022).
The subsequent visual instruction fine-tuning phase
enhances the models’ capabilities to follow com-
plex multimodal instructions. This phase often
involves transforming existing datasets into more
conversationally relevant formats using advanced
LLMs such as GPT-4, as seen in models like
LLaV A-Instruct (Liu et al., 2023b) and SVIT (Liu
et al., 2024). Recent works utilized GPT-4V (Ope-
nAI, 2023) to generate new captions and question-
answers, such as in ShareGPT4V (Chen et al.,
2023), LVIS-instruct4v (Wang et al., 2023) and
Allava (Chen et al., 2024). Arabic MLLMs uti-
lized translated versions of LLaV A-Instruct (Alwa-
jih et al., 2024; Maaz et al., 2024) using different
tools for translation.
3 Methodology
3.1 Arabic Dataset Translation and Filtering
In the first step, we aimed to build an Arabic
MLLM using Arabic datasets. A major obstacle
facing Arabic MLLMs is the lack of resources.This lack is largely due to the challenges of sourc-
ing relevant Arabic image-text pairs on a large
scale. To bridge this resource gap, we have imple-
mented a careful translate-and-filter pipeline con-
sisting of a translation stage and a filtering stage
inspired by (Mohamed et al., 2023; Alwajih et al.,
2024). This pipeline converts publicly available,
English-centric image-text and visual instruction
datasets into Arabic while maintaining data quality
and preventing error propagation due to translation.
We utilize the latest version of the Google Trans-
late API (Google Cloud) for the translation stage
which is the best translation method as shown by
(Zhu et al., 2023). We also conducted back trans-
lation as required by the subsequent filtering stage.
During the filtering stage , we ensure the quality
of our translations by employing a sentence em-
bedding model (Meng et al., 2024; Wang et al.,
2024). We assess the quality by calculating the
similarity of embedding between the original and
back-translated sentences for both question and an-
swer pairs, retaining only those translations that
meet our quality standards. Essentially, we keep
examples with questions and answers above a pre-
defined threshold, which we have empirically set
at 80%. Figure 3 illustrates the translation and
filtering process. Unlike the methods used in (Mo-
hamed et al., 2023; Alwajih et al., 2024), we em-
ploy an English sentence embedding model based
on Mistral-7b (Wang et al., 2024) to calculate the
similarities. This last model is more powerful than
embedding models used in Mohamed et al. (2023);
Alwajih et al. (2024) as shown by MTEB leader-
board (Muennighoff et al., 2022). Refer to Figure 2
for examples illustrating our pipeline’s effective-
ness.
3.2 Dialectal Arabic Dataset Construction
Due to the absence of Arabic dialectal data tailored
for vision tasks, we randomly select six subsets
from our translated LLaV A-instruct 150k dataset.
We aim to ensure that each subset included diverse
content types, such as conversations, complex rea-
soning, and detailed descriptions, from the LLaV A-
instruct dataset. Our goal is to capture the dialects
of Egypt, Mauritania, Morocco, Palestine, Saudi
Arabia, and Yemen. These dialects represent a
broad spectrum of Arabic dialects.
These subsets are then assigned to native profes-
sional translators from the aforementioned coun-
tries in order to translate them from MSA into their
respective dialects. Table 1 displays the number of
What ar e the surf ers holding?Original
ﻣﺎذا ﻳﺤﻤﻞ ﻣﺘﺼﻔﺤﻲ؟Arabic Translation
What does m y browser load?English Back Translation
0.513672 Similarity
The jumper in the image is a
snowboar der.اﻟﻄﺎﺋﺮ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ھﻮ ﻣﺘﺰﻟﺞ ﻋﻠﻰ
اﻟﺠﻠﯿﺪ.The bir d in the photo is an ice skater . 0.549805
Where is the surf er located? أﻳﻦ ﻳﻘﻊ ﻣﻘﺮ ﺳﯿﺮﻓﺮ؟ Where is S erver's headquarters? 0.580566
What is the condi tion of the str eet wher e
the stop sign is located?ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?1.00000
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?0.900391
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻧﻌﻢ، ﺗﻮﺟﺪ ﺗﻌﻠﯿﻘﺎت ﻣﻌﻠﻘﺔ ﻋﻠﻰ اﻟﮫﺎﺗﻒ اﻟﻘﺎﺑﻞ
ﻟﻠﻄﻲ، ﻣﻤﺎ ﻳﻀﯿﻒ ﻟﻤﺴﺔ ﻣﻦ اﻟﺘﺨﺼﯿﺺ
واﻷﻧﺎﻗﺔ إﻟﻰ اﻟﺠﮫﺎز.Yes, ther e are suspensions on the f oldable
phone, adding a touch of personal ization
and elegance to the device.0.800293Figure 2: This figure illustrates the translation and filtering process used in constructing the Arabic dataset for
Dallah . The red rows represent examples that were removed due to low similarity scores between the original
English text and the back-translated English text. The green rows show the retained examples that met the similarity
threshold, ensuring high-quality translations for effective model training.
عA
عACosine Similarity
Raw DataEmbedding Model
Embedding Model
Clean DataTranslation to Arabic
Original EnglishBack Translated English
Threshold filterTranslation back to English
ArabicEnglish
Figure 3: Illustration of the translation and filtering
process for constructing high-quality Arabic multi-
modal datasets. Examples illustrating the results of
this pipeline are in Figure 2.
samples per country, while Figure 1 illustrates the
targeted countries on the map. Refer to A.2 for
more details.
Stage Source #Sample
Pretraining LLaV A-Pretrain LCS (Arabic+English) 800k
Inst. TuningLLaV A-Instruct English 150k
LLaV A-Instruct Arabic 139k
Dialectal TuningEgypt 738
Mauritania 495
Morocco 505
Palestine 853
Saudi Arabia 784
Yemen 604
Total 1.1 M
Table 1: Number of samples used for each stage in the
training of Dallah .3.3 Architecture
The Dallah model follows the structure of
LLaV A1.5 (Liu et al., 2023a) and comprises three
key elements:
1.Vision Encoder: The vision encoder ( Vφ) em-
ploys the CLIP-Large model (Radford et al.,
2021) to process input images ( X) into 576
visual tokens at a resolution of 336x336 with
a patch size of 14, producing a sequence of
patch features V={vj∈Rdx}M
i=j.
2.Projector: A connector ( Pϕ), designed as
a two-layer multi-layer perceptron (MLP),
maps the visual patch sequences {vj}M
j=1to
the text embedding space {hj}M
j=1, allow-
ing for effective integration between the pre-
trained LLM and the vision encoder.
3.Language Model (LLM): The Arabic LLM
(Fθ), based on AraLLaMA (Alwajih et al.,
2024)1processes sequences of text embed-
dings{hi}N−1
i=0in the d-dimensional space,
outputting corresponding next predictions
{hi}N
i=1. A tokenizer and embedding module
maps text sequences {yi}N−1
i=0to the embed-
ding space and back to output text sequences
{yi}N
i=1.
This structure equips the model to handle various
multimodal understanding tasks, taking an image
and instruction text sequence as input and generat-
ing a text sequence as output. Figure 4 illustrates
Dallah architecture.
1AraLLaMA is an enhanced version of LLaMA-2 (Tou-
vron et al., 2023a).
Embedding
SpaceLanguage Model (AraLLaMA 7B)
Vision Encoder
(CLIP ViT-L/336x336px)Vision Language Connector
(MLP) Tokenizer & Embedding
: ﻣﺎ اﻟﺬي ﻳﻤﻜﻦ اﺳﺘﻨﺘﺎﺟﻪ USER
ﻣﻦ اﻟﺼﻮرة؟
Model ResponseFigure 4: Dallah model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide
qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights. | discussion of our findings and future work.2 Related Work
2.1 Large Language Models
Recent progress in NLP has been driven by ad-
vances in LLMs, starting with the foundational
Transformer model (Vaswani et al., 2017). This
innovation paved the way for language models like
the encoder-based BERT (Devlin et al., 2018), and
the decoder-based Generative Pre-trained Trans-
former (GPT) (Brown et al., 2020), as well as
encoder-decoder-based models like T5 (Raffel
et al., 2020), which have significantly improved
linguistic understanding and performance in com-
plex language processing tasks. The develop-
ment of models such as OPT (Zhang et al., 2022),
LLaMA (Touvron et al., 2023a), LLaMA-2 (Tou-
vron et al., 2023b), GPT-2 (Radford et al., 2019),
GPT-3 (Brown et al., 2020), GPT-4 (Achiam
et al., 2023), and ChatGPT (OpenAI, 2023) Mis-
tral (Jiang et al., 2023), Mixtral (Jiang et al., 2024),
Phi-2 (Javaheripi et al., 2023), Phi-3 (Abdin et al.,
2024), and instruction-tuned variants of LLaMA-2
like Alpaca (Taori et al., 2023) and Vicuna (Chiang
et al., 2023), have demonstrated the rapid evolution
of the field. These models benefit from extensive
training on large datasets and tailored instruction
sets, enhancing their effectiveness.
Arabic LLMs Building on the global momen-
tum, the scope of LLMs has extended into Arabic
language processing. The introduction of Jasmine
(Nagoudi et al., 2023) marked a significant mile-
stone, followed by AceGPT (Huang et al., 2023)
and Jais (Sengupta et al., 2023), which have en-
hanced Arabic conversational AI. Recently, AraL-
LaMA (Alwajih et al., 2024) set a new standard
with its proficiency in the Egyptian Arabic dialect,
showcasing the flexibility of LLMs in handling
linguistically diverse data.
2.2 Multimodal Large Language Models
The integration of computer vision and natural lan-
guage processing has given rise to Visual Language
Models (VLMs). These models merge visual and
linguistic data, enhancing tasks that require visual
perception and language abilities. Models like
CLIP (Radford et al., 2021) bridge the gap between
visual recognition and language tasks, demonstrat-
ing the effectiveness of cross-modal applications.
Recent advancements show that LLMs improve
VLMs. Innovations such as Flamingo (Alayrac
et al., 2022), Blip-2 (Li et al., 2023), and
LLaV A (Liu et al., 2023b) have leveraged large
image-text pair datasets, enhancing cross-modal
coordination and learning efficiency. These mod-
els also employ specialized architectural features
for better integration. For instance, Flamingo
utilizes a perceiver resampler to integrate visual
data, and Blip-2 introduces a Q-Former (Li et al.,
2023) for aligning visual and language modalities.
LLaV A (Liu et al., 2023b) adjusts a linear pro-
jection layer to synchronize vision and language
modalities. Meanwhile, LLaV A1.6 (Liu et al.,
2023a) incorporates extensive instruction tuning
and a high-resolution vision encoder, achieving
outstanding results across multiple benchmarks.
Arabic Multimodal LLMs In Arabic NLP, Pea-
cock (Alwajih et al., 2024) represents the first work
in Arabic-centric MLLM capable of handling Ara-
bic multimodal interaction effectively. Addition-
ally, the multilingual PALO (Maaz et al., 2024)
has demonstrated the ability to process and inte-
grate multiple languages, including Arabic, into
multimodal contexts.
2.3 Multimodal Instruction Tuning Datasets
Development of MLLMs typically involves two
phases. The first phase focuses on aligning vi-
sual and linguistic features, utilizing datasets such
as COCO (Lin et al., 2014), LLaV A-Pretrain (Liu
et al., 2023b), and Laion (Schuhmann et al., 2022).
The subsequent visual instruction fine-tuning phase
enhances the models’ capabilities to follow com-
plex multimodal instructions. This phase often
involves transforming existing datasets into more
conversationally relevant formats using advanced
LLMs such as GPT-4, as seen in models like
LLaV A-Instruct (Liu et al., 2023b) and SVIT (Liu
et al., 2024). Recent works utilized GPT-4V (Ope-
nAI, 2023) to generate new captions and question-
answers, such as in ShareGPT4V (Chen et al.,
2023), LVIS-instruct4v (Wang et al., 2023) and
Allava (Chen et al., 2024). Arabic MLLMs uti-
lized translated versions of LLaV A-Instruct (Alwa-
jih et al., 2024; Maaz et al., 2024) using different
tools for translation.
3 Methodology
3.1 Arabic Dataset Translation and Filtering
In the first step, we aimed to build an Arabic
MLLM using Arabic datasets. A major obstacle
facing Arabic MLLMs is the lack of resources.This lack is largely due to the challenges of sourc-
ing relevant Arabic image-text pairs on a large
scale. To bridge this resource gap, we have imple-
mented a careful translate-and-filter pipeline con-
sisting of a translation stage and a filtering stage
inspired by (Mohamed et al., 2023; Alwajih et al.,
2024). This pipeline converts publicly available,
English-centric image-text and visual instruction
datasets into Arabic while maintaining data quality
and preventing error propagation due to translation.
We utilize the latest version of the Google Trans-
late API (Google Cloud) for the translation stage
which is the best translation method as shown by
(Zhu et al., 2023). We also conducted back trans-
lation as required by the subsequent filtering stage.
During the filtering stage , we ensure the quality
of our translations by employing a sentence em-
bedding model (Meng et al., 2024; Wang et al.,
2024). We assess the quality by calculating the
similarity of embedding between the original and
back-translated sentences for both question and an-
swer pairs, retaining only those translations that
meet our quality standards. Essentially, we keep
examples with questions and answers above a pre-
defined threshold, which we have empirically set
at 80%. Figure 3 illustrates the translation and
filtering process. Unlike the methods used in (Mo-
hamed et al., 2023; Alwajih et al., 2024), we em-
ploy an English sentence embedding model based
on Mistral-7b (Wang et al., 2024) to calculate the
similarities. This last model is more powerful than
embedding models used in Mohamed et al. (2023);
Alwajih et al. (2024) as shown by MTEB leader-
board (Muennighoff et al., 2022). Refer to Figure 2
for examples illustrating our pipeline’s effective-
ness.
3.2 Dialectal Arabic Dataset Construction
Due to the absence of Arabic dialectal data tailored
for vision tasks, we randomly select six subsets
from our translated LLaV A-instruct 150k dataset.
We aim to ensure that each subset included diverse
content types, such as conversations, complex rea-
soning, and detailed descriptions, from the LLaV A-
instruct dataset. Our goal is to capture the dialects
of Egypt, Mauritania, Morocco, Palestine, Saudi
Arabia, and Yemen. These dialects represent a
broad spectrum of Arabic dialects.
These subsets are then assigned to native profes-
sional translators from the aforementioned coun-
tries in order to translate them from MSA into their
respective dialects. Table 1 displays the number of
What ar e the surf ers holding?Original
ﻣﺎذا ﻳﺤﻤﻞ ﻣﺘﺼﻔﺤﻲ؟Arabic Translation
What does m y browser load?English Back Translation
0.513672 Similarity
The jumper in the image is a
snowboar der.اﻟﻄﺎﺋﺮ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ھﻮ ﻣﺘﺰﻟﺞ ﻋﻠﻰ
اﻟﺠﻠﯿﺪ.The bir d in the photo is an ice skater . 0.549805
Where is the surf er located? أﻳﻦ ﻳﻘﻊ ﻣﻘﺮ ﺳﯿﺮﻓﺮ؟ Where is S erver's headquarters? 0.580566
What is the condi tion of the str eet wher e
the stop sign is located?ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?1.00000
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?0.900391
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻧﻌﻢ، ﺗﻮﺟﺪ ﺗﻌﻠﯿﻘﺎت ﻣﻌﻠﻘﺔ ﻋﻠﻰ اﻟﮫﺎﺗﻒ اﻟﻘﺎﺑﻞ
ﻟﻠﻄﻲ، ﻣﻤﺎ ﻳﻀﯿﻒ ﻟﻤﺴﺔ ﻣﻦ اﻟﺘﺨﺼﯿﺺ
واﻷﻧﺎﻗﺔ إﻟﻰ اﻟﺠﮫﺎز.Yes, ther e are suspensions on the f oldable
phone, adding a touch of personal ization
and elegance to the device.0.800293Figure 2: This figure illustrates the translation and filtering process used in constructing the Arabic dataset for
Dallah . The red rows represent examples that were removed due to low similarity scores between the original
English text and the back-translated English text. The green rows show the retained examples that met the similarity
threshold, ensuring high-quality translations for effective model training.
عA
عACosine Similarity
Raw DataEmbedding Model
Embedding Model
Clean DataTranslation to Arabic
Original EnglishBack Translated English
Threshold filterTranslation back to English
ArabicEnglish
Figure 3: Illustration of the translation and filtering
process for constructing high-quality Arabic multi-
modal datasets. Examples illustrating the results of
this pipeline are in Figure 2.
samples per country, while Figure 1 illustrates the
targeted countries on the map. Refer to A.2 for
more details.
Stage Source #Sample
Pretraining LLaV A-Pretrain LCS (Arabic+English) 800k
Inst. TuningLLaV A-Instruct English 150k
LLaV A-Instruct Arabic 139k
Dialectal TuningEgypt 738
Mauritania 495
Morocco 505
Palestine 853
Saudi Arabia 784
Yemen 604
Total 1.1 M
Table 1: Number of samples used for each stage in the
training of Dallah .3.3 Architecture
The Dallah model follows the structure of
LLaV A1.5 (Liu et al., 2023a) and comprises three
key elements:
1.Vision Encoder: The vision encoder ( Vφ) em-
ploys the CLIP-Large model (Radford et al.,
2021) to process input images ( X) into 576
visual tokens at a resolution of 336x336 with
a patch size of 14, producing a sequence of
patch features V={vj∈Rdx}M
i=j.
2.Projector: A connector ( Pϕ), designed as
a two-layer multi-layer perceptron (MLP),
maps the visual patch sequences {vj}M
j=1to
the text embedding space {hj}M
j=1, allow-
ing for effective integration between the pre-
trained LLM and the vision encoder.
3.Language Model (LLM): The Arabic LLM
(Fθ), based on AraLLaMA (Alwajih et al.,
2024)1processes sequences of text embed-
dings{hi}N−1
i=0in the d-dimensional space,
outputting corresponding next predictions
{hi}N
i=1. A tokenizer and embedding module
maps text sequences {yi}N−1
i=0to the embed-
ding space and back to output text sequences
{yi}N
i=1.
This structure equips the model to handle various
multimodal understanding tasks, taking an image
and instruction text sequence as input and generat-
ing a text sequence as output. Figure 4 illustrates
Dallah architecture.
1AraLLaMA is an enhanced version of LLaMA-2 (Tou-
vron et al., 2023a).
Embedding
SpaceLanguage Model (AraLLaMA 7B)
Vision Encoder
(CLIP ViT-L/336x336px)Vision Language Connector
(MLP) Tokenizer & Embedding
: ﻣﺎ اﻟﺬي ﻳﻤﻜﻦ اﺳﺘﻨﺘﺎﺟﻪ USER
ﻣﻦ اﻟﺼﻮرة؟
Model ResponseFigure 4: Dallah model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide
qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights. | Section not found | Section not found | Limitations
We identify a number of limitations for our work,
as follows:
•Representation of Arabic Culture : Vision
models, LLMs, and datasets used in build-
ing MLLMs inadequately represent Arabic
figures, places, and culture. As shown in Fig-
ure 10, Dallah struggles with recognizing Ara-
bic figures, unlike those from the USA. This
highlights the need for more diverse cultural
datasets.
•Hallucination Control :Dallah , like many
LLMs, is prone to hallucinations, generating
inaccurate information. Advanced techniquesand more robust datasets are needed to miti-
gate this issue and ensure reliability.
•Dialect Variation and Mixing : The model
sometimes mixes similar dialects, such as
Yemeni and Saudi, and struggles with di-
alects close to MSA. This can be improved
with more extensive data collection and fine-
tuning.
•Arabic Text Recognition in Images :Dal-
lahcannot effectively recognize Arabic text
within images due to the lack of annotated
datasets. Developing such datasets is essential
to enhance the model’s multimodal capabili-
ties.
Ethics Statement
Energy Efficiency. OurDallah models, like many
large MLLMs, require significant pre-training time
and are not energy-efficient. We acknowledge this
critical issue and support continued research to-
wards developing energy-efficient models.
Data. Our pre-training datasets are translated from
publicly available English data, encompassing di-
verse genres, communities, and varieties. Our Dal-
lahmodels demonstrate potential in applications
involving several Arabic varieties, serving broad
populations.
Human Annotation. The human annotators in-
volved in this project are Arabic native speakers
and well-educated individuals with PhD degrees
and extensive NLP experience. No Institutional
Review Board (IRB) review or approval was re-
quired for this project since we only used publicly
available data, which does not require access to any
social networking account or password.
Applications. While Dallah , like many MLLMs,
can be misused. It also holds promise for bene-
ficial applications in education, health, and more.
Responsible deployment and use are crucial to max-
imizing its positive impact. It would also help keep
Arabic varieties in use in written form in the digital
age. | future work.2 Related Work
2.1 Large Language Models
Recent progress in NLP has been driven by ad-
vances in LLMs, starting with the foundational
Transformer model (Vaswani et al., 2017). This
innovation paved the way for language models like
the encoder-based BERT (Devlin et al., 2018), and
the decoder-based Generative Pre-trained Trans-
former (GPT) (Brown et al., 2020), as well as
encoder-decoder-based models like T5 (Raffel
et al., 2020), which have significantly improved
linguistic understanding and performance in com-
plex language processing tasks. The develop-
ment of models such as OPT (Zhang et al., 2022),
LLaMA (Touvron et al., 2023a), LLaMA-2 (Tou-
vron et al., 2023b), GPT-2 (Radford et al., 2019),
GPT-3 (Brown et al., 2020), GPT-4 (Achiam
et al., 2023), and ChatGPT (OpenAI, 2023) Mis-
tral (Jiang et al., 2023), Mixtral (Jiang et al., 2024),
Phi-2 (Javaheripi et al., 2023), Phi-3 (Abdin et al.,
2024), and instruction-tuned variants of LLaMA-2
like Alpaca (Taori et al., 2023) and Vicuna (Chiang
et al., 2023), have demonstrated the rapid evolution
of the field. These models benefit from extensive
training on large datasets and tailored instruction
sets, enhancing their effectiveness.
Arabic LLMs Building on the global momen-
tum, the scope of LLMs has extended into Arabic
language processing. The introduction of Jasmine
(Nagoudi et al., 2023) marked a significant mile-
stone, followed by AceGPT (Huang et al., 2023)
and Jais (Sengupta et al., 2023), which have en-
hanced Arabic conversational AI. Recently, AraL-
LaMA (Alwajih et al., 2024) set a new standard
with its proficiency in the Egyptian Arabic dialect,
showcasing the flexibility of LLMs in handling
linguistically diverse data.
2.2 Multimodal Large Language Models
The integration of computer vision and natural lan-
guage processing has given rise to Visual Language
Models (VLMs). These models merge visual and
linguistic data, enhancing tasks that require visual
perception and language abilities. Models like
CLIP (Radford et al., 2021) bridge the gap between
visual recognition and language tasks, demonstrat-
ing the effectiveness of cross-modal applications.
Recent advancements show that LLMs improve
VLMs. Innovations such as Flamingo (Alayrac
et al., 2022), Blip-2 (Li et al., 2023), and
LLaV A (Liu et al., 2023b) have leveraged large
image-text pair datasets, enhancing cross-modal
coordination and learning efficiency. These mod-
els also employ specialized architectural features
for better integration. For instance, Flamingo
utilizes a perceiver resampler to integrate visual
data, and Blip-2 introduces a Q-Former (Li et al.,
2023) for aligning visual and language modalities.
LLaV A (Liu et al., 2023b) adjusts a linear pro-
jection layer to synchronize vision and language
modalities. Meanwhile, LLaV A1.6 (Liu et al.,
2023a) incorporates extensive instruction tuning
and a high-resolution vision encoder, achieving
outstanding results across multiple benchmarks.
Arabic Multimodal LLMs In Arabic NLP, Pea-
cock (Alwajih et al., 2024) represents the first work
in Arabic-centric MLLM capable of handling Ara-
bic multimodal interaction effectively. Addition-
ally, the multilingual PALO (Maaz et al., 2024)
has demonstrated the ability to process and inte-
grate multiple languages, including Arabic, into
multimodal contexts.
2.3 Multimodal Instruction Tuning Datasets
Development of MLLMs typically involves two
phases. The first phase focuses on aligning vi-
sual and linguistic features, utilizing datasets such
as COCO (Lin et al., 2014), LLaV A-Pretrain (Liu
et al., 2023b), and Laion (Schuhmann et al., 2022).
The subsequent visual instruction fine-tuning phase
enhances the models’ capabilities to follow com-
plex multimodal instructions. This phase often
involves transforming existing datasets into more
conversationally relevant formats using advanced
LLMs such as GPT-4, as seen in models like
LLaV A-Instruct (Liu et al., 2023b) and SVIT (Liu
et al., 2024). Recent works utilized GPT-4V (Ope-
nAI, 2023) to generate new captions and question-
answers, such as in ShareGPT4V (Chen et al.,
2023), LVIS-instruct4v (Wang et al., 2023) and
Allava (Chen et al., 2024). Arabic MLLMs uti-
lized translated versions of LLaV A-Instruct (Alwa-
jih et al., 2024; Maaz et al., 2024) using different
tools for translation.
3 Methodology
3.1 Arabic Dataset Translation and Filtering
In the first step, we aimed to build an Arabic
MLLM using Arabic datasets. A major obstacle
facing Arabic MLLMs is the lack of resources.This lack is largely due to the challenges of sourc-
ing relevant Arabic image-text pairs on a large
scale. To bridge this resource gap, we have imple-
mented a careful translate-and-filter pipeline con-
sisting of a translation stage and a filtering stage
inspired by (Mohamed et al., 2023; Alwajih et al.,
2024). This pipeline converts publicly available,
English-centric image-text and visual instruction
datasets into Arabic while maintaining data quality
and preventing error propagation due to translation.
We utilize the latest version of the Google Trans-
late API (Google Cloud) for the translation stage
which is the best translation method as shown by
(Zhu et al., 2023). We also conducted back trans-
lation as required by the subsequent filtering stage.
During the filtering stage , we ensure the quality
of our translations by employing a sentence em-
bedding model (Meng et al., 2024; Wang et al.,
2024). We assess the quality by calculating the
similarity of embedding between the original and
back-translated sentences for both question and an-
swer pairs, retaining only those translations that
meet our quality standards. Essentially, we keep
examples with questions and answers above a pre-
defined threshold, which we have empirically set
at 80%. Figure 3 illustrates the translation and
filtering process. Unlike the methods used in (Mo-
hamed et al., 2023; Alwajih et al., 2024), we em-
ploy an English sentence embedding model based
on Mistral-7b (Wang et al., 2024) to calculate the
similarities. This last model is more powerful than
embedding models used in Mohamed et al. (2023);
Alwajih et al. (2024) as shown by MTEB leader-
board (Muennighoff et al., 2022). Refer to Figure 2
for examples illustrating our pipeline’s effective-
ness.
3.2 Dialectal Arabic Dataset Construction
Due to the absence of Arabic dialectal data tailored
for vision tasks, we randomly select six subsets
from our translated LLaV A-instruct 150k dataset.
We aim to ensure that each subset included diverse
content types, such as conversations, complex rea-
soning, and detailed descriptions, from the LLaV A-
instruct dataset. Our goal is to capture the dialects
of Egypt, Mauritania, Morocco, Palestine, Saudi
Arabia, and Yemen. These dialects represent a
broad spectrum of Arabic dialects.
These subsets are then assigned to native profes-
sional translators from the aforementioned coun-
tries in order to translate them from MSA into their
respective dialects. Table 1 displays the number of
What ar e the surf ers holding?Original
ﻣﺎذا ﻳﺤﻤﻞ ﻣﺘﺼﻔﺤﻲ؟Arabic Translation
What does m y browser load?English Back Translation
0.513672 Similarity
The jumper in the image is a
snowboar der.اﻟﻄﺎﺋﺮ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ھﻮ ﻣﺘﺰﻟﺞ ﻋﻠﻰ
اﻟﺠﻠﯿﺪ.The bir d in the photo is an ice skater . 0.549805
Where is the surf er located? أﻳﻦ ﻳﻘﻊ ﻣﻘﺮ ﺳﯿﺮﻓﺮ؟ Where is S erver's headquarters? 0.580566
What is the condi tion of the str eet wher e
the stop sign is located?ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?1.00000
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?0.900391
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻧﻌﻢ، ﺗﻮﺟﺪ ﺗﻌﻠﯿﻘﺎت ﻣﻌﻠﻘﺔ ﻋﻠﻰ اﻟﮫﺎﺗﻒ اﻟﻘﺎﺑﻞ
ﻟﻠﻄﻲ، ﻣﻤﺎ ﻳﻀﯿﻒ ﻟﻤﺴﺔ ﻣﻦ اﻟﺘﺨﺼﯿﺺ
واﻷﻧﺎﻗﺔ إﻟﻰ اﻟﺠﮫﺎز.Yes, ther e are suspensions on the f oldable
phone, adding a touch of personal ization
and elegance to the device.0.800293Figure 2: This figure illustrates the translation and filtering process used in constructing the Arabic dataset for
Dallah . The red rows represent examples that were removed due to low similarity scores between the original
English text and the back-translated English text. The green rows show the retained examples that met the similarity
threshold, ensuring high-quality translations for effective model training.
عA
عACosine Similarity
Raw DataEmbedding Model
Embedding Model
Clean DataTranslation to Arabic
Original EnglishBack Translated English
Threshold filterTranslation back to English
ArabicEnglish
Figure 3: Illustration of the translation and filtering
process for constructing high-quality Arabic multi-
modal datasets. Examples illustrating the results of
this pipeline are in Figure 2.
samples per country, while Figure 1 illustrates the
targeted countries on the map. Refer to A.2 for
more details.
Stage Source #Sample
Pretraining LLaV A-Pretrain LCS (Arabic+English) 800k
Inst. TuningLLaV A-Instruct English 150k
LLaV A-Instruct Arabic 139k
Dialectal TuningEgypt 738
Mauritania 495
Morocco 505
Palestine 853
Saudi Arabia 784
Yemen 604
Total 1.1 M
Table 1: Number of samples used for each stage in the
training of Dallah .3.3 Architecture
The Dallah model follows the structure of
LLaV A1.5 (Liu et al., 2023a) and comprises three
key elements:
1.Vision Encoder: The vision encoder ( Vφ) em-
ploys the CLIP-Large model (Radford et al.,
2021) to process input images ( X) into 576
visual tokens at a resolution of 336x336 with
a patch size of 14, producing a sequence of
patch features V={vj∈Rdx}M
i=j.
2.Projector: A connector ( Pϕ), designed as
a two-layer multi-layer perceptron (MLP),
maps the visual patch sequences {vj}M
j=1to
the text embedding space {hj}M
j=1, allow-
ing for effective integration between the pre-
trained LLM and the vision encoder.
3.Language Model (LLM): The Arabic LLM
(Fθ), based on AraLLaMA (Alwajih et al.,
2024)1processes sequences of text embed-
dings{hi}N−1
i=0in the d-dimensional space,
outputting corresponding next predictions
{hi}N
i=1. A tokenizer and embedding module
maps text sequences {yi}N−1
i=0to the embed-
ding space and back to output text sequences
{yi}N
i=1.
This structure equips the model to handle various
multimodal understanding tasks, taking an image
and instruction text sequence as input and generat-
ing a text sequence as output. Figure 4 illustrates
Dallah architecture.
1AraLLaMA is an enhanced version of LLaMA-2 (Tou-
vron et al., 2023a).
Embedding
SpaceLanguage Model (AraLLaMA 7B)
Vision Encoder
(CLIP ViT-L/336x336px)Vision Language Connector
(MLP) Tokenizer & Embedding
: ﻣﺎ اﻟﺬي ﻳﻤﻜﻦ اﺳﺘﻨﺘﺎﺟﻪ USER
ﻣﻦ اﻟﺼﻮرة؟
Model ResponseFigure 4: Dallah model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide
qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 | Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights.
Limitations
We identify a number of limitations for our work,
as follows:
•Representation of Arabic Culture : Vision
models, LLMs, and datasets used in build-
ing MLLMs inadequately represent Arabic
figures, places, and culture. As shown in Fig-
ure 10, Dallah struggles with recognizing Ara-
bic figures, unlike those from the USA. This
highlights the need for more diverse cultural
datasets.
•Hallucination Control :Dallah , like many
LLMs, is prone to hallucinations, generating
inaccurate information. Advanced techniquesand more robust datasets are needed to miti-
gate this issue and ensure reliability.
•Dialect Variation and Mixing : The model
sometimes mixes similar dialects, such as
Yemeni and Saudi, and struggles with di-
alects close to MSA. This can be improved
with more extensive data collection and fine-
tuning.
•Arabic Text Recognition in Images :Dal-
lahcannot effectively recognize Arabic text
within images due to the lack of annotated
datasets. Developing such datasets is essential
to enhance the model’s multimodal capabili-
ties.
Ethics Statement
Energy Efficiency. OurDallah models, like many
large MLLMs, require significant pre-training time
and are not energy-efficient. We acknowledge this
critical issue and support continued research to-
wards developing energy-efficient models.
Data. Our pre-training datasets are translated from
publicly available English data, encompassing di-
verse genres, communities, and varieties. Our Dal-
lahmodels demonstrate potential in applications
involving several Arabic varieties, serving broad
populations.
Human Annotation. The human annotators in-
volved in this project are Arabic native speakers
and well-educated individuals with PhD degrees
and extensive NLP experience. No Institutional
Review Board (IRB) review or approval was re-
quired for this project since we only used publicly
available data, which does not require access to any
social networking account or password.
Applications. While Dallah , like many MLLMs,
can be misused. It also holds promise for bene-
ficial applications in education, health, and more.
Responsible deployment and use are crucial to max-
imizing its positive impact. It would also help keep
Arabic varieties in use in written form in the digital
age. | Section not found | Acknowledgments
We acknowledge support from Canada Research
Chairs (CRC), the Natural Sciences and Engineer-
ing Research Council of Canada (NSERC; RGPIN-
2018-04267), the Social Sciences and Humanities
Research Council of Canada (SSHRC; 435-2018-
0576; 895-2020-1004; 895-2021-1008), Canadian
Foundation for Innovation (CFI; 37771), Digital
Research Alliance of Canada,6and UBC ARC-
Sockeye. | References
Marah Abdin, Sam Ade Jacobs, Ammar Ahmad Awan,
Jyoti Aneja, Ahmed Awadallah, Hany Awadalla,
Nguyen Bach, Amit Bahree, Arash Bakhtiari, Harki-
rat Behl, et al. 2024. Phi-3 technical report: A highly
capable language model locally on your phone. arXiv
preprint arXiv:2404.14219 .
Josh Achiam, Steven Adler, Sandhini Agarwal, Lama
Ahmad, Ilge Akkaya, Florencia Leoni Aleman,
Diogo Almeida, Janko Altenschmidt, Sam Altman,
Shyamal Anadkat, et al. 2023. Gpt-4 technical report.
arXiv preprint arXiv:2303.08774 .
Azimjon Ahmedov and Xabibullayeva Shaxrizoda.
2024. The english effect. Ta’limning zamonaviy
transformatsiyasi , 7(3):18–23.
Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc,
Antoine Miech, Iain Barr, Yana Hasson, Karel
Lenc, Arthur Mensch, Katherine Millican, Malcolm
Reynolds, et al. 2022. Flamingo: a visual language
model for few-shot learning. Advances in neural
information processing systems , 35:23716–23736.
Fakhraddin Alwajih, El Moatez Billah Nagoudi, Gagan
Bhatia, Abdelrahman Mohamed, and Muhammad
Abdul-Mageed. 2024. Peacock: A family of arabic
multimodal large language models and benchmarks.
Preprint , arXiv:2403.01031.
Richard Barnet and John Cavanagh. 2014. Homoge-
nization of global culture. In The case against the
global economy , pages 169–174. Routledge.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind
Neelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, et al. 2020. Language models are few-shot
learners. Advances in neural information processing
systems , 33:1877–1901.
Guiming Hardy Chen, Shunian Chen, Ruifei Zhang,
Junying Chen, Xiangbo Wu, Zhiyi Zhang, Zhihong
Chen, Jianquan Li, Xiang Wan, and Benyou Wang.
2024. Allava: Harnessing gpt4v-synthesized data
for a lite vision-language model. arXiv preprint
arXiv:2402.11684 .
Lin Chen, Jisong Li, Xiaoyi Dong, Pan Zhang, Con-
ghui He, Jiaqi Wang, Feng Zhao, and Dahua
Lin. 2023. Sharegpt4v: Improving large multi-
modal models with better captions. arXiv preprint
arXiv:2311.12793 .
Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng,
Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan
6https://alliancecan.caZhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion
Stoica, and Eric P. Xing. 2023. Vicuna: An open-
source chatbot impressing gpt-4 with 90%* chatgpt
quality.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. Bert: Pre-training of deep
bidirectional transformers for language understand-
ing.arXiv preprint arXiv:1810.04805 .
Zakaria Fahmi and Dacota Liska. 2024. Promoting ara-
bic as a foreign language in the middle east and north
africa: Host-grounded study abroad discourses. Fron-
tiers: The Interdisciplinary Journal of Study Abroad ,
36(1):384–417.
Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang,
and Weizhu Chen. 2021. Lora: Low-rank adap-
tation of large language models. arXiv preprint
arXiv:2106.09685 .
Huang Huang, Fei Yu, Jianqing Zhu, Xuening Sun, Hao
Cheng, Dingjie Song, Zhihong Chen, Abdulmohsen
Alharthi, Bang An, Ziche Liu, Zhiyi Zhang, Juny-
ing Chen, Jianquan Li, Benyou Wang, Lian Zhang,
Ruoyu Sun, Xiang Wan, Haizhou Li, and Jinchao Xu.
2023. Acegpt, localizing large language models in
arabic. Preprint , arXiv:2309.12053.
Mojan Javaheripi, S ´ebastien Bubeck, Marah Abdin,
Jyoti Aneja, Caio C ´esar Teodoro Mendes, Weizhu
Chen, Allie Del Giorno, Ronen Eldan, Sivakanth
Gopi, Suriya Gunasekar, Piero Kauffmann, Yin Tat
Lee, Yuanzhi Li, Anh Nguyen, Gustavo de Rosa,
Olli Saarikivi, Adil Salim, Shital Shah, Michael San-
tacroce, Harkirat Singh Behl, Adam Taumann Kalai,
Xin Wang, Rachel Ward, Philipp Witte, Cyril Zhang,
and Yi Zhang. 2023. Phi-2: The surprising power of
small language models. Microsoft Research Blog.
Albert Q Jiang, Alexandre Sablayrolles, Arthur Men-
sch, Chris Bamford, Devendra Singh Chaplot, Diego
de las Casas, Florian Bressand, Gianna Lengyel, Guil-
laume Lample, Lucile Saulnier, et al. 2023. Mistral
7b.arXiv preprint arXiv:2310.06825 .
Albert Q Jiang, Alexandre Sablayrolles, Antoine
Roux, Arthur Mensch, Blanche Savary, Chris Bam-
ford, Devendra Singh Chaplot, Diego de las Casas,
Emma Bou Hanna, Florian Bressand, et al. 2024.
Mixtral of experts. arXiv preprint arXiv:2401.04088 .
Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi.
2023. Blip-2: Bootstrapping language-image pre-
training with frozen image encoders and large lan-
guage models. In International conference on ma-
chine learning , pages 19730–19742. PMLR.
Tsung-Yi Lin, Michael Maire, Serge Belongie, James
Hays, Pietro Perona, Deva Ramanan, Piotr Doll ´ar,
and C Lawrence Zitnick. 2014. Microsoft coco:
Common objects in context. In Computer Vision–
ECCV 2014: 13th European Conference, Zurich,
Switzerland, September 6-12, 2014, Proceedings,
Part V 13 , pages 740–755. Springer.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2023a. Improved baselines with visual instruc-
tion tuning.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2024. Improved baselines with visual instruc-
tion tuning. In Proceedings of the IEEE/CVF Con-
ference on Computer Vision and Pattern Recognition ,
pages 26296–26306.
Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae
Lee. 2023b. Visual instruction tuning. In NeurIPS .
Muhammad Maaz, Hanoona Rasheed, Abdelrahman
Shaker, Salman Khan, Hisham Cholakal, Rao M. An-
wer, Tim Baldwin, Michael Felsberg, and Fahad S.
Khan. 2024. Palo: A polyglot large multimodal
model for 5b people. Preprint , arXiv:2402.14818.
Rui Meng, Ye Liu, Shafiq Rayhan Joty, Caiming
Xiong, Yingbo Zhou, and Semih Yavuz. 2024. Sfr-
embedding-mistral:enhance text retrieval with trans-
fer learning.
Abdelrahman Mohamed, Fakhraddin Alwajih,
El Moatez Billah Nagoudi, Alcides Inciarte, and
Muhammad Abdul-Mageed. 2023. Violet: A
vision-language model for Arabic image captioning
with gemini decoder. In Proceedings of ArabicNLP
2023 , pages 1–11, Singapore (Hybrid). Association
for Computational Linguistics.
Niklas Muennighoff, Nouamane Tazi, Lo ¨ıc Magne, and
Nils Reimers. 2022. Mteb: Massive text embedding
benchmark. arXiv preprint arXiv:2210.07316 .
El Moatez Billah Nagoudi, Muhammad Abdul-Mageed,
AbdelRahim Elmadany, Alcides Alcoba Inciarte, and
Md Tawkat Islam Khondaker. 2023. Jasmine: Ara-
bic gpt models for few-shot learning. Preprint ,
arXiv:2212.10755.
OpenAI. 2023. Chatgpt. AI language model. Accessed:
2024-04-30.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya
Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sas-
try, Amanda Askell, Pamela Mishkin, Jack Clark,
et al. 2021. Learning transferable visual models from
natural language supervision. In International confer-
ence on machine learning , pages 8748–8763. PMLR.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan,
Dario Amodei, Ilya Sutskever, et al. 2019. Language
models are unsupervised multitask learners. OpenAI
blog, 1(8):9.
Colin Raffel, Noam Shazeer, Adam Roberts, Katherine
Lee, Sharan Narang, Michael Matena, Yanqi Zhou,
Wei Li, and Peter J Liu. 2020. Exploring the lim-
its of transfer learning with a unified text-to-text
transformer. Journal of machine learning research ,
21(140):1–67.Christoph Schuhmann, Romain Beaumont, Richard
Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti,
Theo Coombes, Aarush Katta, Clayton Mullis,
Mitchell Wortsman, et al. 2022. Laion-5b: An open
large-scale dataset for training next generation image-
text models. Advances in Neural Information Pro-
cessing Systems , 35:25278–25294.
Neha Sengupta, Sunil Kumar Sahu, Bokang Jia,
Satheesh Katipomu, Haonan Li, Fajri Koto, William
Marshall, Gurpreet Gosal, Cynthia Liu, Zhiming
Chen, Osama Mohammed Afzal, Samta Kamboj,
Onkar Pandit, Rahul Pal, Lalit Pradhan, Zain Muham-
mad Mujahid, Massa Baali, Xudong Han, Son-
dos Mahmoud Bsharat, Alham Fikri Aji, Zhiqiang
Shen, Zhengzhong Liu, Natalia Vassilieva, Joel Hes-
tness, Andy Hock, Andrew Feldman, Jonathan Lee,
Andrew Jackson, Hector Xuguang Ren, Preslav
Nakov, Timothy Baldwin, and Eric Xing. 2023.
Jais and jais-chat: Arabic-centric foundation and
instruction-tuned open generative large language
models. Preprint , arXiv:2308.16149.
Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann
Dubois, Xuechen Li, Carlos Guestrin, Percy Liang,
and Tatsunori B. Hashimoto. 2023. Stanford alpaca:
An instruction-following llama model. https://
github.com/tatsu-lab/stanford alpaca .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timoth ´ee Lacroix,
Baptiste Rozi `ere, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Junke Wang, Lingchen Meng, Zejia Weng, Bo He, Zux-
uan Wu, and Yu-Gang Jiang. 2023. To see is to be-
lieve: Prompting gpt-4v for better visual instruction
tuning. arXiv preprint arXiv:2311.07574 .
Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang,
Rangan Majumder, and Furu Wei. 2024. Multilingual
e5 text embeddings: A technical report. Preprint ,
arXiv:2402.05672.
Susan Zhang, Stephen Roller, Naman Goyal, Mikel
Artetxe, Moya Chen, Shuohui Chen, Christopher De-
wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022.
Opt: Open pre-trained transformer language models.
arXiv preprint arXiv:2205.01068 .
Wenhao Zhu, Hongyi Liu, Qingxiu Dong, Jingjing Xu,
Shujian Huang, Lingpeng Kong, Jiajun Chen, and
Lei Li. 2023. Multilingual machine translation with
large language models: Empirical results and analy-
sis.Preprint , arXiv:2304.04675.
A Appendices
We organize content here as follows:
• Translation and Filtering Details (A.1)
• Dialect Translation Examples (A.2)
• | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | Section not found | model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide
qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the | Section not found | Section not found | Section not found | Section not found | Section not found | comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights.
Limitations
We identify a number of limitations for our work,
as follows:
•Representation of Arabic Culture : Vision
models, LLMs, and datasets used in build-
ing MLLMs inadequately represent Arabic
figures, places, and culture. As shown in Fig-
ure 10, Dallah struggles with recognizing Ara-
bic figures, unlike those from the USA. This
highlights the need for more diverse cultural
datasets.
•Hallucination Control :Dallah , like many
LLMs, is prone to hallucinations, generating
inaccurate information. Advanced techniquesand more robust datasets are needed to miti-
gate this issue and ensure reliability.
•Dialect Variation and Mixing : The model
sometimes mixes similar dialects, such as
Yemeni and Saudi, and struggles with di-
alects close to MSA. This can be improved
with more extensive data collection and fine-
tuning.
•Arabic Text Recognition in Images :Dal-
lahcannot effectively recognize Arabic text
within images due to the lack of annotated
datasets. Developing such datasets is essential
to enhance the model’s multimodal capabili-
ties.
Ethics Statement
Energy Efficiency. OurDallah models, like many
large MLLMs, require significant pre-training time
and are not energy-efficient. We acknowledge this
critical issue and support continued research to-
wards developing energy-efficient models.
Data. Our pre-training datasets are translated from
publicly available English data, encompassing di-
verse genres, communities, and varieties. Our Dal-
lahmodels demonstrate potential in applications
involving several Arabic varieties, serving broad
populations.
Human Annotation. The human annotators in-
volved in this project are Arabic native speakers
and well-educated individuals with PhD degrees
and extensive NLP experience. No Institutional
Review Board (IRB) review or approval was re-
quired for this project since we only used publicly
available data, which does not require access to any
social networking account or password.
Applications. While Dallah , like many MLLMs,
can be misused. It also holds promise for bene-
ficial applications in education, health, and more.
Responsible deployment and use are crucial to max-
imizing its positive impact. It would also help keep
Arabic varieties in use in written form in the digital
age.
Acknowledgments
We acknowledge support from Canada Research
Chairs (CRC), the Natural Sciences and Engineer-
ing Research Council of Canada (NSERC; RGPIN-
2018-04267), the Social Sciences and Humanities
Research Council of Canada (SSHRC; 435-2018-
0576; 895-2020-1004; 895-2021-1008), Canadian
Foundation for Innovation (CFI; 37771), Digital
Research Alliance of Canada,6and UBC ARC-
Sockeye.
References
Marah Abdin, Sam Ade Jacobs, Ammar Ahmad Awan,
Jyoti Aneja, Ahmed Awadallah, Hany Awadalla,
Nguyen Bach, Amit Bahree, Arash Bakhtiari, Harki-
rat Behl, et al. 2024. Phi-3 technical report: A highly
capable language model locally on your phone. arXiv
preprint arXiv:2404.14219 .
Josh Achiam, Steven Adler, Sandhini Agarwal, Lama
Ahmad, Ilge Akkaya, Florencia Leoni Aleman,
Diogo Almeida, Janko Altenschmidt, Sam Altman,
Shyamal Anadkat, et al. 2023. Gpt-4 technical report.
arXiv preprint arXiv:2303.08774 .
Azimjon Ahmedov and Xabibullayeva Shaxrizoda.
2024. The english effect. Ta’limning zamonaviy
transformatsiyasi , 7(3):18–23.
Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc,
Antoine Miech, Iain Barr, Yana Hasson, Karel
Lenc, Arthur Mensch, Katherine Millican, Malcolm
Reynolds, et al. 2022. Flamingo: a visual language
model for few-shot learning. Advances in neural
information processing systems , 35:23716–23736.
Fakhraddin Alwajih, El Moatez Billah Nagoudi, Gagan
Bhatia, Abdelrahman Mohamed, and Muhammad
Abdul-Mageed. 2024. Peacock: A family of arabic
multimodal large language models and benchmarks.
Preprint , arXiv:2403.01031.
Richard Barnet and John Cavanagh. 2014. Homoge-
nization of global culture. In The case against the
global economy , pages 169–174. Routledge.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind
Neelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, et al. 2020. Language models are few-shot
learners. Advances in neural information processing
systems , 33:1877–1901.
Guiming Hardy Chen, Shunian Chen, Ruifei Zhang,
Junying Chen, Xiangbo Wu, Zhiyi Zhang, Zhihong
Chen, Jianquan Li, Xiang Wan, and Benyou Wang.
2024. Allava: Harnessing gpt4v-synthesized data
for a lite vision-language model. arXiv preprint
arXiv:2402.11684 .
Lin Chen, Jisong Li, Xiaoyi Dong, Pan Zhang, Con-
ghui He, Jiaqi Wang, Feng Zhao, and Dahua
Lin. 2023. Sharegpt4v: Improving large multi-
modal models with better captions. arXiv preprint
arXiv:2311.12793 .
Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng,
Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan
6https://alliancecan.caZhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion
Stoica, and Eric P. Xing. 2023. Vicuna: An open-
source chatbot impressing gpt-4 with 90%* chatgpt
quality.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. Bert: Pre-training of deep
bidirectional transformers for language understand-
ing.arXiv preprint arXiv:1810.04805 .
Zakaria Fahmi and Dacota Liska. 2024. Promoting ara-
bic as a foreign language in the middle east and north
africa: Host-grounded study abroad discourses. Fron-
tiers: The Interdisciplinary Journal of Study Abroad ,
36(1):384–417.
Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang,
and Weizhu Chen. 2021. Lora: Low-rank adap-
tation of large language models. arXiv preprint
arXiv:2106.09685 .
Huang Huang, Fei Yu, Jianqing Zhu, Xuening Sun, Hao
Cheng, Dingjie Song, Zhihong Chen, Abdulmohsen
Alharthi, Bang An, Ziche Liu, Zhiyi Zhang, Juny-
ing Chen, Jianquan Li, Benyou Wang, Lian Zhang,
Ruoyu Sun, Xiang Wan, Haizhou Li, and Jinchao Xu.
2023. Acegpt, localizing large language models in
arabic. Preprint , arXiv:2309.12053.
Mojan Javaheripi, S ´ebastien Bubeck, Marah Abdin,
Jyoti Aneja, Caio C ´esar Teodoro Mendes, Weizhu
Chen, Allie Del Giorno, Ronen Eldan, Sivakanth
Gopi, Suriya Gunasekar, Piero Kauffmann, Yin Tat
Lee, Yuanzhi Li, Anh Nguyen, Gustavo de Rosa,
Olli Saarikivi, Adil Salim, Shital Shah, Michael San-
tacroce, Harkirat Singh Behl, Adam Taumann Kalai,
Xin Wang, Rachel Ward, Philipp Witte, Cyril Zhang,
and Yi Zhang. 2023. Phi-2: The surprising power of
small language models. Microsoft Research Blog.
Albert Q Jiang, Alexandre Sablayrolles, Arthur Men-
sch, Chris Bamford, Devendra Singh Chaplot, Diego
de las Casas, Florian Bressand, Gianna Lengyel, Guil-
laume Lample, Lucile Saulnier, et al. 2023. Mistral
7b.arXiv preprint arXiv:2310.06825 .
Albert Q Jiang, Alexandre Sablayrolles, Antoine
Roux, Arthur Mensch, Blanche Savary, Chris Bam-
ford, Devendra Singh Chaplot, Diego de las Casas,
Emma Bou Hanna, Florian Bressand, et al. 2024.
Mixtral of experts. arXiv preprint arXiv:2401.04088 .
Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi.
2023. Blip-2: Bootstrapping language-image pre-
training with frozen image encoders and large lan-
guage models. In International conference on ma-
chine learning , pages 19730–19742. PMLR.
Tsung-Yi Lin, Michael Maire, Serge Belongie, James
Hays, Pietro Perona, Deva Ramanan, Piotr Doll ´ar,
and C Lawrence Zitnick. 2014. Microsoft coco:
Common objects in context. In Computer Vision–
ECCV 2014: 13th European Conference, Zurich,
Switzerland, September 6-12, 2014, Proceedings,
Part V 13 , pages 740–755. Springer.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2023a. Improved baselines with visual instruc-
tion tuning.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2024. Improved baselines with visual instruc-
tion tuning. In Proceedings of the IEEE/CVF Con-
ference on Computer Vision and Pattern Recognition ,
pages 26296–26306.
Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae
Lee. 2023b. Visual instruction tuning. In NeurIPS .
Muhammad Maaz, Hanoona Rasheed, Abdelrahman
Shaker, Salman Khan, Hisham Cholakal, Rao M. An-
wer, Tim Baldwin, Michael Felsberg, and Fahad S.
Khan. 2024. Palo: A polyglot large multimodal
model for 5b people. Preprint , arXiv:2402.14818.
Rui Meng, Ye Liu, Shafiq Rayhan Joty, Caiming
Xiong, Yingbo Zhou, and Semih Yavuz. 2024. Sfr-
embedding-mistral:enhance text retrieval with trans-
fer learning.
Abdelrahman Mohamed, Fakhraddin Alwajih,
El Moatez Billah Nagoudi, Alcides Inciarte, and
Muhammad Abdul-Mageed. 2023. Violet: A
vision-language model for Arabic image captioning
with gemini decoder. In Proceedings of ArabicNLP
2023 , pages 1–11, Singapore (Hybrid). Association
for Computational Linguistics.
Niklas Muennighoff, Nouamane Tazi, Lo ¨ıc Magne, and
Nils Reimers. 2022. Mteb: Massive text embedding
benchmark. arXiv preprint arXiv:2210.07316 .
El Moatez Billah Nagoudi, Muhammad Abdul-Mageed,
AbdelRahim Elmadany, Alcides Alcoba Inciarte, and
Md Tawkat Islam Khondaker. 2023. Jasmine: Ara-
bic gpt models for few-shot learning. Preprint ,
arXiv:2212.10755.
OpenAI. 2023. Chatgpt. AI language model. Accessed:
2024-04-30.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya
Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sas-
try, Amanda Askell, Pamela Mishkin, Jack Clark,
et al. 2021. Learning transferable visual models from
natural language supervision. In International confer-
ence on machine learning , pages 8748–8763. PMLR.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan,
Dario Amodei, Ilya Sutskever, et al. 2019. Language
models are unsupervised multitask learners. OpenAI
blog, 1(8):9.
Colin Raffel, Noam Shazeer, Adam Roberts, Katherine
Lee, Sharan Narang, Michael Matena, Yanqi Zhou,
Wei Li, and Peter J Liu. 2020. Exploring the lim-
its of transfer learning with a unified text-to-text
transformer. Journal of machine learning research ,
21(140):1–67.Christoph Schuhmann, Romain Beaumont, Richard
Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti,
Theo Coombes, Aarush Katta, Clayton Mullis,
Mitchell Wortsman, et al. 2022. Laion-5b: An open
large-scale dataset for training next generation image-
text models. Advances in Neural Information Pro-
cessing Systems , 35:25278–25294.
Neha Sengupta, Sunil Kumar Sahu, Bokang Jia,
Satheesh Katipomu, Haonan Li, Fajri Koto, William
Marshall, Gurpreet Gosal, Cynthia Liu, Zhiming
Chen, Osama Mohammed Afzal, Samta Kamboj,
Onkar Pandit, Rahul Pal, Lalit Pradhan, Zain Muham-
mad Mujahid, Massa Baali, Xudong Han, Son-
dos Mahmoud Bsharat, Alham Fikri Aji, Zhiqiang
Shen, Zhengzhong Liu, Natalia Vassilieva, Joel Hes-
tness, Andy Hock, Andrew Feldman, Jonathan Lee,
Andrew Jackson, Hector Xuguang Ren, Preslav
Nakov, Timothy Baldwin, and Eric Xing. 2023.
Jais and jais-chat: Arabic-centric foundation and
instruction-tuned open generative large language
models. Preprint , arXiv:2308.16149.
Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann
Dubois, Xuechen Li, Carlos Guestrin, Percy Liang,
and Tatsunori B. Hashimoto. 2023. Stanford alpaca:
An instruction-following llama model. https://
github.com/tatsu-lab/stanford alpaca .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timoth ´ee Lacroix,
Baptiste Rozi `ere, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Junke Wang, Lingchen Meng, Zejia Weng, Bo He, Zux-
uan Wu, and Yu-Gang Jiang. 2023. To see is to be-
lieve: Prompting gpt-4v for better visual instruction
tuning. arXiv preprint arXiv:2311.07574 .
Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang,
Rangan Majumder, and Furu Wei. 2024. Multilingual
e5 text embeddings: A technical report. Preprint ,
arXiv:2402.05672.
Susan Zhang, Stephen Roller, Naman Goyal, Mikel
Artetxe, Moya Chen, Shuohui Chen, Christopher De-
wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022.
Opt: Open pre-trained transformer language models.
arXiv preprint arXiv:2205.01068 .
Wenhao Zhu, Hongyi Liu, Qingxiu Dong, Jingjing Xu,
Shujian Huang, Lingpeng Kong, Jiajun Chen, and
Lei Li. 2023. Multilingual machine translation with
large language models: Empirical results and analy-
sis.Preprint , arXiv:2304.04675.
A Appendices
We organize content here as follows:
• Translation and Filtering Details (A.1)
• Dialect Translation Examples (A.2)
• | Section not found | implementation details and the bench-
marks used for evaluation. Section 5 presents our | experimental results, including both quantitative
and qualitative analyses. We conclude in Section 6
with a discussion of our findings and future work.2 Related Work
2.1 Large Language Models
Recent progress in NLP has been driven by ad-
vances in LLMs, starting with the foundational
Transformer model (Vaswani et al., 2017). This
innovation paved the way for language models like
the encoder-based BERT (Devlin et al., 2018), and
the decoder-based Generative Pre-trained Trans-
former (GPT) (Brown et al., 2020), as well as
encoder-decoder-based models like T5 (Raffel
et al., 2020), which have significantly improved
linguistic understanding and performance in com-
plex language processing tasks. The develop-
ment of models such as OPT (Zhang et al., 2022),
LLaMA (Touvron et al., 2023a), LLaMA-2 (Tou-
vron et al., 2023b), GPT-2 (Radford et al., 2019),
GPT-3 (Brown et al., 2020), GPT-4 (Achiam
et al., 2023), and ChatGPT (OpenAI, 2023) Mis-
tral (Jiang et al., 2023), Mixtral (Jiang et al., 2024),
Phi-2 (Javaheripi et al., 2023), Phi-3 (Abdin et al.,
2024), and instruction-tuned variants of LLaMA-2
like Alpaca (Taori et al., 2023) and Vicuna (Chiang
et al., 2023), have demonstrated the rapid evolution
of the field. These models benefit from extensive
training on large datasets and tailored instruction
sets, enhancing their effectiveness.
Arabic LLMs Building on the global momen-
tum, the scope of LLMs has extended into Arabic
language processing. The introduction of Jasmine
(Nagoudi et al., 2023) marked a significant mile-
stone, followed by AceGPT (Huang et al., 2023)
and Jais (Sengupta et al., 2023), which have en-
hanced Arabic conversational AI. Recently, AraL-
LaMA (Alwajih et al., 2024) set a new standard
with its proficiency in the Egyptian Arabic dialect,
showcasing the flexibility of LLMs in handling
linguistically diverse data.
2.2 Multimodal Large Language Models
The integration of computer vision and natural lan-
guage processing has given rise to Visual Language
Models (VLMs). These models merge visual and
linguistic data, enhancing tasks that require visual
perception and language abilities. Models like
CLIP (Radford et al., 2021) bridge the gap between
visual recognition and language tasks, demonstrat-
ing the effectiveness of cross-modal applications.
Recent advancements show that LLMs improve
VLMs. Innovations such as Flamingo (Alayrac
et al., 2022), Blip-2 (Li et al., 2023), and
LLaV A (Liu et al., 2023b) have leveraged large
image-text pair datasets, enhancing cross-modal
coordination and learning efficiency. These mod-
els also employ specialized architectural features
for better integration. For instance, Flamingo
utilizes a perceiver resampler to integrate visual
data, and Blip-2 introduces a Q-Former (Li et al.,
2023) for aligning visual and language modalities.
LLaV A (Liu et al., 2023b) adjusts a linear pro-
jection layer to synchronize vision and language
modalities. Meanwhile, LLaV A1.6 (Liu et al.,
2023a) incorporates extensive instruction tuning
and a high-resolution vision encoder, achieving
outstanding results across multiple benchmarks.
Arabic Multimodal LLMs In Arabic NLP, Pea-
cock (Alwajih et al., 2024) represents the first work
in Arabic-centric MLLM capable of handling Ara-
bic multimodal interaction effectively. Addition-
ally, the multilingual PALO (Maaz et al., 2024)
has demonstrated the ability to process and inte-
grate multiple languages, including Arabic, into
multimodal contexts.
2.3 Multimodal Instruction Tuning Datasets
Development of MLLMs typically involves two
phases. The first phase focuses on aligning vi-
sual and linguistic features, utilizing datasets such
as COCO (Lin et al., 2014), LLaV A-Pretrain (Liu
et al., 2023b), and Laion (Schuhmann et al., 2022).
The subsequent visual instruction fine-tuning phase
enhances the models’ capabilities to follow com-
plex multimodal instructions. This phase often
involves transforming existing datasets into more
conversationally relevant formats using advanced
LLMs such as GPT-4, as seen in models like
LLaV A-Instruct (Liu et al., 2023b) and SVIT (Liu
et al., 2024). Recent works utilized GPT-4V (Ope-
nAI, 2023) to generate new captions and question-
answers, such as in ShareGPT4V (Chen et al.,
2023), LVIS-instruct4v (Wang et al., 2023) and
Allava (Chen et al., 2024). Arabic MLLMs uti-
lized translated versions of LLaV A-Instruct (Alwa-
jih et al., 2024; Maaz et al., 2024) using different
tools for translation.
3 Methodology
3.1 Arabic Dataset Translation and Filtering
In the first step, we aimed to build an Arabic
MLLM using Arabic datasets. A major obstacle
facing Arabic MLLMs is the lack of resources.This lack is largely due to the challenges of sourc-
ing relevant Arabic image-text pairs on a large
scale. To bridge this resource gap, we have imple-
mented a careful translate-and-filter pipeline con-
sisting of a translation stage and a filtering stage
inspired by (Mohamed et al., 2023; Alwajih et al.,
2024). This pipeline converts publicly available,
English-centric image-text and visual instruction
datasets into Arabic while maintaining data quality
and preventing error propagation due to translation.
We utilize the latest version of the Google Trans-
late API (Google Cloud) for the translation stage
which is the best translation method as shown by
(Zhu et al., 2023). We also conducted back trans-
lation as required by the subsequent filtering stage.
During the filtering stage , we ensure the quality
of our translations by employing a sentence em-
bedding model (Meng et al., 2024; Wang et al.,
2024). We assess the quality by calculating the
similarity of embedding between the original and
back-translated sentences for both question and an-
swer pairs, retaining only those translations that
meet our quality standards. Essentially, we keep
examples with questions and answers above a pre-
defined threshold, which we have empirically set
at 80%. Figure 3 illustrates the translation and
filtering process. Unlike the methods used in (Mo-
hamed et al., 2023; Alwajih et al., 2024), we em-
ploy an English sentence embedding model based
on Mistral-7b (Wang et al., 2024) to calculate the
similarities. This last model is more powerful than
embedding models used in Mohamed et al. (2023);
Alwajih et al. (2024) as shown by MTEB leader-
board (Muennighoff et al., 2022). Refer to Figure 2
for examples illustrating our pipeline’s effective-
ness.
3.2 Dialectal Arabic Dataset Construction
Due to the absence of Arabic dialectal data tailored
for vision tasks, we randomly select six subsets
from our translated LLaV A-instruct 150k dataset.
We aim to ensure that each subset included diverse
content types, such as conversations, complex rea-
soning, and detailed descriptions, from the LLaV A-
instruct dataset. Our goal is to capture the dialects
of Egypt, Mauritania, Morocco, Palestine, Saudi
Arabia, and Yemen. These dialects represent a
broad spectrum of Arabic dialects.
These subsets are then assigned to native profes-
sional translators from the aforementioned coun-
tries in order to translate them from MSA into their
respective dialects. Table 1 displays the number of
What ar e the surf ers holding?Original
ﻣﺎذا ﻳﺤﻤﻞ ﻣﺘﺼﻔﺤﻲ؟Arabic Translation
What does m y browser load?English Back Translation
0.513672 Similarity
The jumper in the image is a
snowboar der.اﻟﻄﺎﺋﺮ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ھﻮ ﻣﺘﺰﻟﺞ ﻋﻠﻰ
اﻟﺠﻠﯿﺪ.The bir d in the photo is an ice skater . 0.549805
Where is the surf er located? أﻳﻦ ﻳﻘﻊ ﻣﻘﺮ ﺳﯿﺮﻓﺮ؟ Where is S erver's headquarters? 0.580566
What is the condi tion of the str eet wher e
the stop sign is located?ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?1.00000
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻣﺎ ھﻲ ﺣﺎﻟﺔ اﻟﺸﺎرع اﻟﺬي ﺗﻮﺟﺪ ﻓﯿﻪ إﺷﺎرة
اﻟﺘﻮﻗﻒ؟What is the condi tion of the str eet wher e
the stop sign is located?0.900391
The ki tchen counter is clut tered wi th
various i tems, contributing to the messy
appear ance of the ki tchen.ﻧﻌﻢ، ﺗﻮﺟﺪ ﺗﻌﻠﯿﻘﺎت ﻣﻌﻠﻘﺔ ﻋﻠﻰ اﻟﮫﺎﺗﻒ اﻟﻘﺎﺑﻞ
ﻟﻠﻄﻲ، ﻣﻤﺎ ﻳﻀﯿﻒ ﻟﻤﺴﺔ ﻣﻦ اﻟﺘﺨﺼﯿﺺ
واﻷﻧﺎﻗﺔ إﻟﻰ اﻟﺠﮫﺎز.Yes, ther e are suspensions on the f oldable
phone, adding a touch of personal ization
and elegance to the device.0.800293Figure 2: This figure illustrates the translation and filtering process used in constructing the Arabic dataset for
Dallah . The red rows represent examples that were removed due to low similarity scores between the original
English text and the back-translated English text. The green rows show the retained examples that met the similarity
threshold, ensuring high-quality translations for effective model training.
عA
عACosine Similarity
Raw DataEmbedding Model
Embedding Model
Clean DataTranslation to Arabic
Original EnglishBack Translated English
Threshold filterTranslation back to English
ArabicEnglish
Figure 3: Illustration of the translation and filtering
process for constructing high-quality Arabic multi-
modal datasets. Examples illustrating the results of
this pipeline are in Figure 2.
samples per country, while Figure 1 illustrates the
targeted countries on the map. Refer to A.2 for
more details.
Stage Source #Sample
Pretraining LLaV A-Pretrain LCS (Arabic+English) 800k
Inst. TuningLLaV A-Instruct English 150k
LLaV A-Instruct Arabic 139k
Dialectal TuningEgypt 738
Mauritania 495
Morocco 505
Palestine 853
Saudi Arabia 784
Yemen 604
Total 1.1 M
Table 1: Number of samples used for each stage in the
training of Dallah .3.3 Architecture
The Dallah model follows the structure of
LLaV A1.5 (Liu et al., 2023a) and comprises three
key elements:
1.Vision Encoder: The vision encoder ( Vφ) em-
ploys the CLIP-Large model (Radford et al.,
2021) to process input images ( X) into 576
visual tokens at a resolution of 336x336 with
a patch size of 14, producing a sequence of
patch features V={vj∈Rdx}M
i=j.
2.Projector: A connector ( Pϕ), designed as
a two-layer multi-layer perceptron (MLP),
maps the visual patch sequences {vj}M
j=1to
the text embedding space {hj}M
j=1, allow-
ing for effective integration between the pre-
trained LLM and the vision encoder.
3.Language Model (LLM): The Arabic LLM
(Fθ), based on AraLLaMA (Alwajih et al.,
2024)1processes sequences of text embed-
dings{hi}N−1
i=0in the d-dimensional space,
outputting corresponding next predictions
{hi}N
i=1. A tokenizer and embedding module
maps text sequences {yi}N−1
i=0to the embed-
ding space and back to output text sequences
{yi}N
i=1.
This structure equips the model to handle various
multimodal understanding tasks, taking an image
and instruction text sequence as input and generat-
ing a text sequence as output. Figure 4 illustrates
Dallah architecture.
1AraLLaMA is an enhanced version of LLaMA-2 (Tou-
vron et al., 2023a).
Embedding
SpaceLanguage Model (AraLLaMA 7B)
Vision Encoder
(CLIP ViT-L/336x336px)Vision Language Connector
(MLP) Tokenizer & Embedding
: ﻣﺎ اﻟﺬي ﻳﻤﻜﻦ اﺳﺘﻨﺘﺎﺟﻪ USER
ﻣﻦ اﻟﺼﻮرة؟
Model ResponseFigure 4: Dallah model architecture, showcasing the in-
tegration of the vision encoder, projector, and language
model.
3.4 Training
Training of Dallah consists of three stages: (i) pre-
training using data LLaV A-Pretrain (MAS Arabic
and English), (ii) visual instruction supervised fine-
tuning using LLaV A-Instruct (Arabic MSA and En-
glish), and (iii) further visual instruction supervised
fine-tuning using dialectal data. Table 1 details the
datasets used in each stage. Training data com-
prises pairs of images and text (X, Y ), with the
text sequence Yformatted as a single-turn in the
pre-training phase and multi-turn conversation in
the visual Instruction Supervised Fine-tuning stage.
Y= (Y1
q, Y1
a, . . . , YT
q, YT
a). Here, Trepresents
the number of conversation turns, Yt
qthe user’s
prompt, and Yt
athe model’s response.
3.4.1 Pre-training
During this phase, the goal is to enhance the align-
ment between the vision and text data within the
embedding space. For this, image-caption style
data(X, Y a)is extracted from the conversation,
where Xis the image and Yais a corresponding
text description. The probability of generating Ya
given the image is calculated as:
p(Ya|X) =NaY
i=1Fθ(yi|Pϕ◦Vφ(X)),
where Nais the length of Ya. The training objective
is to maximize the log-likelihood of Yaautoregres-
🔥
LoRA
ViTProjection 🔥LLM
ImageViTProjection 🔥LLM
ImageInstruction
InstructionOutput text Output text🔥 Pre-trained and frozen Train from scratch
Pre-training Fine-tuningFigure 5: Training schema for Dallah , detailing the pre-
training and visual instruction supervised fine-tuning
phases.
sively:
max
ϕNaX
i=1logFθ(yi|Pϕ◦Vφ(X)),
This framework permits the adjustment of learnable
parameters of projector layers during pre-training.
LLM and vision encoder learnable parameters are
frozen during pre-training, as shown in Figure 5.
3.4.2 Visual Instruction Supervised
Fine-tuning
The full image-text pairs (X, Y )in their multi-
turn conversation format are used for fine-tuning.
The set of tokens corresponding to the model’s re-
sponses is denoted as A={y|y∈Yt
a,for any t=
1, . . . , T }. The training objective is to maximize
the log-likelihood of the model’s responses autore-
gressively:
max
´θ,ϕNX
i=1I(yi∈A) logFθ(yi|Pϕ◦Vφ(X)),
where Nis the total number of tokens in Y,´θis
a subset of θ, and I(yi∈A)is1ifyibelongs to
A, and 0otherwise. Training the projector layers’
learnable parameters while the vision encoder is
kept frozen during this phase. For LLM, we utilize
LoRA (Hu et al., 2021) to train the LLM. Figure 5
visualizes both pre-training and visual instruction
supervised fine-tuning stages.
4 Experiments
4.1 Implementation Details
Model Configurations. In this work, we develop
theDallah model based on the LLaV A1.5 frame-
work. Specifically, we employ the CLIP-ViT-L/14
as the visual encoder with a standard resolution of
336×336. We also use AraLLaMA, a language
model tailored specifically for Arabic, and employ
a two-layer MLP as the interface to connect the
visual encoder with the LLM.
For the construction of Dallah , a three-stages
training process is implemented. Initially, we estab-
lish a base MSA MLLM in two stages pretraining
and MSA fine-tuning, followed by an adaptation
stage for Arabic dialects. The following are details
of these different stages:
Stage 1: Pre-training stage. During this initial
stage, training is conducted for a single epoch only
on the projector as described in 3.4.1 using the
translated LCS-558 (Liu et al., 2023b) dataset. This
dataset includes data filtered for Arabic and 300K
samples of English samples. The optimization is
done using the AdamW optimizer with a learning
rate of 1×10−3, combined with a cosine learning
rate schedule. The overall batch size is maintained
at 32. This phase required approximately 28 hours
of training on a single A100 GPU.
Stage 2: Instruction-tuning stage. In this satge,
the visual encoder is frozen, tuning is applied to the
visual projector, and the LLM is fine-tuned using
LoRA as described in 3.4.2. Here we employ the
150K LLaV A-Instruct dataset in English alongside
a translated and filtered Arabic version. The learn-
ing rate is set to 2×10−4with a batch size of 8,
maintaining the same settings as in the first stage.
This training phase took around 58 hours using a
single A100 GPU.
Stage 3: Dialectal instruction-tuning stage.
This stage is similar to stage 2, but is focused on di-
alectal data for six different Arabic dialects and par-
allel data for MSA. The settings remain the same
as in the second stage with learning rate 2×10−5,
over five epochs. This training phase took approxi-
mately 2 hours using a single A100 GPU. Table 1
details the data used in the aforementioned stages.
4.2 Benchmarks
We evaluate our model using two benchmarks:
LLaV A-Bench for MSA evaluation and compar-
ison with counterpart Arabic MLLMs and Dallah-
Bench to assess the model’s capabilities in six Ara-
bic dialects.
4.2.1 LLaV A-Bench for MSA
The Ara-LLaV A-Bench is the Arabic version of
the LLaV A-Bench, translated using Google API
GPT-4 Command R + GPT-4-Turbo Human
Evaluator020406080100Average Score (%)82.86
69.35
64.25
63.78
86.96
78.07
70.98
73.67
89.74
79.43
72.90
74.56
Peacock PALO DallahFigure 6: Average score comparison by evaluator and
model.
and reviewed by Arabic native annotator. The
LLaV A-Bench includes 30 images selected from
the COCO2014 validation dataset. Each image is
accompanied by three types of questions: conver-
sion, detailed descriptions, and complex reasoning,
amounting to 90 questions.
4.2.2 Dallah-Bench for Dialects
We select a subset of 20 questions from the
Henna (Alwajih et al., 2024) dataset to assess the
model’s response to dialects, naming it Dallah-
Bench . We task native professionals from each
dialect to translate these from MSA into the afore-
mentioned six Arabic dialects.
5 Results
5.1 LLaV A-Bench for MSA
Evaluator Model Arch. CC DD CR Avg
GPT-4Peacock
85.66 80.25 82.52 82.86
PALO
87.30 86.31 87.24 86.96
Dallah
89.64 90.79 88.80 89.74
Command R +Peacock
74.49 66.54 66.78 69.35
PALO
76.61 75.32 82.15 78.07
Dallah
75.37 77.1 85.78 79.43
GPT-4-TurboPeacock
67.35 62.5 62.86 64.25
PALO
69.2 70.02 73.76 70.98
Dallah
71.47 70.75 76.52 72.9
HumanPeacock
68.56 61.00 61.78 63.78
PALO
75.11 67.78 78.11 73.67
Dallah
78.56 69.44 75.67 74.56
Table 2: Evaluation of Arabic LLaV A-Bench in MSA
using four different evaluators: GPT-4, GPT-4-Turbo,
Cohere Command R+, and Human. We consider Human
Evaluation to be the gold standard. CC: Conversations,
DD: Details, CR: Complex Reasoning.
We evaluate Dallah using the LLaV A-Bench
benchmark described in 4.2.1, specifically de-
signed for multimodal models. We compare Dallah
against two baselines: Peacock, an Arabic MLLM
based on the InstructBlip architecture integrated
with AraLLaMA, an LLM based on LLaMA-2; and
PALO, a multilingual MLLM based on the LLaV A
architecture integrated with Vicuna, an LLM based
on LLaMA-2. PALO supports Arabic, along with
nine other languages. We utilize both model-based
evaluation and human evaluation. We describe each
of these next.
Model Evaluation. We follow the original
methodology of LLaV A-Bench (Liu et al., 2023b)
by calling the APIs of three different models: GPT-
4, Cohere Command R+2, and GPT-4-Turbo. We
slightly modify the prompts to accommodate Ara-
bic instead of English.
Human Evaluation. We conduct a human eval-
uation of three models using LLaV A-Bench. We
present three well-educated annotators with images
and questions-answer pairs generated by Dallah
and two other baseline models, Peacock and PALO.
To ensure integrity, the names of the models are hid-
den throughout the evaluation process. Annotators
are asked to rate the models’ responses on a scale
from 1 to 10, based on correctness3,helpfulness4
and question-answer consistency5.
Figure 6 presents the average scores (%) of the
models Peacock, PALO, and Dallah as evaluated
by four different evaluators: GPT-4, Command R+,
GPT-4-Turbo, and Human.
5.1.1 Analysis
We report the main results in Table 2. In the GPT-
4 evaluation, the scale of scores is higher than in
other evaluations. The overall scores for Cohere
Command R+ and GPT-4-Turbo are close to those
of the human evaluation, with GPT-4-Turbo being
the closest numerically to human evaluation.
From Table 2, it is observed that the Dallah
model outperforms the baseline models in most
dimensions of the LLaVa-Bench across all evalua-
tion methods. Peacock generally showed the lowest
performance, which could be attributed to multi-
ple factors, including the scale of training data and
2https://docs.cohere.com/docs/command-r-plus
3Correctness : The accuracy and factual correctness of the
model’s response to the given question.
4Helpfulness : The degree to which the model’s response
provides useful and informative assistance to the user.
5Consistency : The coherence and logical flow within the
model’s responses, ensuring they are free from contradictions.the model architecture, where the best model in
the Peacock suite is based on InstructBlip and was
trained with frozen Q-former components.
Dallah and PALO show close results across all
evaluations, with Dallah having a slight advantage.
Dallah surpasses PALO by an average of 1.74%
across all evaluations. Both models share the same
LLaV A architecture but differ in their LLMs; Dal-
lahuses AraLLaMA, an Arabic LLM, giving it
an advantage, whereas PALO utilizes Vicuna, a
multilingual LLM based on LLaMa-2 (Touvron
et al., 2023a). The training data are almost identi-
cal, though Dallah ’s data went through a careful
filtering method to ensure quality. Also, Dallah is
trained on high-quality human-translated dialectal
data.
These results demonstrate Dallah ’s effectiveness
in MSA, exhibiting strong reasoning capabilities
and substantial knowledge.
5.2 Dallah-Bench for Dialects
Evalutator Command R+ GPT-4-Turbo Human
Country DA CA DA CA DA CA
Egypt 7.82 8.04 7.00 5.96 6.59 7.22
Mauritania 7.11 7.86 3.59 5.04 4.41 6.36
Morocco 8.82 8.59 7.54 6.68 6.50 5.27
Palestine 8.00 8.32 5.32 6.36 8.73 7.68
Saudi 8.50 8.91 5.77 6.46 7.50 8.27
Yemen 8.36 9.00 5.04 4.77 7.49 7.73
Average 8.10 8.45 5.71 5.88 6.87 7.09
Table 3: Evaluation of Dallah model on dialect bench
using three evaluators: Cohere Command R+, GPT4-
Turbo, and Humans from respective countries. DA:
Dialect Authenticity, CA: Content Accuracy. Prompts
for the evaluation can be found in Figure 7.
We assess Dallah ’s performance in dialects us-
ingDallah-Bench described in 4.2.2. We employ
two types of evaluations: human evaluation and
model-based evaluation.
Human Evaluation. To evaluate the model re-
sponses related to dialect questions about the im-
age, we ask native speakers from each respective
country to score the models on a scale from 1 to 10
using the following criteria:
•Context Accuracy Score : This criterion fo-
cuses on the accuracy of the model’s response
in relation to the question posed, irrespective
of the dialect or language used. It assesses
how well the response addresses the content
and context of the question.
•Dialect Authenticity Score : This criterion
assesses the authenticity of the dialect used
in the response, independent of the content’s
accuracy. It evaluates how authentically the re-
sponse represents the specific dialect in ques-
tion.
Model Evaluation. We craft a prompt to assess
Dallah ’s responses and subsequently call the APIs
of two different models, Cohere Command R+ and
GPT-4 Turbo. In the prompt, we request that the
evaluator models rate Dallah ’s response on a scale
from 1 to 10 based on the Dialect Authenticity
Score and Content Accuracy Score. We utilize
GPT4V to extract a detailed description of the
image content and include this description in the
prompt to give context to the model. Figure 7 il-
lustrates the prompt used to instruct the models for
evaluation.
5.2.1 Model vs. Human Evaluation
In our analysis in Table 3, we compare the perfor-
mance of Dallah based on two evaluators, Cohere
Command R+ and GPT-4-Turbo, against human
evaluations across several Arabic dialects. The
mean absolute differences in scores for dialect au-
thenticity and content accuracy are calculated to
quantify the closeness of model evaluations to hu-
man judgments. Cohere Command R+ consistently
shows a smaller deviation from human scores, with
an average difference of 1.47 in dialect authenticity
and 1.36 in content accuracy, compared to GPT-4-
Turbo’s 1.64 and 1.68, respectively. This suggests
that Cohere Command R+ is better aligned with
human evaluations, offering a more accurate reflec-
tion of human perception in dialect authenticity and
content accuracy assessments.
5.2.2 Dallah Performance on Dialects
The evaluation of Dallah ’s performance on vari-
ous Arabic dialects using model-based and human
evaluators in Table 3 provides crucial insights into
its linguistic capabilities. The dialect authenticity
and content accuracy scores indicate that Dallah
can generate generally well-received outputs, with
some variations across different evaluators and di-
alects.
The higher ratings from Cohere Command R+
indicate that Dallah excels in producing authentic
dialect responses that align well with Command
R+’s evaluation framework. However, the lower
scores from GPT-4-Turbo reveal that some dialects
are underrepresented in its training data, leading to
You are a special ized chatbot tr ained to ev aluate the authentici ty of Ar abic
dialects. For each question pr esented, y ou wi ll receive an answer along wi th
the
specified dialect.
Your task is to assess the authentici ty of the dialect used in the answer on a
scale f rom 1 to 10, wher e 10 signi fies perf ect authentici ty. And also to assess
the ac curacy of the answer f rom the giv en context.
In your explanation of the scor e, mention the wor ds that belong to the dialect
and those that lower the scor e because they ar e from Modern Standar d Arabic
(MSA). Explain the r elevance and completeness of the r esponse.
Your explanation should be concise, clear , and in a maximum of 50 wor ds.
Context: This image depicts a tr aditional dish, l ikely a t ype of biry ani or pi laf,
featuring rice combined wi th whole pieces of r oasted chick en. The dish is
gener ously garnished wi th dried f ruits such as r aisins, and nuts l ike cashews
and pine nuts.
Dialect: Egyptian.
Question: اﻳﻪ ﻧﻮع اﻟﻠﺤﻤﺔ اﻟﻤﻌﻤﻮﻟﺔ ﻓﻲ اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة؟
Answer: اﻷﻛﻠﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة دي ﻓﯿﮫﺎ ﻟﺤﻢ ﻓﺮاخ .
"Dialect A uthentici ty Score": "9",
"Dialect A uthentici ty Reason": " The response uses mostly Egyptian dialect
words like "اﻟﻠﻲ "and " ﻓﺮاخ,".
"Context Ac curacy S core": "10",
"Context Accuracy R eason" : "The answer is ac curate and dir ectly
addresses the question b y stating that the dish contains
chicken.."
Figure 7: Method employed to evaluate dialect authen-
ticity and content accuracy using both model and human
evaluators. Human evaluators are also provided with an
image for each question to facilitate better judgment.
misunderstandings of dialectal responses and lower
scores in content accuracy.
Moreover, the variation within individual di-
alects and the representation of each dialect in the
LLM, along with the limited data used in the fine-
tuning, affect the performance of these systems. It
is important to note that spoken dialects often differ
from written forms. Written dialects are typically
closer to MSA as they lack acoustic cues, which
may influence human evaluators. When reading the
written model responses, evaluators might perceive
them as MSA. When spoken aloud, however, the
text may sound dialectal.
Furthermore, we attempt to compare our results
with GPT-4V . However, GPT-4V consistently re-
sponded in MSA even when prompted with dialects.
This highlights our model’s superiority over GPT-
4V in handling dialectal variation as our model
responds in dialect.
Additionally, the human evaluation highlights
the importance of incorporating cultural and lin-
guistic subtleties in model assessments. Future
work could explore more sophisticated evaluation
metrics or integrate additional human feedback to
refine Dallah ’s performance further. We provide | qualitative analysis in A.3. This analysis offers
insights into the model’s handling of MSA and
various dialects.
5.2.3 Feasibility of Model Evaluations for
Arabic Dialects
Given the findings from the comparative analysis,
model evaluations, particularly using Cohere Com-
mand R+, demonstrate potential as useful tools for
assessing dialect authenticity in Arabic dialects.
While these evaluations do not completely align
with human judgments, they offer a sufficiently
close approximation that can be valuable in scenar-
ios where rapid or large-scale evaluations are neces-
sary. However, for applications requiring accurate
understanding and cultural sensitivity, human as-
sessments should ideally complement these model
evaluations to ensure accuracy and relevance in the
context of specific Arabic dialects.
6 Conclusion
The paper introduces Dallah , an advanced multi-
modal large language model tailored for Arabic
dialects, which demonstrates superior performance
in processing both standard Arabic and regional
dialects. Developed through innovative data filter-
ing and training, Dallah achieves state-of-the-art
performance in the LLaV A-benchmark. Dallah
maintains dialect authenticity and content accu-
racy, showing promising results in benchmarks and
evaluations. Extensive testing shows the model’s
robustness in MSA and across various dialects and
contexts. This model marks a significant step in
enhancing Arabic NLP, with future goals to expand
dialect coverage and refine evaluation metrics for
better user interaction insights.
Limitations
We identify a number of limitations for our work,
as follows:
•Representation of Arabic Culture : Vision
models, LLMs, and datasets used in build-
ing MLLMs inadequately represent Arabic
figures, places, and culture. As shown in Fig-
ure 10, Dallah struggles with recognizing Ara-
bic figures, unlike those from the USA. This
highlights the need for more diverse cultural
datasets.
•Hallucination Control :Dallah , like many
LLMs, is prone to hallucinations, generating
inaccurate information. Advanced techniquesand more robust datasets are needed to miti-
gate this issue and ensure reliability.
•Dialect Variation and Mixing : The model
sometimes mixes similar dialects, such as
Yemeni and Saudi, and struggles with di-
alects close to MSA. This can be improved
with more extensive data collection and fine-
tuning.
•Arabic Text Recognition in Images :Dal-
lahcannot effectively recognize Arabic text
within images due to the lack of annotated
datasets. Developing such datasets is essential
to enhance the model’s multimodal capabili-
ties.
Ethics Statement
Energy Efficiency. OurDallah models, like many
large MLLMs, require significant pre-training time
and are not energy-efficient. We acknowledge this
critical issue and support continued research to-
wards developing energy-efficient models.
Data. Our pre-training datasets are translated from
publicly available English data, encompassing di-
verse genres, communities, and varieties. Our Dal-
lahmodels demonstrate potential in applications
involving several Arabic varieties, serving broad
populations.
Human Annotation. The human annotators in-
volved in this project are Arabic native speakers
and well-educated individuals with PhD degrees
and extensive NLP experience. No Institutional
Review Board (IRB) review or approval was re-
quired for this project since we only used publicly
available data, which does not require access to any
social networking account or password.
Applications. While Dallah , like many MLLMs,
can be misused. It also holds promise for bene-
ficial applications in education, health, and more.
Responsible deployment and use are crucial to max-
imizing its positive impact. It would also help keep
Arabic varieties in use in written form in the digital
age.
Acknowledgments
We acknowledge support from Canada Research
Chairs (CRC), the Natural Sciences and Engineer-
ing Research Council of Canada (NSERC; RGPIN-
2018-04267), the Social Sciences and Humanities
Research Council of Canada (SSHRC; 435-2018-
0576; 895-2020-1004; 895-2021-1008), Canadian
Foundation for Innovation (CFI; 37771), Digital
Research Alliance of Canada,6and UBC ARC-
Sockeye.
References
Marah Abdin, Sam Ade Jacobs, Ammar Ahmad Awan,
Jyoti Aneja, Ahmed Awadallah, Hany Awadalla,
Nguyen Bach, Amit Bahree, Arash Bakhtiari, Harki-
rat Behl, et al. 2024. Phi-3 technical report: A highly
capable language model locally on your phone. arXiv
preprint arXiv:2404.14219 .
Josh Achiam, Steven Adler, Sandhini Agarwal, Lama
Ahmad, Ilge Akkaya, Florencia Leoni Aleman,
Diogo Almeida, Janko Altenschmidt, Sam Altman,
Shyamal Anadkat, et al. 2023. Gpt-4 technical report.
arXiv preprint arXiv:2303.08774 .
Azimjon Ahmedov and Xabibullayeva Shaxrizoda.
2024. The english effect. Ta’limning zamonaviy
transformatsiyasi , 7(3):18–23.
Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc,
Antoine Miech, Iain Barr, Yana Hasson, Karel
Lenc, Arthur Mensch, Katherine Millican, Malcolm
Reynolds, et al. 2022. Flamingo: a visual language
model for few-shot learning. Advances in neural
information processing systems , 35:23716–23736.
Fakhraddin Alwajih, El Moatez Billah Nagoudi, Gagan
Bhatia, Abdelrahman Mohamed, and Muhammad
Abdul-Mageed. 2024. Peacock: A family of arabic
multimodal large language models and benchmarks.
Preprint , arXiv:2403.01031.
Richard Barnet and John Cavanagh. 2014. Homoge-
nization of global culture. In The case against the
global economy , pages 169–174. Routledge.
Tom Brown, Benjamin Mann, Nick Ryder, Melanie
Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind
Neelakantan, Pranav Shyam, Girish Sastry, Amanda
Askell, et al. 2020. Language models are few-shot
learners. Advances in neural information processing
systems , 33:1877–1901.
Guiming Hardy Chen, Shunian Chen, Ruifei Zhang,
Junying Chen, Xiangbo Wu, Zhiyi Zhang, Zhihong
Chen, Jianquan Li, Xiang Wan, and Benyou Wang.
2024. Allava: Harnessing gpt4v-synthesized data
for a lite vision-language model. arXiv preprint
arXiv:2402.11684 .
Lin Chen, Jisong Li, Xiaoyi Dong, Pan Zhang, Con-
ghui He, Jiaqi Wang, Feng Zhao, and Dahua
Lin. 2023. Sharegpt4v: Improving large multi-
modal models with better captions. arXiv preprint
arXiv:2311.12793 .
Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng,
Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan
6https://alliancecan.caZhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion
Stoica, and Eric P. Xing. 2023. Vicuna: An open-
source chatbot impressing gpt-4 with 90%* chatgpt
quality.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and
Kristina Toutanova. 2018. Bert: Pre-training of deep
bidirectional transformers for language understand-
ing.arXiv preprint arXiv:1810.04805 .
Zakaria Fahmi and Dacota Liska. 2024. Promoting ara-
bic as a foreign language in the middle east and north
africa: Host-grounded study abroad discourses. Fron-
tiers: The Interdisciplinary Journal of Study Abroad ,
36(1):384–417.
Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan
Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang,
and Weizhu Chen. 2021. Lora: Low-rank adap-
tation of large language models. arXiv preprint
arXiv:2106.09685 .
Huang Huang, Fei Yu, Jianqing Zhu, Xuening Sun, Hao
Cheng, Dingjie Song, Zhihong Chen, Abdulmohsen
Alharthi, Bang An, Ziche Liu, Zhiyi Zhang, Juny-
ing Chen, Jianquan Li, Benyou Wang, Lian Zhang,
Ruoyu Sun, Xiang Wan, Haizhou Li, and Jinchao Xu.
2023. Acegpt, localizing large language models in
arabic. Preprint , arXiv:2309.12053.
Mojan Javaheripi, S ´ebastien Bubeck, Marah Abdin,
Jyoti Aneja, Caio C ´esar Teodoro Mendes, Weizhu
Chen, Allie Del Giorno, Ronen Eldan, Sivakanth
Gopi, Suriya Gunasekar, Piero Kauffmann, Yin Tat
Lee, Yuanzhi Li, Anh Nguyen, Gustavo de Rosa,
Olli Saarikivi, Adil Salim, Shital Shah, Michael San-
tacroce, Harkirat Singh Behl, Adam Taumann Kalai,
Xin Wang, Rachel Ward, Philipp Witte, Cyril Zhang,
and Yi Zhang. 2023. Phi-2: The surprising power of
small language models. Microsoft Research Blog.
Albert Q Jiang, Alexandre Sablayrolles, Arthur Men-
sch, Chris Bamford, Devendra Singh Chaplot, Diego
de las Casas, Florian Bressand, Gianna Lengyel, Guil-
laume Lample, Lucile Saulnier, et al. 2023. Mistral
7b.arXiv preprint arXiv:2310.06825 .
Albert Q Jiang, Alexandre Sablayrolles, Antoine
Roux, Arthur Mensch, Blanche Savary, Chris Bam-
ford, Devendra Singh Chaplot, Diego de las Casas,
Emma Bou Hanna, Florian Bressand, et al. 2024.
Mixtral of experts. arXiv preprint arXiv:2401.04088 .
Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi.
2023. Blip-2: Bootstrapping language-image pre-
training with frozen image encoders and large lan-
guage models. In International conference on ma-
chine learning , pages 19730–19742. PMLR.
Tsung-Yi Lin, Michael Maire, Serge Belongie, James
Hays, Pietro Perona, Deva Ramanan, Piotr Doll ´ar,
and C Lawrence Zitnick. 2014. Microsoft coco:
Common objects in context. In Computer Vision–
ECCV 2014: 13th European Conference, Zurich,
Switzerland, September 6-12, 2014, Proceedings,
Part V 13 , pages 740–755. Springer.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2023a. Improved baselines with visual instruc-
tion tuning.
Haotian Liu, Chunyuan Li, Yuheng Li, and Yong Jae
Lee. 2024. Improved baselines with visual instruc-
tion tuning. In Proceedings of the IEEE/CVF Con-
ference on Computer Vision and Pattern Recognition ,
pages 26296–26306.
Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae
Lee. 2023b. Visual instruction tuning. In NeurIPS .
Muhammad Maaz, Hanoona Rasheed, Abdelrahman
Shaker, Salman Khan, Hisham Cholakal, Rao M. An-
wer, Tim Baldwin, Michael Felsberg, and Fahad S.
Khan. 2024. Palo: A polyglot large multimodal
model for 5b people. Preprint , arXiv:2402.14818.
Rui Meng, Ye Liu, Shafiq Rayhan Joty, Caiming
Xiong, Yingbo Zhou, and Semih Yavuz. 2024. Sfr-
embedding-mistral:enhance text retrieval with trans-
fer learning.
Abdelrahman Mohamed, Fakhraddin Alwajih,
El Moatez Billah Nagoudi, Alcides Inciarte, and
Muhammad Abdul-Mageed. 2023. Violet: A
vision-language model for Arabic image captioning
with gemini decoder. In Proceedings of ArabicNLP
2023 , pages 1–11, Singapore (Hybrid). Association
for Computational Linguistics.
Niklas Muennighoff, Nouamane Tazi, Lo ¨ıc Magne, and
Nils Reimers. 2022. Mteb: Massive text embedding
benchmark. arXiv preprint arXiv:2210.07316 .
El Moatez Billah Nagoudi, Muhammad Abdul-Mageed,
AbdelRahim Elmadany, Alcides Alcoba Inciarte, and
Md Tawkat Islam Khondaker. 2023. Jasmine: Ara-
bic gpt models for few-shot learning. Preprint ,
arXiv:2212.10755.
OpenAI. 2023. Chatgpt. AI language model. Accessed:
2024-04-30.
Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya
Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sas-
try, Amanda Askell, Pamela Mishkin, Jack Clark,
et al. 2021. Learning transferable visual models from
natural language supervision. In International confer-
ence on machine learning , pages 8748–8763. PMLR.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan,
Dario Amodei, Ilya Sutskever, et al. 2019. Language
models are unsupervised multitask learners. OpenAI
blog, 1(8):9.
Colin Raffel, Noam Shazeer, Adam Roberts, Katherine
Lee, Sharan Narang, Michael Matena, Yanqi Zhou,
Wei Li, and Peter J Liu. 2020. Exploring the lim-
its of transfer learning with a unified text-to-text
transformer. Journal of machine learning research ,
21(140):1–67.Christoph Schuhmann, Romain Beaumont, Richard
Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti,
Theo Coombes, Aarush Katta, Clayton Mullis,
Mitchell Wortsman, et al. 2022. Laion-5b: An open
large-scale dataset for training next generation image-
text models. Advances in Neural Information Pro-
cessing Systems , 35:25278–25294.
Neha Sengupta, Sunil Kumar Sahu, Bokang Jia,
Satheesh Katipomu, Haonan Li, Fajri Koto, William
Marshall, Gurpreet Gosal, Cynthia Liu, Zhiming
Chen, Osama Mohammed Afzal, Samta Kamboj,
Onkar Pandit, Rahul Pal, Lalit Pradhan, Zain Muham-
mad Mujahid, Massa Baali, Xudong Han, Son-
dos Mahmoud Bsharat, Alham Fikri Aji, Zhiqiang
Shen, Zhengzhong Liu, Natalia Vassilieva, Joel Hes-
tness, Andy Hock, Andrew Feldman, Jonathan Lee,
Andrew Jackson, Hector Xuguang Ren, Preslav
Nakov, Timothy Baldwin, and Eric Xing. 2023.
Jais and jais-chat: Arabic-centric foundation and
instruction-tuned open generative large language
models. Preprint , arXiv:2308.16149.
Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann
Dubois, Xuechen Li, Carlos Guestrin, Percy Liang,
and Tatsunori B. Hashimoto. 2023. Stanford alpaca:
An instruction-following llama model. https://
github.com/tatsu-lab/stanford alpaca .
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
Martinet, Marie-Anne Lachaux, Timoth ´ee Lacroix,
Baptiste Rozi `ere, Naman Goyal, Eric Hambro, Faisal
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint
arXiv:2302.13971 .
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
Bhosale, et al. 2023b. Llama 2: Open founda-
tion and fine-tuned chat models. arXiv preprint
arXiv:2307.09288 .
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob
Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz
Kaiser, and Illia Polosukhin. 2017. Attention is all
you need. Advances in neural information processing
systems , 30.
Junke Wang, Lingchen Meng, Zejia Weng, Bo He, Zux-
uan Wu, and Yu-Gang Jiang. 2023. To see is to be-
lieve: Prompting gpt-4v for better visual instruction
tuning. arXiv preprint arXiv:2311.07574 .
Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang,
Rangan Majumder, and Furu Wei. 2024. Multilingual
e5 text embeddings: A technical report. Preprint ,
arXiv:2402.05672.
Susan Zhang, Stephen Roller, Naman Goyal, Mikel
Artetxe, Moya Chen, Shuohui Chen, Christopher De-
wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022.
Opt: Open pre-trained transformer language models.
arXiv preprint arXiv:2205.01068 .
Wenhao Zhu, Hongyi Liu, Qingxiu Dong, Jingjing Xu,
Shujian Huang, Lingpeng Kong, Jiajun Chen, and
Lei Li. 2023. Multilingual machine translation with
large language models: Empirical results and analy-
sis.Preprint , arXiv:2304.04675.
A Appendices
We organize content here as follows:
• Translation and Filtering Details (A.1)
• Dialect Translation Examples (A.2)
• Qualitative Analysis (A.3)
A.1 Translation and Filtering Details
As described in Section 3.1, we employed a care-
ful translation and filtering process to ensure the
quality of the Arabic dataset used for training the
Dallah model. Figure 2 demonstrates this process,
highlighting the importance of maintaining high
translation accuracy. Examples with low similarity
scores between the original English text and back-
translated English text were removed, as shown in
the red rows. These include mistranslations such
as “What does my browser load?” and “The bird
in the photo is an ice skater,” which were incor-
rectly back-translated from the original prompts.
Conversely, examples with high similarity scores,
as shown in the green rows, were retained, ensur-
ing that both the questions and answers remained
consistent and accurate. This careful filtering pro-
cess was crucial in developing a robust and reliable
Arabic multimodal language model capable of han-
dling complex dialectal interactions.
A.2 Dialect Translation Examples
Figure 8 showcases examples of translations from
MSA to regional dialects from six Arabic-speaking
countries: Egypt, Mauritania, Morocco, Palestine,
Saudi Arabia, and Yemen. These translations were
performed by native speakers, ensuring cultural
and contextual accuracy. Such examples highlight
the complexities involved in developing a dialect-
aware multimodal language model like Dallah .
A.3 Qualitative Analysis
The qualitative evaluation of Dallah ’s responses
showcases its effectiveness in generating accurate
and contextually relevant answers across various
Arabic dialects. This evaluation is based on ex-
amples illustrated in Figures 9, 10, 11, and 12 ,
highlighting Dallah ’s capability to handle MSAand diverse dialectal interactions in both textual
and visual contexts.
In the context of food descriptions in Figure 9,
Dallah was asked to describe a traditional dish,
including the preparation steps. The response pro-
vided a detailed and coherent step-by-step guide,
demonstrating the model’s understanding of culi-
nary terms. This example highlights Dallah ’s profi-
ciency in generating detailed content. Additionally,
in the same figure, Dallah demonstrated the ability
to generate detailed and accurate descriptions of an
image containing a group of children and was ca-
pable of providing potential risks about the activity
in the image when asked about potential risks.
As shown in Figure 10, Dallah illustrates its
ability to describe the appearance of persons and
Arabic figures but fails to identify these figures. In
contrast, the model was capable of identifying the
US president, which is due to the lack of represen-
tation for Arabic figures and culture.
Dallah also demonstrated its ability to manage
dialectal variations and maintain contextual accu-
racy as shown in Figure 11 and 12. When address-
ing questions in a specific dialect, the model ac-
curately reflected local linguistic features and id-
iomatic expressions. The ability to switch between
dialects and maintain contextual accuracy is cru-
cial for multilingual and multicultural applications,
highlighting Dallah ’s comprehensive training on
diverse dialectal datasets.
Dallah ’s qualitative performance underscores its
potential as a robust multimodal language model
tailored for Arabic dialects. Its capability to gen-
erate accurate, contextually relevant, and dialect-
specific responses makes it a valuable tool for vari-
ous applications, from education to cultural preser-
vation. The model’s strength in handling diverse
dialectal variations and integrating visual and tex-
tual information is particularly noteworthy, paving
the way for further advancements in Arabic NLP.
Egyptﻧﻌﻢ، ﻳﺒﺪو أن اﻟﻤﺮأﺗﯿﻦ ﻣﻨﺨﺮطﺘﺎن ﻓﻲ ﻣﺤﺎدﺛﺔ أﺛﻨﺎء اﺳﺘﺨﺪاﻣﮫﻤﺎ
ﻟﮫﻮاﺗﻔﮫﻤﺎ، ﻣﻤﺎ ﻳﻮﺣﻲ ﺑﺄﻧﮫﻤﺎ رﺑﻤﺎ ﻳﻨﺎﻗﺸﺎن ﻣﺎ ﻳﺸﺎرﻛﺎﻧﻪ ﻋﻠﻰ أﺟﮫﺰﺗﮫﻤﺎ أو
ﻳﺴﺘﻤﺘﻌﺎن ﺑﻤﺤﺎدﺛﺔ ودﻳﺔ أﺛﻨﺎء ﺗﻨﺎول اﻟﻌﺸﺎء ﻣﻌًﺎ.اﻳﻮا، واﺿﺢ ان اﻻﺗﻨﯿﻦ ﺳﺘﺎت ﻣﺸﻐﻮﻟﯿﻦ وھﻤﺎ ﺑﯿﺘﻜﻠﻤﻮا ﻓﻲ اﻟﺘﻠﯿﻔﻮﻧﺎت
ﺑﺘﺎﻋﺘﮫﻢ، اﻟﻠﻲ ﺑﯿﻮﺣﻲ اﻧﮫﻢ ﻣﻤﻜﻦ ﻳﻜﻮﻧﻮا ﺑﯿﺘﻨﺎﻗﺸﻮا اﻟﻠﻲ ﻓﻲ اﺟﮫﺰﺗﮫﻢ أو
ﺑﯿﺴﺘﻤﺘﻌﻮا ﺑﻤﻜﺎﻣﻠﺔ ودﻳﺔ وھﻤﺎ ﺑﯿﺘﻌﺸﻮا ﺳﻮا.
ھﻞ اﻟﻤﺮأة واﻗﻔﺔ أم ﺟﺎﻟﺴﺔ؟ﻟﻤﺮا واﻗﻔﺔ وﻟﻼ ﻗﺎﻋﺪة؟
ﻛﻢ ﻋﺪد اﻷﺷﺨﺎص اﻟﻤﻮﺟﻮدﻳﻦ ﻓﻲ اﻟﺼﻮرة، وﻣﺎذا ﻳﻔﻌﻠﻮن؟ﺷﺤﺎل دﻳﺎل اﻟﻨﺎس ﻛﺎﻳﻨﯿﻦ ﻓﻲ اﻟﺼﻮرة, وﺷﻨﻮ ﻛﺎﻳﺪﻳﺮو؟
ﻣﺎ ﻧﻮع اﻟﺰھﻮر اﻟﺘﻲ ﻳﻤﻜﻦ رؤﻳﺘﮫﺎ ﺗﺤﯿﻂ ﺑﻤﻌﺎﻟﻢ اﻟﺤﺪﻳﻘﺔ؟ﺷﻮ ﻧﻮع اﻟﻮرد اﻟﻲ ﻗﺎدر ﺗﺸﻮﻓﻪ ﺣﻮﻟﯿﻦ اﻟﻤﻨﺘﺰة؟
ﻧﻌﻢ، ھﻨﺎك رﺟﻞ ﻳﻈﮫﺮ ﻓﻲ اﻟﺼﻮرة، وھﻮ ﻳﻨﻈﺮ إﻟﻰ اﻟﺪراﺟﺎت اﻟﻨﺎرﻳﺔ
اﻟﻤﺘﻮﻗﻔﺔ.اﻳﻪ، ﻓﻲ رﺟﺎل ﻳﻄﻞّ ﻓﻲ اﻟﺼﻮرة، ﻳﻄﺎﻟﻊ ﻓﻲ اﻟﺪﺑﺎﺑﺎت واﻗﻔﺔ.
ﻻ ﻳﻮﺟﺪ ﺳﻮى ﺷﺨﺺ واﺣﺪ، وھﻮ راﻛﺐ أﻣﻮاج، ﻳﻈﮫﺮ ﻓﻲ اﻟﺼﻮرة.ﻣﺎ ﺑﺶ اﻻ ﺷﺨﺺ واﺣﺪ , وھﻮ راﻛﺐ أﻣﻮاج , ﺑﺎﻳﻦ ﻓﻲ اﻟﺼﻮرة. Mauritania
Morocco
Palestine
Suadi Arabia
YemenMSA Dialect Translation CountryFigure 8: Examples of Human Translation of MSA to Dialects Across Six Arabic-Speaking Countries
ھﺬي اﻟﻮﺟﺒﺔ اﺳﻤﮫﺎ دﺟﺎج ﻣﻊ اﻷرز واﻟﺨﻀﺎر ﻋﻠﻰ ﺻﺤﻦ ﻓﻀﻲ . ﻣﺎ اﺳﻢ ھﺬي اﻟﻮﺟﺒﺔ؟
ھﻞ ﻳﻤﻜﻨﻚ وﺻﻒ طﺮﻳﻘﺔ ﺗﺤﻀﯿﺮھﺎ ﺑﺎﻟﺘﻔﺼﯿﻞ؟
ﻳﺒﺪو أن طﺮﻳﻘﺔ ﺗﺤﻀﯿﺮھﺎ ھﻲ ﺧﻠﯿﻂ ﻣﻦ اﻟﺪﺟﺎج واﻷرز واﻟﺨﻀﺎر، ﻣﻊ ﺧﻠﻂ اﻟﻤﻜﻮﻧﺎت ﻣﻌًﺎ ﻓﻲ ﺻﺤﻦ .
ارﻳﺪ ﺧﻄﻮات
ﺧﻄﻮات ﺗﺤﻀﯿﺮ اﻟﻮﺟﺒﺔ:
. 1 .اﻏﺴﻠﻲ اﻟﺪﺟﺎج وﻗﻄﻌﯿﻪ اﻟﻰ ﻗﻄﻊ
. 2 .ﻓﻲ ﻣﻘﻼة او ﺻﺤﻦ ﻛﺒﯿﺮ ، ﻗﻮﻣﻲ ﺑﻄﮫﻲ اﻟﺪﺟﺎج ﺣﺘﻰ ﻳﻨﻀﺞ ﺑﺎﻟﻜﺎﻣﻞ
. 3 .ﻓﻲ ﻧﻔﺲ اﻟﻤﻘﻼة او اﻟﺼﺤﻦ، ﻗﻮﻣﻲ ﺑﻄﮫﻲ اﻻرز ﺣﺘﻰ ﻳﻨﻀﺞ
. 4 .ﻓﻲ ﻣﻘﻼة ، ﻗﻮﻣﻲ ﺑﻄﮫﻲ اﻟﺨﻀﺎر، ﻣﻊ اﻟﺘﺄﻛﺪ ﻣﻦ طﮫﯿﮫﺎ ﺣﺘﻰ ﺗﺼﺒﺢ طﺮﻳﺔ وﻟﻜﻦ ﻻ ﺗﺰال ﻣﻘﺮﻣﺸﺔ ﻗﻠﯿﻼً
. 5 .ﻓﻲ ﻣﻘﻼة او اﻟﺼﺤﻦ، ﻗﻮﻣﻲ ﺑﺘﺠﻤﯿﻊ اﻟﺪﺟﺎج واﻷرز واﻟﺨﻀﺎر ﻣﻌًﺎ
. 6 .اﺳﻜﺒﻲ اﻟﺪﺟﺎج واﻷرز واﻟﺨﻀﺎر اﻟﻤﻄﺒﻮخ ﻓﻲ طﺒﻖ
. 7 .ﻗﺪﻣﻲ اﻟﻮﺟﺒﺔ
ھﺬه ھﻲ اﻟﺨﻄﻮات اﻟﻌﺎﻣﺔ اﻟﺘﻲ ﻳﺠﺐ اﺗﺒﺎﻋﮫﺎ ﻹﻋﺪاد وﺟﺒﺔ اﻟﺪﺟﺎج ﻣﻊ اﻷرز واﻟﺨﻀﺎر.
ﺗُﻈﮫﺮ اﻟﺼﻮرة ﻣﺠﻤﻮﻋﺔ ﻣﻦ ﺧﻤﺴﺔ أطﻔﺎل ﻳﻠﻌﺒﻮن ﻋﻠﻰ ﺗﻠﺔ ﻋﺸﺒﯿﺔ. إﻧﮫﻢ ﻳﻘﻔﻮن ﺣﻮل ﻛﺮة ﻛﺒﯿﺮة ﻣﻠﻮﻧﺔ، ﺗﺸﺒﻪ ﻛﺮة
اﻷرض، ﻣﻤﺎ ﻳﻀﯿﻒ ﻋﻨﺼﺮًا ﻣﺮﺣًﺎ إﻟﻰ ﻟﻌﺒﺘﮫﻢ. اﻟﺴﻤﺎء ﻓﻲ اﻟﺨﻠﻔﯿﺔ زرﻗﺎء ﺻﺎﻓﯿﺔ، ﻣﻤﺎ ﻳﻮﻓﺮ ﺗﺒﺎﻳﻨًﺎ ﺟﻤﯿﻼً ﻣﻊ اﻷرض اﻟﺨﻀﺮاء
ﻟﻠﺘﻞ. ﻳﺒﺪو أن اﻷطﻔﺎل ﻳﺴﺘﻤﺘﻌﻮن ﺑﻮﻗﺘﮫﻢ ﻓﻲ اﻟﮫﻮاء اﻟﻄﻠﻖ، وﻳﺘﻔﺎﻋﻠﻮن ﻣﻊ ﺑﻌﻀﮫﻢ اﻟﺒﻌﺾ، وﻳﺘﺸﺎرﻛﻮن ﻟﺤﻈﺔ ﻣﺮﺣﺔ. ﺻﻒ اﻟﺼﻮرة؟
ﻣﺎھﻲ اﻟﻤﺨﺎطﺮ اﻟﻤﺤﺘﻤﻠﺔ ﻣﻦ ھﺬه اﻟﻠﻌﺒﺔ؟
ﻋﻠﻰ اﻟﺮﻏﻢ ﻣﻦ أن اﻟﻠﻌﺒﺔ ﺗﺒﺪو ﻣﻤﺘﻌﺔ، إﻻ أﻧﮫﺎ ﻗﺪ ﺗﺸﻜﻞ ﺑﻌﺾ اﻟﻤﺨﺎطﺮ اﻟﻤﺤﺘﻤﻠﺔ ﻟﻸطﻔﺎل. ﻧﻈﺮًا ﻷن اﻷطﻔﺎل ﻳﻘﻔﻮن ﺣﻮل اﻟﻜﺮة
اﻟﻜﺒﯿﺮة وﻳﺘﻔﺎﻋﻠﻮن ﻣﻌﮫﺎ، ﻓﻘﺪ ﻳﺴﻘﻄﻮن اﻟﻜﺮة أو ﻳﺼﻄﺪﻣﻮن ﺑﮫﺎ ﻋﻦ طﺮﻳﻖ اﻟﺨﻄﺄ، ﻣﻤﺎ ﻗﺪ ﻳﺆدي إﻟﻰ إﺻﺎﺑﺎت طﻔﯿﻔﺔ. ﺑﺎﻹﺿﺎﻓﺔ إﻟﻰ
ذﻟﻚ، إذا ﻓﻘﺪ اﻟﻄﻔﻞ ﺗﻮازﻧﻪ وﺳﻘﻂ ﻣﻦ ﻋﻠﻰ اﻟﻜﺮة، ﻓﻘﺪ ﻳﺘﻌﺮض ﻹﺻﺎﺑﺎت أﻛﺜﺮ ﺧﻄﻮرة، ﻣﺜﻞ اﻟﻜﺪﻣﺎت أو اﻻﻟﺘﻮاء أو ﺣﺘﻰ اﻟﻜﺴﻮر. ﻣﻦ
اﻟﻀﺮوري أن ﻳﺸﺮف اﻟﻜﺒﺎر ﻋﻠﻰ اﻷطﻔﺎل أﺛﻨﺎء ﻟﻌﺒﮫﻢ وأن ﻳﻀﻤﻨﻮا ﺳﻼﻣﺘﮫﻢ أﺛﻨﺎء اﻟﻤﺸﺎرﻛﺔ ﻓﻲ ﻣﺜﻞ ھﺬه اﻷﻧﺸﻄﺔ.
ﺗﻤﺘﻠﺊ اﻟﺜﻼﺟﺔ ﺑﻤﺠﻤﻮﻋﺔ ﻣﺘﻨﻮﻋﺔ ﻣﻦ اﻟﺒﻘﺎﻟﺔ، ﺑﻤﺎ ﻓﻲ ذﻟﻚ اﻟﻔﻮاﻛﻪ واﻟﺨﻀﺮوات واﻟﺒﯿﺾ واﻟﺠﺒﻦ. ھﻞ ﻳﻤﻜﻨﻚ وﺻﻒ أﻧﻮاع اﻟﺒﻘﺎﻟﺔ اﻟﻤﻘﺪﻣﺔ ﻓﻲ ھﺬه اﻟﺜﻼﺟﺔ؟
اذﻛﺮ ﻛﻞ اﻻﺻﻨﺎف اﻟﻤﻮﺟﻮدة
ﻓﻲ ھﺬه اﻟﺜﻼﺟﺔ، ﻳﻤﻜﻨﻚ اﻟﻌﺜﻮر ﻋﻠﻰ اﻟﻄﻤﺎطﻢ واﻟﻔﻠﻔﻞ اﻟﺤﻠﻮ واﻟﻘﺮﻧﺒﯿﻂ واﻟﻔﻠﻔﻞ اﻷﺣﻤﺮ واﻟﺠﺰر. ﺑﺎﻹﺿﺎﻓﺔ إﻟﻰ ذﻟﻚ، ھﻨﺎك اﻟﺠﺒﻦ
واﻟﺒﯿﺾ.
ﻣﺎھﻲ اﻟﻮﺟﺒﺔ اﻟﺘﻲ ﻳﻤﻜﻦ ﺻﻨﻌﮫﺎ ﻣﻦ ھﺬه اﻟﺨﻀﺮوات ؟
إﺣﺪى اﻟﻮﺟﺒﺎت اﻟﻤﻤﻜﻨﺔ اﻟﺘﻲ ﻳﻤﻜﻦ إﻋﺪادھﺎ ﻣﻦ ھﺬه اﻟﺨﻀﺮوات ھﻲ ﺳﻠﻄﺔ ﻣﻠﻮﻧﺔ وﺻﺤﯿﺔ. ﻳﻤﻜﻨﻚ ﺗﻘﻄﯿﻊ اﻟﻄﻤﺎطﻢ واﻟﻔﻠﻔﻞ اﻟﺤﻠﻮ
واﻟﻘﺮﻧﺒﯿﻂ واﻟﻔﻠﻔﻞ اﻷﺣﻤﺮ واﻟﺠﺰر إﻟﻰ ﻗﻄﻊ ﺻﻐﯿﺮة اﻟﺤﺠﻢ، ﺛﻢ ﻗﻢ ﺑﺘﺠﻤﯿﻌﮫﺎ ﻣﻊ ﺷﺮاﺋﺢ اﻟﺒﯿﺾ. ﻳﻤﻜﻨﻚ ﺑﻌﺪ ذﻟﻚ رش اﻟﺴﻠﻄﺔ ﺑﺰﻳﺖ
اﻟﺰﻳﺘﻮن اﻟﺒﻜﺮ اﻟﻤﻤﺘﺎز وﻋﺼﯿﺮ اﻟﻠﯿﻤﻮن واﻟﻤﻠﺢ واﻟﻔﻠﻔﻞ ﺣﺴﺐ اﻟﺮﻏﺒﺔ. ﻳﻤﻜﻦ أن ﺗﻜﻮن اﻟﺴﻠﻄﺔ ﻣﺼﺤﻮﺑﺔ ﺑﺠﺒﻨﺔ اﻟﺸﯿﺪر اﻟﻤﺒﺸﻮرة أو
اﻟﻤﻘﻄﻌﺔ إﻟﻰ ﺷﺮاﺋﺢ رﻓﯿﻌﺔ، واﻟﺘﻲ ﻳﻤﻜﻦ أن ﺗﻀﯿﻒ ﻧﻜﮫﺔ ﻛﺮﻳﻤﯿﺔ إﻟﻰ اﻟﻄﺒﻖ. ﻳﻤﻜﻦ أن ﺗﻜﻮن ھﺬه اﻟﻮﺟﺒﺔ اﻟﻤﻐﺬﻳﺔ واﻟﻠﺬﻳﺬة ﻣﺜﺎﻟﯿﺔ
ﻟﻠﻐﺪاء أو اﻟﻌﺸﺎء، ﻣﻤﺎ ﻳﻮﻓﺮ ﻣﺰﻳﺠًﺎ ﻣﻦ اﻟﻔﯿﺘﺎﻣﯿﻨﺎت واﻟﻤﻌﺎدن واﻟﺒﺮوﺗﯿﻨﺎت ﻣﻦ اﻟﺨﻀﺮوات واﻟﺒﯿﺾ واﻟﺠﺒﻦ.
Figure 9: Three examples demonstrating Dallah ’s chat capabilities in Modern Standard Arabic (MSA). The first
example involves describing a traditional dish and its preparation steps. The second example showcases Dallah ’s
ability to describe an image and identify potential risks for children in the activity depicted. The third example
highlights Dallah ’s proficiency in providing nutritional advice and describing various types of food.
ﻓﻲ اﻟﺼﻮرة، رﺟﻞ ﻛﺒﯿﺮ اﻟﺴﻦ ذو ﻟﺤﯿﺔ ﺑﯿﻀﺎء طﻮﻳﻠﺔ وﻳﺮﺗﺪي رداءً أﺑﯿﺾ. ﻳﺒﺪو أﻧﻪ رﺟﻞ ﻛﺒﯿﺮ اﻟﺴﻦ، رﺑﻤﺎ ﻣﻦ اﻟﺸﺮق اﻷوﺳﻂ،
ذو ﺷﻌﺮ أﺑﯿﺾ. ﺗﺸﯿﺮ وﺿﻌﯿﺘﻪ إﻟﻰ أﻧﻪ ﻗﺪ ﻳﻜﻮن ﻓﻲ ﻣﻨﺘﺼﻒ ﻟﺤﻈﺔ ﺗﻔﻜﯿﺮ أو ﺗﺄﻣﻞ. اﻟﺼﻮرة ﺑﺎﻷﺑﯿﺾ واﻷﺳﻮد، ﻣﻤﺎ ﻳﻀﻔﻲ
ﻋﻠﯿﮫﺎ طﺎﺑﻌًﺎ ﺧﺎﻟﺪًا وﻛﻼﺳﯿﻜﯿًﺎ .ﺻﻒ اﻟﺼﻮرة ﺑﺎﻟﺘﻔﺼﯿﻞ؟
ھﻞ ﻣﻦ اﻟﻤﻤﻜﻦ ان ﺗﺨﺒﺮﻧﻲ ﺑﻤﻮطﻦ ھﺬا اﻟﺮﺟﻞ؟
وﻣﻦ اﻟﺼﻌﺐ ﺗﺤﺪﻳﺪ ﻣﻮطﻦ اﻟﺮﺟﻞ ﺑﺸﻜﻞ ﻗﺎطﻊ ﺑﻨﺎءً ﻋﻠﻰ اﻟﺼﻮرة ﻓﻘﻂ. وﻣﻊ ذﻟﻚ، ﻓﺈن ﻣﻼﺑﺴﻪ ووﺟﻮده ﺻﺤﺮاء ﻗﺪ ﻳﺸﯿﺮ إﻟﻰ
أﻧﻪ ﻓﻲ ﻣﻜﺎن ﻟﻪ طﺎﺑﻊ ﺷﺮﻗﻲ أو ﻣﺘﻮﺳﻂ ﺷﺮﻗﻲ، ﻣﺜﻞ اﻟﺸﺮق اﻷوﺳﻂ أو ﺷﻤﺎل أﻓﺮﻳﻘﯿﺎ. ﻳﻤﻜﻦ أن ﺗﻜﻮن ھﺬه أﻳﻀًﺎ ﻣﻨﻄﻘﺔ
ذات ﺗﺄﺛﯿﺮ ﺛﻘﺎﻓﻲ أوروﺑﻲ أو ﻣﺘﻮﺳﻂ أوﺳﻂ أو ﻣﺘﻮﺳﻂ ﺷﺮﻗﻲ. وﻣﻊ ذﻟﻚ، ﺑﺪون ﺳﯿﺎق إﺿﺎﻓﻲ أو ﺗﻔﺎﺻﯿﻞ أﻛﺜﺮ ﺗﺤﺪﻳﺪًا، ﻓﻤﻦ
اﻟﻤﺴﺘﺤﯿﻞ ﺗﺤﺪﻳﺪ ﻣﻮطﻨﻪ ﺑﺪﻗﺔ.
اﻧﻪ ﻋﻤﺮ اﻟﻤﺨﺘﺎر ھﻞ ﺗﻌﺮف ﺗﺎرﻳﺨﻪ؟
، وھﻮ ﻗﺎﺋﺪ ﻋﺴﻜﺮي وﺳﯿﺎﺳﻲ ﻟﯿﺒﻲ ﻣﺸﮫﻮر. اﺷﺘﮫﺮ ﺧﻼل اﻟﺤﺮب اﻟﻌﺎﻟﻤﯿﺔ 1862 ﻋﻤﺮ اﻟﻤﺨﺘﺎر ھﻮ رﺟﻞ ﻟﯿﺒﻲ اﻟﻤﻮﻟﺪ، وﻟﺪ ﻓﻲ ﻋﺎم
اﻷوﻟﻰ ﻋﻨﺪﻣﺎ ﻗﺎد اﻟﻤﻘﺎوﻣﺔ اﻟﻠﯿﺒﯿﺔ ﺿﺪ اﻻﺣﺘﻼل اﻹﻳﻄﺎﻟﻲ ﻟﻠﺒﻼد. أﺻﺒﺢ رﻣﺰًا ﻟﻼﺳﺘﻘﻼل اﻟﻠﯿﺒﻲ وأﺻﺒﺢ ﺷﺨﺼﯿﺔ ﻣﮫﻤﺔ ﻓﻲ اﻟﻜﻔﺎح
اﻟﻠﯿﺒﻲ ﻣﻦ أﺟﻞ اﻟﺤﺮﻳﺔ واﻻﺳﺘﻘﻼل. ﺧﻼل اﻟﺤﺮب اﻟﻌﺎﻟﻤﯿﺔ اﻷوﻟﻰ، ﻗﺎد ﻋﻤﺮ اﻟﻤﺨﺘﺎر اﻟﻘﻮات اﻟﻠﯿﺒﯿﺔ ﻓﻲ ﻣﻌﺎرك ﻣﺨﺘﻠﻔﺔ ﺿﺪ اﻟﻘﻮات
وﺗﻢ ﻧﻘﻠﻪ، ﺗﻢ أﺳﺮ ﻋﻤﺮ اﻟﻤﺨﺘﺎر ﻣﻦ ﻗﺒﻞ اﻟﻘﻮات اﻹﻳﻄﺎﻟﯿﺔ، 1916 ﻋﺎماﻹﻳﻄﺎﻟﯿﺔ، وﻛﺎن ﻣﻦ أﺑﺮز ﻣﻌﺎرﻛﻪ ﻣﻌﺮﻛﺔ اﻟﻘﺮﺿﺔ اﻟﺸﮫﯿﺮة. ﻓﻲ
ﺣﯿﺚ ﺗﻢ اﻋﺪاﻣﻪ ﻓﻲ اﻟﻌﺎم اﻟﺘﺎﻟﻲ. ﻋﻠﻰ اﻟﺮﻏﻢ ﻣﻦ وﻓﺎﺗﻪ، ﻓﺈن ﻋﻤﺮ اﻟﻤﺨﺘﺎر ﻳﻈﻞ ﺷﺨﺼﯿﺔ ﺗﺎرﻳﺨﯿﺔ ﻣﮫﻤﺔ ورﻣﺰًاإﻟﻰ روﻣﺎ
ﻟﻼﺳﺘﻘﻼل اﻟﻠﯿﺒﻲ. ﻟﻘﺪ أﻟﮫﻤﺖ ﺣﯿﺎﺗﻪ وإﻧﺠﺎزاﺗﻪ اﻟﻌﺪﻳﺪ ﻣﻦ اﻟﻠﯿﺒﯿﯿﻦ اﻟﺬﻳﻦ واﺻﻠﻮا اﻟﻜﻔﺎح ﻣﻦ أﺟﻞ ﺣﺮﻳﺘﮫﻢ واﺳﺘﻘﻼﻟﮫﻢ.
ﻓﻲ اﻟﺼﻮرة، ﻳﻘﻒ رﺟﻞ ﻳﺮﺗﺪي ﺑﺪﻟﺔ ورﺑﻄﺔ ﻋﻨﻖ أﻣﺎم ﺣﺸﺪ ﻣﻦ اﻟﻨﺎس. إﻧﻪ ﻳﺮﺗﺪي ﻧﻈﺎرة وﻳﺒﺪو أﻧﻪ ﻳﺒﺘﺴﻢ. ھﻨﺎك اﻟﻌﺪﻳﺪ ﻣﻦ
اﻷﺷﺨﺎص اﻵﺧﺮﻳﻦ ﻓﻲ اﻟﺨﻠﻔﯿﺔ، ﻣﻤﺎ ﻳﺨﻠﻖ ﺟﻮًا ﻣﺰدﺣﻤًﺎ. ﻳﺒﺪو أن اﻟﺮﺟﻞ اﻟﺬي ﻳﺮﺗﺪي اﻟﺒﺪﻟﺔ ھﻮ اﻟﺸﺨﺼﯿﺔ اﻟﻤﺮﻛﺰﻳﺔ ﻓﻲ
اﻟﺼﻮرة، ﺣﯿﺚ ﻳﺠﺬب اﻧﺘﺒﺎه اﻟﻤﺸﺎھﺪ ﺑﺤﻀﻮره. ﻣﺎذا ﺗﺮى ﻓﻲ اﻟﺼﻮرة؟
ھﻞ ﺗﻌﺮف اﻟﺸﺨﺼﯿﺔ ھﺬه؟
ﺑﻨﺎءً ﻋﻠﻰ اﻟﺼﻮرة، ﻻ ﻳﻤﻜﻦ ﺗﺤﺪﻳﺪ ھﻮﻳﺔ اﻟﺸﺨﺼﯿﺔ ﺑﺸﻜﻞ ﻗﺎطﻊ. وﻣﻊ ذﻟﻚ، ﻧﻈﺮًا ﻟﻤﻼﺑﺴﮫﻢ وﺣﻘﯿﻘﺔ أﻧﮫﻢ ﻳﻘﻔﻮن أﻣﺎم ﺣﺸﺪ
ﻣﻦ اﻟﻨﺎس، ﻓﻤﻦ اﻟﻤﺤﺘﻤﻞ أن ﺗﻜﻮن ﺷﺨﺼﯿﺔ ﺑﺎرزة أو ﻣﺸﮫﻮرة.
اﻧﻪ اﻟﺸﺎﻋﺮ ﻋﺒﺪﷲ اﻟﺒﺮودوﻧﻲ اﺧﺒﺮﻧﻲ ﻋﻨﻪ؟
. ﻳُﻌﺘﺒﺮ ﻣﻦ أھﻢ اﻟﺸﻌﺮاء اﻟﻌﺮب ﻓﻲ اﻟﻘﺮن اﻟﻌﺸﺮﻳﻦ. 1986 وﺗﻮﻓﻲ ﻓﻲ ﻋﺎم 1910 ﻋﺒﺪ ﷲ اﻟﺒﺮودﻧﻲ ھﻮ ﺷﺎﻋﺮ ﻳﻤﻨﻲ وﻟﺪ ﻓﻲ ﻋﺎم
وُﻟﺪ ﻓﻲ ﻗﺮﻳﺔ اﻟﺒﺮدوﻧﻰ ﻓﻲ اﻟﯿﻤﻦ. اﺷﺘﮫﺮ اﻟﺒﺮودﻧﻲ ﺑﺄﺳﻠﻮﺑﻪ اﻟﻔﺮﻳﺪ ﻓﻲ اﻟﺸﻌﺮ وأﺳﻠﻮﺑﻪ اﻟﺬي ﻳﻤﺰج ﺑﯿﻦ اﻟﺘﻘﺎﻟﯿﺪ اﻟﺸﻌﺮﻳﺔ اﻟﻘﺪﻳﻤﺔ
واﻟﺤﺪﻳﺜﺔ.
ﻧﻌﻢ ﻳﻤﻜﻦ اﻟﺘﻌﺮف ﻋﻠﻰ اﻟﺸﺨﺺ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة ﻋﻠﻰ أﻧﻪ اﻟﺮﺋﯿﺲ أوﺑﺎﻣﺎ. ھﻞ ﻳﻤﻜﻨﻚ ان ﺗﺘﻌﺮف ﻋﻠﻰ اﻟﺸﺨﺺ اﻟﻤﻮﺟﻮد ﻓﻲ اﻟﺼﻮرة؟
اﻳﻦ ﻳﻘﻊ اﻟﻤﻜﺎن اﻟﺬي ﺗﻢ ﻓﯿﻪ ﺗﺼﻮﻳﺮه ﻓﯿﮫﺎ؟
ﺗﻢ ﺗﺼﻮﻳﺮ اﻟﺮﺋﯿﺲ أوﺑﺎﻣﺎ ﻓﻲ ﻣﻮﻗﻊ ﺗﺎرﻳﺨﻲ، رﺑﻤﺎ ﻓﻲ ﻣﺼﺮ، ﻛﻤﺎ ﻳﺪل ﻋﻠﻰ ذﻟﻚ وﺟﻮد اﻷھﺮاﻣﺎت ﻓﻲ اﻟﺨﻠﻔﯿﺔ.
Figure 10: Dallah is capable of answering questions related to images. However, Dallah couldn’t identify Arabic
figures in the first and second examples, while it was able to recognize the US president. Like many LLMs, Dallah
is prone to hallucinations. Red color font in the responses highlights examples of Dallah ’s hallucinations.
🇲🇦
.اﻟﻤﻌﻠﻢ اﻟﺘﺎرﻳﺨﻲ ﻛﺎﻳﻦ ﻋﻨﺪ ﺳﻔﺢ ﺟﺒﻞ ﺻﺨﺮي، وﻛﺎﻳﺒﺎن ﻓﺎﻟﺼﻮرة ﻣﻌﻠﻢ ﺣﺠﺮي ﻗﺪﻳﻢ، ﻳﻤﻜﻦ ﻳﻜﻮن ﻗﺼﺮ أو ﻣﻌﺒﺪ
اﻟﻤﻌﻠﻢ ﻛﺎﻳﺒﺎن ﻓﺎﻟﺨﻠﻔﯿﺔ، وھﺎدﺷﻲ ﻛﺎﻳﺨﻠﯿﻪ اﻟﻨﻘﻄﺔ اﻟﻤﺤﻮرﻳﺔ ﻓﺎﻟﺼﻮرة. وﺟﻮد اﻟﻌﺪﻳﺪ ﻣﻦ اﻷﺷﺨﺎص ﻓﺎﻟﻤﻨﻄﻘﺔ
ﻛﺎﻳﺸﯿﺮ أﻧﮫﺎ ﻳﻤﻜﻦ ﺗﻜﻮن ﻣﻨﻄﻘﺔ ﺟﺬب ﺳﯿﺎﺣﻲ أو ﻣﻮﻗﻊ ﺗﺎرﻳﺨﻲ ﺷﮫﯿﺮ، ﻣﻤﺎ ﻛﺎﻳﺨﻠﯿﮫﺎ ﻣﻜﺎن ﺷﮫﯿﺮ ﻟﻠﻨﺎس ﺑﺎش
ﻳﺘﻔﺮﺟﻮ ﻋﻠﻰ اﻟﻤﻌﻠﻢ وﻳﺴﺘﻜﺸﻔﻮ . ﻓﯿﻦ ﻛﺎﻳﻦ ھﺎد اﻟﻤﻌﻠﻢ اﻟﺘﺎرﻳﺨﻲ, ﻋﻄﻲ ﺟﻮاب ﺑﺎﻟﺘﻔﺎﺻﯿﻞ؟
🇪🇬
اﻟﺼﻮرة ﻓﯿﮫﺎ ﻣﺠﻤﻮﻋﺔ ﻣﻦ اﻟﺒﻠﺪات اﻟﺼﻐﯿﺮة أو اﻟﻘﺮى ﻋﻠﻰ ﺟﺒﻞ أو ﺗﻠﺔ، ودا ﺑﯿﻈﮫﺮ أﻧﮫﺎ أﻣﺎﻛﻦ ﺳﯿﺎﺣﯿﺔ
ﺷﮫﯿﺮة. اﻟﺴﯿﺎح ﺑﯿﺠﯿﻮا ھﻨﺎ ﻋﺸﺎن ﻳﺴﺘﻤﺘﻌﻮا ﺑﺎﻟﻤﻨﺎظﺮ اﻟﺨﻼﺑﺔ واﻟﺘﻔﺎﻋﻞ ﻣﻊ اﻟﺴﻜﺎن اﻟﻤﺤﻠﯿﯿﻦ واﻟﺘﻌﺮف
ﻋﻠﻰ اﻟﺜﻘﺎﻓﺔ اﻟﻤﺤﻠﯿﺔ . ﻓﻲ أي ﻣﻮاﻗﻊ ﺳﯿﺎﺣﯿﺔ ﻣﻌﺮوﻓﺔ ﻓﻲ اﻟﺼﻮرة دي؟
🇲🇷
اﻟﻠﺤﻢ اﻟﻤﺸﻐﻞ ﻓﻲ ھﺬي اﻟﻮﺟﺒﺔ ھﻮ اﻟﺪﺟﺎج . ﺷﻨﮫﻮ ﻧﻮع اﻟﻠﺤﻢ اﻟﻲ ﻣﺸﻐﻞ ﻓﻲ ھﺬي اﻟﻮﺟﺒﺔ اﻟﻲ ﻓﻲ اﻟﺼﻮرة؟
🇸🇦
ﻓﻲ ﺟﺒﻞ ﻛﺒﯿﺮ ﺑﺎﻳﻦ ﻓﻲ اﻟﺼﻮرة ورا اﻟﻤﺒﺎﻧﻲ اﻟﻠﻲ ﻋﻠﯿﮫﺎ ﻧﻮر . اﻳﺶ ﻧﺸﻮف ﻓﻮق ﺑﺎﻟﺼﻮرة ورا اﻟﻤﺒﺎﻧﻲ اﻟﻠﻲ ﻋﻠﯿﮫﺎ ﻧﻮر؟
اﻟﺴﻤﺎء ﻓﻲ اﻟﺼﻮرة زرﻗﺎء ﻣﻊ ﺑﻌﺾ اﻟﺴﺤﺐ، وھﺬا ﻳﺪل ﻋﻠﻰ أن اﻟﻮﻗﺖ ﻟﯿﻞ واﻟﻨﺎس
ﻳﺘﺠﻤﻌﻮن ﻗﺪام ﻣﺒﻨﻰ ﻛﺒﯿﺮ . اﻳﺶ ﻳﻌﻨﻲ ﻟﻚ ﻟﻮن اﻟﺴﻤﺎء ﺑﺎﻟﺼﻮرة؟
🇵🇸
اﻟﺸﺨﺺ اﻟﻲ ﺑﺎﻟﺼﻮرة ﻻﺑﺲ ﺛﻮب ﻋﺮﺑﻲ، اﻟﻲ ﻣﻤﻜﻦ ﻳﻜﻮن ﺟﺰء ﻣﻦ اﻟﺰي اﻟﺨﻠﯿﺠﻲ . ﺷﻮ ﻧﻮع اﻟﺜﻮب اﻟﻲ ﻻﺑﺴﻪ اﻟﺸﺨﺺ اﻟﻲ ﺑﺎﻟﺼﻮرة؟
🇾🇪
Figure 11: Examples of Dallah’s answers in different dialects from the evaluation datasets.
اﻳﺶ ھﻮ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎي اﻟﺼﻮرة؟
اﻳﻪ ھﻮ اﻟﻐﺮﻳﺐ ﻓﻲ اﻟﺼﻮرة دي؟
ﺷﻮ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎي اﻟﺼﻮرة؟
اﻟﺠﺎﻧﺐ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎي اﻟﺼﻮرة ھﻮ وﺟﻮد ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺔ ﻓﻮق ﺷﺠﺮة ﻣﺰھﺮة. اﻟﻘﻄﻂ ﻋﻤﻮﻣﺎً ﻣﺶ
ﺣﯿﻮاﻧﺎت زھﻮر وﺑﺘﻜﻮن ﻓﻲ اﻷﻣﺎﻛﻦ اﻟﻌﺎدﻳﺔ، زي اﻟﺤﻤﺎﻣﺎت أو اﻷﺣﻮاض أو اﻷﻣﺎﻛﻦ اﻟﻤﻐﻠﻘﺔ. ﻣﺶ ﻣﺸﮫﺪ ﻋﺎدي
اﻧﻚ ﺗﺸﻮف ﻗﻄﺔ واﻗﻔﺔ ﻋﻠﻰ ﺷﺠﺮة ﻓﯿﮫﺎ زھﻮر أو ﺷﺠﺮة ﻓﯿﮫﺎ ﺷﺠﺮ. وﺟﻮد اﻟﻘﻄﺔ ﻓﻲ ھﺬا اﻟﻤﻜﺎن ﻏﯿﺮ ﻣﻌﺘﺎد
وﺑﯿﺜﯿﺮ اﻟﻔﻀﻮل.
آﺷﻨﻮ ھﻮّ ﻟْﻌﺠﯿﺐ ﻓﮫﺎد ﻟﺘﺼﻮﻳﺮة؟
آش ﻛﺮﻳﺐ ﻓﮫﺎد اﻟﺼﻮرة ھﻮ ﺗﺼﻮﻳﺮة ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺎء ﻛﺎﺗﺠﻠﺲ ﻓﻮق ﻏﺼﻦ ﺷﺠﺮة ﻣﻠﯿﺎﻧﺔ زھﻮر. اﻟﻘﻄﺔ ﻛﺎﻳﻨﺔ
ﻋﻠﻰ طﺮف اﻟﻐﺼﻦ، واﻟﻜﺎب دﻳﺎﻟﮫﺎ ﻛﺎﻳﺒﺎن ﻓﺎﻟﺴﻤﺎء اﻟﺼﺎﻓﯿﺔ اﻟﻔﻮﻻذﻳﺔ ﻣﻦ ﺗﺤﺘﮫﺎ. اﻟﻈﻼل واﻟﺘﻔﺎﻋﻞ ﺑﯿﻦ اﻟﻘﻄﺔ
واﻟﺨﻠﻔﯿﺔ ﻛﺎﻳﺨﻠﻘﻮ ﺻﻮرة ﻣﻠﻔﺘﺔ ﻟﻠﻨﻈﺮ وﺟﺬاﺑﺔ ﺑﺼﺮﻳًﺎ. اﻟﻘﻄﺔ ﻛﺎﺗﺎﺧﺪ ﻣﺮﻛﺰ اﻟﺼﺪارة ﻓﺎﻟﺼﻮرة، ﺑﯿﻨﻤﺎ أوراق اﻟﺸﺠﺮ
واﻟﺰھﻮر ﻛﺎﺗﺰﻳﺪ ﻣﻦ اﻹﺣﺴﺎس ﺑﺎﻟﻄﺒﯿﻌﺔ واﻟﮫﺪوء. ھﺎد اﻟﺘﺼﻮﻳﺮة ﻛﺎﺗﺒﯿﻦ ﺑﻠﻲ اﻟﻘﻄﺔ ﺗﺤﺐ اﻟﺠﻠﻮس ﻓﻮق
اﻷﺷﺠﺎر أو رﺑﻤﺎ ﻛﺎﺗﺤﺐ ﺗﺴﺘﻤﺘﻊ ﺑﺎﻟﻤﻨﻈﺮ أو اﻟﻀﻮء.
اﻳﺶ اﻟﻐﺮﻳﺐ ﺑﺎﻟﺼﻮرة ھﺬي؟
اﻟﺠﺎﻧﺐ اﻟﻐﺮﻳﺐ ﺑﺎﻟﺼﻮرة ھﺬي ھﻮ وﺟﻮد ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺎء ﻓﻮق ﺷﺠﺮة ﻣﺰھﺮة. ﻋﺎدة ﻣﺎ ﺗﻜﻮن اﻟﻘﻄﻂ
ﺣﯿﻮاﻧﺎت داﺧﻠﯿﺔ، وﺑﺘﺤﺐ ﺗﺴﺘﺮﺧﻲ ﻋﻠﻰ اﻟﻔﺮش أو اﻷﺳﺮة أو أي ﺳﻄﺢ داﺧﻠﻲ ﺗﺎﻧﻲ. ﻣﺎ ﺗﺸﻮف ﻗﻄﺔ واﻗﻔﺔ
ﻋﻠﻰ ﺷﺠﺮة ﺑﺸﻜﻞ ﻣﻨﺘﻈﻢ، ﺧﺎﺻﺔ ﺷﺠﺮة ﻓﯿﮫﺎ زھﻮر ﺑﺘﺰﻳﺪ ﻣﻦ اﻟﻤﻨﻈﺮ اﻟﻐﯿﺮ ﻋﺎدي. اﻟﻘﻄﺔ اﻟﻠﻲ ﻓﻲ اﻟﺼﻮرة
ﺑﺘﺘﻄﻠﻊ ﻣﺒﺎﺷﺮة ﻟﻠﻜﺎﻣﯿﺮا، وھﺬا ﺑﯿﺰﻳﺪ ﻣﻦ اﻟﺘﺄﻛﯿﺪ ﻋﻠﻰ اﻟﻤﻨﻈﺮ اﻟﻔﺮﻳﺪ. اﻟﺼﻮرة ﺑﺘﺒﯿﻦ ﻓﻀﻮل اﻟﻘﻄﺔ واﻧﺠﺬاﺑﮫﺎ
ﻟﻠﻤﻜﺎن اﻟﺨﺎرﺟﻲ.
ﺷﻨﮫﻮ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎﻟﺼﻮرة؟
اﻟﺠﺎﻧﺐ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎﻟﺼﻮرة ھﻮ وﺟﻮد ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺔ ﺟﺎﻟﺴﺔ ﻋﻠﻰ ﻏﺼﻦ ﺷﺠﺮة ﻣﺰھﺮ. ﻟﯿﺲ ﻣﻦ
اﻟﺸﺎﺋﻊ أن ﺗﺸﻮف ﻗﻄﻂ ﺟﺎﻟﺴﺔ ﻋﻠﻰ أﻏﺼﺎن اﻷﺷﺠﺎر اﻟﻤﺰھﺮة، ﺣﯿﺚ أن اﻟﻘﻄﻂ ﻋﺎدة ﺗﻔﻀﻞ اﻟﺠﻠﻮس ﻋﻠﻰ
اﻷﺳﻄﺢ اﻟﺼﻠﺒﺔ ﻣﺜﻞ اﻷرﺿﯿﺎت أو اﻷﺛﺎث. ﺑﺎﻹﺿﺎﻓﺔ إﻟﻰ ذﻟﻚ، ﻓﺈن وﺟﻮد اﻟﻘﻄﺔ وﺳﻂ اﻟﺰھﻮر اﻟﺠﻤﯿﻠﺔ ﻳﻀﯿﻒ
ﻟﻤﺴﺔ ﻏﺮﻳﺒﺔ ﻟﻠﻤﺸﮫﺪ.
اﻟﺠﺎﻧﺐ اﻟﻐﺮﻳﺐ ﻓﻲ ھﺎي اﻟﺼﻮرة ھﻮ وﺟﻮد ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺎء ﻓﻮق ﺷﺠﺮة ﻣﺰھﺮة. اﻟﻘﻄﻂ ﻋﻤﻮﻣﺎً ﻣﺶ
ﺣﯿﻮاﻧﺎت ﺑﺘﻔﺮح ﺑﺎﻟﺘﺴﻠﻖ ﻋﻠﻰ اﻷﺷﺠﺎر، ﺧﺎﺻﺔ ﻟﻤﺎ ﺗﻜﻮن ﻓﯿﮫﺎ زھﻮر أو ﺛﻤﺎر. ﻣﻤﻜﻦ ﻳﻜﻮن ھﺬا اﻟﻤﻨﻈﺮ ﻏﯿﺮ
ﻋﺎدي ﻻن اﻟﻘﻄﻂ ﻣﺶ ﻋﻤﻮﻣﺎً ﺑﺘﺘﻔﺎﻋﻞ ﻣﻊ اﻟﺒﯿﺌﺔ اﻟﺰھﺮﻳﺔ أو ﺑﺘﺘﻔﺎﻋﻞ ﻣﻊ اﻟﺜﻤﺮة اﻟﻤﻮﺟﻮدة ﻋﻠﻰ اﻟﺸﺠﺮة.
ﻛﻤﺎن، اﻟﻘﻄﻂ ﻋﻤﻮﻣﺎً ﻣﺶ ﺣﯿﻮاﻧﺎت ﺑﺘﺘﻔﺎﻋﻞ ﻣﻊ اﻷﺷﺠﺎر، ﻻﻧﮫﺎ ﺑﺘﺴﺘﺨﺪم ﻣﺨﺎﻟﺒﮫﺎ ﻋﺸﺎن ﺗﺘﺴﻠﻖ ﺑﺲ!
اﻟﺠﺎﻧﺐ اﻟﻐﺮﻳﺐ ﻓﻲ اﻟﺼﻮرة دي ھﻮ وﺟﻮد ﻗﻄﺔ ﺑﺮﺗﻘﺎﻟﯿﺔ وﺑﯿﻀﺎء ﻓﻮق ﺷﺠﺮة أزھﺎر ﺑﺒﺘﻼت زھﻮر وردﻳﺔ اﻟﻠﻮن.
اﻟﻘﻄﻂ ﻣﺶ ﺑﺘﺘﻌﻠﻖ ﺑﺎﻷﺷﺠﺎر ﻋﺎدةً، ودا أﻣﺮ ﻏﯿﺮ ﻣﻌﺘﺎد ﻷن اﻟﻘﻄﻂ ﺗﻔﻀﻞ ﻏﺎﻟﺒًﺎ اﻟﺠﻠﻮس ﻋﻠﻰ اﻷﺳﻄﺢ
اﻟﻤﺴﺘﻮﻳﺔ زي اﻷﺳﺮة أو اﻟﻜﺮاﺳﻲ أو اﻟﻄﺎوﻻت. وﻛﻤﺎن اﻟﻘﻄﻂ ﺣﯿﻮاﻧﺎت ﻣﻔﺘﺮﺳﺔ ﺑﻄﺒﯿﻌﺘﮫﺎ، ﻓﺈﻧﮫﺎ ﺑﺘﺤﺐ
ﺗﺴﺘﻜﺸﻒ اﻟﻤﻨﺎطﻖ اﻟﻤﺤﯿﻄﺔ ﺑﮫﺎ، وﻛﻤﺎن ﻣﻤﻜﻦ ﺗﻜﻮن اﻟﻘﻄﺔ اﻟﻤﻮﺟﻮدة ﻓﻲ اﻟﺼﻮرة ﻓﻀﻮﻟﯿﺔ أو ﺣﺘﻰ ﻣﻨﺠﺬﺑﺔ
ﻟﻠﺒﺘﻼت اﻟﻮردﻳﺔ اﻟﻤﻮﺟﻮدة ﻋﻠﻰ اﻟﺸﺠﺮة.Figure 12: In this examples, Dallah was asked ”What is the strange thing in this picture?” using six different
dialects. Dallah responded to each question in the corresponding dialect, demonstrating a degree of dialectness.
The responses conveyed the same meaning with slight variations across the different dialects. | Section not found | Section not found | Section not found | Section not found | Section not found |