ZHANGYUXUAN-zR commited on
Commit
bab7525
·
verified ·
1 Parent(s): 8725a52

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. parse/test/5a79AqFr0c/5a79AqFr0c.md +327 -0
  2. parse/test/5a79AqFr0c/5a79AqFr0c_content_list.json +719 -0
  3. parse/test/5a79AqFr0c/5a79AqFr0c_middle.json +0 -0
  4. parse/test/5a79AqFr0c/5a79AqFr0c_model.json +0 -0
  5. parse/test/Fq8tKtjACC/Fq8tKtjACC.md +509 -0
  6. parse/test/Fq8tKtjACC/Fq8tKtjACC_content_list.json +1036 -0
  7. parse/test/Fq8tKtjACC/Fq8tKtjACC_middle.json +0 -0
  8. parse/test/Fq8tKtjACC/Fq8tKtjACC_model.json +0 -0
  9. parse/test/OqlmgmS4Wr/OqlmgmS4Wr.md +835 -0
  10. parse/test/OqlmgmS4Wr/OqlmgmS4Wr_content_list.json +0 -0
  11. parse/test/OqlmgmS4Wr/OqlmgmS4Wr_middle.json +0 -0
  12. parse/test/OqlmgmS4Wr/OqlmgmS4Wr_model.json +0 -0
  13. parse/test/RXFVcynVe1/RXFVcynVe1.md +538 -0
  14. parse/test/RXFVcynVe1/RXFVcynVe1_content_list.json +0 -0
  15. parse/test/RXFVcynVe1/RXFVcynVe1_middle.json +0 -0
  16. parse/test/RXFVcynVe1/RXFVcynVe1_model.json +0 -0
  17. parse/test/UU9Icwbhin/UU9Icwbhin.md +304 -0
  18. parse/test/UU9Icwbhin/UU9Icwbhin_content_list.json +684 -0
  19. parse/test/UU9Icwbhin/UU9Icwbhin_middle.json +0 -0
  20. parse/test/UU9Icwbhin/UU9Icwbhin_model.json +0 -0
  21. parse/test/Vi8AepAXGy/Vi8AepAXGy.md +0 -0
  22. parse/test/Vi8AepAXGy/Vi8AepAXGy_content_list.json +0 -0
  23. parse/test/Vi8AepAXGy/Vi8AepAXGy_middle.json +0 -0
  24. parse/test/Vi8AepAXGy/Vi8AepAXGy_model.json +0 -0
  25. parse/test/ZPQhzTSWA7/ZPQhzTSWA7.md +0 -0
  26. parse/test/ZPQhzTSWA7/ZPQhzTSWA7_content_list.json +0 -0
  27. parse/test/ZPQhzTSWA7/ZPQhzTSWA7_middle.json +0 -0
  28. parse/test/ZPQhzTSWA7/ZPQhzTSWA7_model.json +0 -0
  29. parse/test/dsUB4bst9S/dsUB4bst9S.md +0 -0
  30. parse/test/dsUB4bst9S/dsUB4bst9S_content_list.json +0 -0
  31. parse/test/dsUB4bst9S/dsUB4bst9S_middle.json +0 -0
  32. parse/test/dsUB4bst9S/dsUB4bst9S_model.json +0 -0
  33. parse/test/fvhJu0FODp/fvhJu0FODp.md +0 -0
  34. parse/test/fvhJu0FODp/fvhJu0FODp_content_list.json +0 -0
  35. parse/test/fvhJu0FODp/fvhJu0FODp_middle.json +0 -0
  36. parse/test/fvhJu0FODp/fvhJu0FODp_model.json +0 -0
  37. parse/test/nnVO1PvbTv/nnVO1PvbTv.md +0 -0
  38. parse/test/nnVO1PvbTv/nnVO1PvbTv_content_list.json +0 -0
  39. parse/test/nnVO1PvbTv/nnVO1PvbTv_middle.json +0 -0
  40. parse/test/nnVO1PvbTv/nnVO1PvbTv_model.json +0 -0
  41. parse/test/pyW37euNXb/pyW37euNXb.md +349 -0
  42. parse/test/pyW37euNXb/pyW37euNXb_content_list.json +820 -0
  43. parse/test/pyW37euNXb/pyW37euNXb_middle.json +0 -0
  44. parse/test/pyW37euNXb/pyW37euNXb_model.json +0 -0
  45. parse/test/xbjSwwrQOe/xbjSwwrQOe.md +539 -0
  46. parse/test/xbjSwwrQOe/xbjSwwrQOe_content_list.json +0 -0
  47. parse/test/xbjSwwrQOe/xbjSwwrQOe_middle.json +0 -0
  48. parse/test/y886UXPEZ0/y886UXPEZ0.md +0 -0
  49. parse/test/y886UXPEZ0/y886UXPEZ0_content_list.json +0 -0
  50. parse/test/y886UXPEZ0/y886UXPEZ0_model.json +0 -0
parse/test/5a79AqFr0c/5a79AqFr0c.md ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CONTROLVIDEO: TRAINING-FREE CONTROLLABLE TEXT-TO-VIDEO GENERATION
2
+
3
+ Yabo Zhang1 Yuxiang Wei1 Dongsheng Jiang2 Xiaopeng Zhang2 Wangmeng Zuo1 $( \boxtimes )$ Qi Tian2
4
+
5
+ 1Harbin Institute of Technology 2Huawei Cloud
6
+
7
+ # ABSTRACT
8
+
9
+ Text-driven diffusion models have unlocked unprecedented abilities in image generation, whereas their video counterpart lags behind due to the excessive training cost. To avert the training burden, we propose a training-free ControlVideo to produce high-quality videos based on the provided text prompts and motion sequences. Specifically, ControlVideo adapts a pre-trained text-to-image model (i.e., ControlNet) for controllable text-to-video generation. To generate continuous videos without flicker effects, we propose an interleaved-frame smoother to smooth the intermediate frames. In particular, interleaved-frame smoother splits the whole video with successive three-frame clips, and stabilizes each clip by updating the middle frame with the interpolation among other two frames in latent space. Furthermore, a fully cross-frame interaction mechanism is exploited to further enhance the frame consistency, while a hierarchical sampler is employed to produce long videos efficiently. Extensive experiments demonstrate that our ControlVideo outperforms the state-of-the-arts both quantitatively and qualitatively. It is worth noting that, thanks to the efficient designs, ControlVideo could generate both short and long videos within several minutes using one NVIDIA 2080Ti. Code and videos are available at this link.
10
+
11
+ # 1 INTRODUCTION
12
+
13
+ Large-scale diffusion models have made a tremendous breakthrough on text-to-image synthesis (Nichol et al., 2021; Rombach et al., 2022; Balaji et al., 2022; Ramesh et al., 2022; Saharia et al., 2022) and their creative applications (Gal et al., 2022; Wei et al., 2023; Ni et al., 2022; Hertz et al., 2022). Several studies (Ho et al., 2022b;a; Singer et al., 2022; Esser et al., 2023; Hong et al., 2022) attempt to replicate this success in the video counterpart, i.e., modeling higher-dimensional complex video distributions in the wild world. However, training such a text-to-video model requires massive amounts of high-quality videos and computational resources, which limits further research and applications by relevant communities.
14
+
15
+ In this work, we study a new and efficient form to avert the excessive training requirements: controllable text-to-video generation with text-to-image models. As shown in Fig. 1, our method, termed ControlVideo, takes textual description and motion sequence (e.g., depth or edge maps) as conditions to generate videos. Instead of learning the video distribution from scratch, ControlVideo adapts the pre-trained text-to-image models (e.g., ControlNet (Zhang & Agrawala, 2023)) for high-quality video generation. With the structural information from motion sequence and the superior generation capability of image models, it is feasible to produce a vivid video without additional training.
16
+
17
+ However, as shown in Fig. 1, due to the lack of temporal interaction, individually producing each frame with ControlNet (Zhang & Agrawala, 2023) fails to ensure both (i) frame consistency and (ii) video continuity. Frame consistency requires all frames to be generated with a coherent appearance, while video continuity ensures smooth transitions between frames. Tune-A-Video (Wu et al., 2022b) and Text2Video-Zero (Khachatryan et al., 2023) facilitate appearance consistency by extending self-attention to sparser cross-frame attention. Nonetheless, such a cross-frame interaction is not sufficient to guarantee video continuity, and visible flickers appear in their synthesized videos (as shown in Fig. 1 and corresponding videos).
18
+
19
+ ![](images/d1c94a87f431ed8decf8708008be42280186424c7cb94567abd7cf4cf5dcc95b.jpg)
20
+ Figure 1: Training-free controllable text-to-video generation. Left: We visualize the frames and x-t slice (pixels in red line of original frame) of Text2Video-Zero, and observe visible discontinuity in $x$ -t slice. Right: ControlVideo, adapted from ControlNet, achieves more continuous $x { - } t$ slice across time, along with improved appearance consistency than Text2Video-Zero. See videos for better view.
21
+
22
+ Intuitively, a continuous video could be considered as multiple continuous three-frame clips, so the problem of ensuring the video continuity is converted to ensuring all three-frame clips continuous. Driven by this analysis, we propose an interleaved-frame smoother to enable continuous video generation. Specifically, interleaved-frame smoother divides all three-frame clips into even and odd clips based on indices of middle frames, and separately smooths out their corresponding latents at different denoising steps. To stabilize the latent of each clip, we first convert it to predicted RGB frames with DDIM, followed by replacing the middle frame with the interpolated frame. Note that, the smoother is only applied at a few timesteps, and the quality and individuality of interpolated frames can be well retained by the following denoising steps.
23
+
24
+ We further investigate the cross-frame mechanisms in terms of effectiveness and efficiency. Firstly, we explore fully cross-frame interaction that concatenates all frames to become a “larger image”, and first empirically demonstrate its superior consistency and quality than sparser counterparts (see Sec. 4.4). Secondly, applying existing cross-frame mechanisms for long-video generation suffers from either heavy computational burden or long-term inconsistency. Therefore, a hierarchical sampler is presented to produce a long video in a top-down way. In specific, it pre-generates the key frames with fully cross-frame attention for long-range coherence, followed by efficiently generating the short clips conditioned on pairs of key frames.
25
+
26
+ We conduct the experiments on extensively collected motion-prompt pairs, and show that ControlVideo outperforms alternative competitors qualitatively and quantitatively. Thanks to the efficient designs, ControlVideo produces short and long videos in several minutes using one NVIDIA 2080Ti.
27
+
28
+ In summary, our contributions are presented as follows:
29
+
30
+ • We propose training-free ControlVideo with interleaved-frame smoother for consistent and continuous controllable text-to-video generation.
31
+ • Interleaved-frame smoother alternately smooths out the latents of three-frame clips, effectively stabilizing the entire video during sampling.
32
+ • We empirically demonstrate the superior consistency and quality of fully cross-frame interaction, while presenting a hierarchical sampler for long-video generation in commodity GPUs.
33
+
34
+ # 2 BACKGROUND
35
+
36
+ Latent diffusion model (LDM) (Rombach et al., 2022) is an efficient variant of diffusion models (Ho et al., 2020) by applying the diffusion process in the latent space. LDM uses an encoder to compress an image $_ { \textbf { \em x } }$ into latent code $z = ( { \pmb x } )$ . It learns the distribution of image latent codes $z _ { 0 } \sim p _ { d a t a } ( z _ { 0 } )$ in a DDPM formulation (Ho et al., 2020), including a forward and a backward process. The forward diffusion process gradually adds gaussian noise at each timestep $t$ to obtain ${ \boldsymbol { z } } _ { t }$ :
37
+
38
+ $$
39
+ q ( z _ { t } | z _ { t - 1 } ) = \mathcal { N } ( z _ { t } ; \sqrt { 1 - \beta _ { t } } z _ { t - 1 } , \beta _ { t } I ) ,
40
+ $$
41
+
42
+ ![](images/be5a86338f5f0690c18fbffc176104780b244c71015a3a6e2bcaf751230024ca.jpg)
43
+ Figure 2: Overview of ControlVideo. For consistency in appearance, ControlVideo adapts ControlNet to the video counterpart by adding cross-frame interaction into self-attention modules. To further improve video continuity, interleaved-frame smoother is introduced to stabilize video latents during denosing (see Alg. 1 for details).
44
+
45
+ where $\{ \beta _ { t } \} _ { t = 1 } ^ { T }$ are the scale of noises, and $T$ denotes the number of diffusion timesteps. The backward denoising process reverses the above diffusion process to predict less noisy $z _ { t - 1 }$ :
46
+
47
+ $$
48
+ p _ { \theta } ( z _ { t - 1 } | z _ { t } ) = \mathcal { N } ( z _ { t - 1 } ; \mu _ { \theta } ( z _ { t } , t ) , \Sigma _ { \theta } ( z _ { t } , t ) ) .
49
+ $$
50
+
51
+ The $\mu _ { \theta }$ and $\Sigma _ { \theta }$ are implemented with a denoising model $\epsilon _ { \theta }$ with learnable parameters $\theta$ . When generating new samples, we start from $z _ { T } \sim \mathcal { N } ( 0 , 1 )$ and employ DDIM sampling to predict $z _ { t - 1 }$ of previous timestep:
52
+
53
+ $$
54
+ \begin{array} { r } { z _ { t - 1 } = \sqrt { \alpha _ { t - 1 } } \underbrace { \left( \frac { z _ { t } - \sqrt { 1 - \alpha _ { t } } \epsilon _ { \theta } ( z _ { t } , t ) } { \sqrt { \alpha _ { t } } } \right) } _ { \substack { \mathrm { ~ \triangleq ~ p r e d i c t e d } z _ { 0 } \mathrm { , ~ } } } + \underbrace { \sqrt { 1 - \alpha _ { t - 1 } } \cdot \epsilon _ { \theta } ( z _ { t } , t ) } _ { \substack { \mathrm { ~ \triangleq ~ d i r e c t i o n ~ p o i n t i n g ~ t o ~ } z _ { t } \mathrm { , ~ } } } , } \end{array}
55
+ $$
56
+
57
+ where $\begin{array} { r } { \alpha _ { t } = \prod _ { i = 1 } ^ { t } ( 1 - \beta _ { i } ) } \end{array}$ . We use $z _ { t 0 }$ to represent “predicted $z _ { \mathrm { 0 } } ^ { \mathrm { , , } }$ at timestep $t$ for simplicity. Note that we use Stable Diffusion (SD) $\epsilon _ { \theta } ( z _ { t } , t , \tau )$ as our base model, which is an instantiation of text-guided LDMs pre-trained on billions of image-text pairs. $\tau$ denotes the text prompt.
58
+
59
+ ControlNet (Zhang & Agrawala, 2023) enables SD to support more controllable input conditions during text-to-image synthesis, e.g., depth maps, poses, edges, etc. The ControlNet uses the same U-Net (Ronneberger et al., 2015) architecture as SD and finetunes its weights to support taskspecific conditions, converting $\epsilon _ { \theta } ( z _ { t } , t , \tau )$ to $\epsilon _ { \theta } ( z _ { t } , t , c , \tau )$ , where $^ c$ denotes additional conditions. To distinguish the U-Net architectures of SD and ControlNet, we denote the former as the main $U _ { ☉ }$ -Net while the latter as the auxiliary $U$ -Net.
60
+
61
+ # 3 CONTROLVIDEO
62
+
63
+ Controllable text-to-video generation aims to produce a video of length $N$ conditioned on motion sequences $\boldsymbol { c } = \{ c ^ { i } \} _ { i = 0 } ^ { N - 1 }$ and a text prompt $\tau$ . As illustrated in Fig. 2, we propose ControlVideo with interleaved-frame smoother towards consistent and continuous video generation. ControlVideo, adapted from ControlNet, adds cross-frame interaction to self-attention modules for frame consistency (in Sec. 3.1). To ensure video continuity, interleaved-frame smoother divides all three-frame clips into even and odd clips, and separately smooths out their corresponding latents at different denoising steps (in Sec. 3.2). Finally, we further investigate the cross-frame mechanisms in terms of effectiveness and efficiency, including fully cross-frame interaction and hierarchical sampler (in Sec. 3.3).
64
+
65
+ # 3.1 PRELIMINARY
66
+
67
+ The main challenge of adapting text-to-image models to the video counterpart is to ensure temporal consistency. Leveraging the controllability of ControlNet, motion sequences could provide coarselevel consistency in structure. Nonetheless, due to the lack of temporal interaction, individually producing each frame with ControlNet leads to drastic inconsistency in appearance (see row 2 in
68
+
69
+ # Algorithm 1 Interleaved-frame smoother
70
+
71
+ Require: $z _ { t } = \{ z _ { t } ^ { i } \} _ { i = 0 } ^ { N - 1 }$ , $\boldsymbol { c } = \{ c ^ { i } \} _ { i = 0 } ^ { N - 1 }$ , τ , timestep t.
72
+ 1: zt→0 ← zt− 1−αtϵθ(zt,t,c,τ )√ . ▷ predict clean latents 2: $\pmb { x } _ { t 0 } \mathscr { D } ( \pmb { z } _ { t 0 } ) ; \tilde { \pmb { x } } _ { t 0 } \pmb { x } _ { t 0 }$ ▷ convert latents to $R G B$ space 3: if $( t \ \mathrm { ~ m o d ~ } 2 ) = 0$ then $\triangleright$ smooth all even three-frame clips $\cdot$ 4: for $\cdot$ from 0 to $\cdot$ do
73
+ 5: x˜2kt→0 ← Interpolate(x2k−1t→0 , x2k+1t→0 ) oth all odd three-frame clips
74
+ 6: else if $( t \ \mathrm { ~ m o d ~ } 2 ) = 1$ then $\triangleright$ $( \tilde { x } _ { t 0 } ^ { 2 k } , \tilde { x } _ { t 0 } ^ { 2 k + 1 } , \tilde { x } _ { t 0 } ^ { 2 k + 2 } )$ $k$ $N / 2$
75
+ $\begin{array} { r l r } { \} : } & { { } \lfloor } & { \tilde { \boldsymbol { x } } _ { t 0 } ^ { 2 k + 1 } \mathrm { I n t e r p o l a t e } ( \boldsymbol { x } _ { t 0 } ^ { 2 k } , \boldsymbol { x } _ { t 0 } ^ { 2 k + 2 } ) } \end{array}$
76
+ 9: $\tilde { z } _ { t 0 } \mathcal { E } ( \tilde { x } _ { t 0 } )$ ▷ convert frames to latent space 10: $z _ { t - 1 } \gets \sqrt { \alpha _ { t - 1 } } \tilde { z } _ { t \to 0 } + \sqrt { 1 - \alpha _ { t - 1 } } \cdot \epsilon _ { \theta } ( z _ { t } , t , c , \tau ) .$ . ▷ predict less noisy latent 11: return zt−1
77
+
78
+ Fig. 5). Similar to previous works (Wu et al., 2022b; Khachatryan et al., 2023), we also extend original self-attention of SD U-Net to cross-frame attention, so that the video content could be temporally shared via inter-frame interaction.
79
+
80
+ In specific, ControlVideo inflates the main U-Net from Stable Diffusion along the temporal axis, while keeping the auxiliary U-Net from ControlNet. Analogous to (Ho et al., 2022b; Wu et al., 2022b; Khachatryan et al., 2023), it directly converts 2D convolution layers to 3D counterpart by replacing $3 \times 3$ kernels with $1 \times 3 \times 3$ kernels. Self-attention is converted to cross-frame attention by querying from other frames as:
81
+
82
+ $$
83
+ \mathrm { A t t e n t i o n } ( Q , K , V ) = \mathrm { S o f t m a x } \big ( \frac { Q K ^ { T } } { \sqrt { d } } \big ) \cdot V , \mathrm { ~ w h e r e ~ } Q = W ^ { Q } z _ { t } ^ { i } , ~ K = W ^ { K } \tilde { z } _ { t } , ~ V = W ^ { V } \tilde { z } _ { t } ,
84
+ $$
85
+
86
+ where $W ^ { Q } , W ^ { K }$ , and $W ^ { V }$ project ${ \boldsymbol { z } } _ { t }$ into query, key, and value, respectively. $ { \boldsymbol { z } } _ { t } ^ { i }$ and $\widetilde { z } _ { t }$ denote ith latent frame and the latents of reference frames at timestep $t$ e. We will discuss the choices of cross-frame mechanisms (i.e., reference frames) in Sec. 3.3
87
+
88
+ # 3.2 INTERLEAVED-FRAME SMOOTHER
89
+
90
+ Albeit cross-frame interaction promisingly keeps frame consistency in appearance, they are still visibly flickering in structure. Discrete motion sequences only ensure coarse-level structural consistency, not sufficient to keep the continuous inter-frame transition. Intuitively, a continuous video could be considered as multiple continuous three-frame clips, so we simplify the problem of ensuring the video continuity to ensuring all three-frame clips continuous.
91
+
92
+ Inspired by this, we propose an interleaved-frame smoother to enable continuous video generation. In Alg. 1, interleaved-frame smoother divides all three-frame clips into even and odd clips based on indices of middle frames, and individually smooths their corresponding latents at different timesteps. To stabilize the latent of each clip, we first convert it to predicted RGB frames with DDIM, following by replacing middle frame with the interpolated frame.
93
+
94
+ Specifically, at timestep $t$ , we first predict the clean video latent $z _ { t 0 }$ according to ${ \boldsymbol { z } } _ { t }$
95
+
96
+ $$
97
+ z _ { t 0 } = \frac { z _ { t } - \sqrt { 1 - \alpha _ { t } } \epsilon _ { \theta } ( z _ { t } , t , c , \tau ) } { \sqrt { \alpha _ { t } } } .
98
+ $$
99
+
100
+ After projecting $z _ { t 0 }$ into a RGB video ${ \pmb x } _ { t 0 } = \mathcal { D } ( { \pmb z } _ { t 0 } )$ , we convert it to a more smoothed video $\tilde { \mathbf { x } } _ { t 0 }$ by replacing each middle frame with the interpolated one. Based on smoothed video latent $\tilde { z } _ { t 0 } = \mathcal { E } ( \tilde { { x } } _ { t 0 } )$ , we compute the less noisy latent $z _ { t - 1 }$ following DDIM denoising in Eq. 3:
101
+
102
+ $$
103
+ z _ { t - 1 } = \sqrt { \alpha _ { t - 1 } } \tilde { z } _ { t 0 } + \sqrt { 1 - \alpha _ { t - 1 } } \cdot \epsilon _ { \theta } ( z _ { t } , t , c , \tau ) .
104
+ $$
105
+
106
+ We note that the above process is only performed at a few intermediate timesteps, the individuality and quality of interpolated frames are also well retained by the following denoising steps. Additionally, the newly computational burden can be negligible (See Table 3).
107
+
108
+ ![](images/bd1ecad5220209f938742c14bf7b9e45c444bf29c8c74cb82af70d240a2ebee5.jpg)
109
+ Figure 3: Qualitative comparisons conditioned on depth maps and canny edges. Our ControlVideo produces videos with better (a) appearance consistency and (b) video quality than others. In contrast, Tune-A-Video fails to inherit structures from source videos, while Text2Video-Zero brings visible artifacts in large motion videos. See videos at qualitative comparisons.
110
+
111
+ # 3.3 CROSS-FRAME MECHANISMS FOR EFFECTIVENESS AND EFFICIENCY
112
+
113
+ Fully cross-frame interaction. Previous works (Wu et al., 2022b; Khachatryan et al., 2023) usually replace self-attention with sparser cross-frame mechanisms, e.g., taking the reference frames as first or previous frames. Such mechanisms will increase the discrepancy between the query and key in self-attention modules, resulting in the degradation of video quality and consistency. In contrast, fully cross-frame interaction considers all frames as reference (i.e., becoming a “large image”), so has a less generation gap with text-to-image models. We conduct comparison experiments on above mechanisms in Fig. 5 and Table 3. Despite slightly more computational burden, fully cross-frame interaction empirically shows better consistency and quality than the sparser counterparts.
114
+
115
+ Hierarchical sampler. Applying existing cross-frame mechanisms for long-video generation suffers from either heavy computational burden or long-term inconsistency, limiting the practicability of ControlVideo. For more efficient long-video synthesis, we introduce a hierarchical sampler to produce a long video clip-by-clip, which is implemented with two types of cross-frame mechanisms. At each timestep, a long video $\bar { z } _ { t } = \{ z _ { t } ^ { i } \} _ { i = 0 } ^ { N - 1 }$ is separated into multiple short video clips with the selected kedenoted as $z _ { t } ^ { k e y } = \{ z _ { t } ^ { k N _ { c } } \} _ { k = 0 } ^ { \frac { N } { N _ { c } } }$ , where each clip is of length , we pre-generate the key fra $N _ { c } - 1$ and the h fully c $k$ th clip isss-frame $\widehat { \pmb { z } } _ { t } ^ { k } = \{ { \pmb z } _ { t } ^ { j } \} _ { j = k N _ { c } + 1 } ^ { ( k + 1 ) N _ { c } - 1 }$ Then mes wit ro attention for long-range coherence, where reference frames are = {zkNct } NNck=0. Conditioned on each pair of key frames, i.e., reference frames as $\{ z _ { t } ^ { k N _ { c } } , z _ { t } ^ { ( k + 1 ) N _ { c } } \}$ z(k+1)Nct }, we sequentially synthesize their corresponding clip $\widehat { z } _ { t } ^ { k }$ holding the holistic consistency.
116
+
117
+ # 4 EXPERIMENTS
118
+
119
+ # 4.1 EXPERIMENTAL SETTINGS
120
+
121
+ Implementation details. ControlVideo is adapted from ControlNet 1 (Zhang & Agrawala, 2023) , and our interleaved-frame smoother employs a lightweight RIFE (Huang et al., 2022) to interpolate the middle frame of each three-frame clip. The synthesized short videos are of length 15, while the long videos usually contain about 100 frames. Unless otherwise noted, their resolution is both $5 1 2 \times 5 1 2$ . During sampling, we adopt DDIM sampling (Song et al., 2020a) with 50 timesteps, and interleaved-frame smoother is performed on predicted RGB frames at timesteps $\{ 3 0 , 3 1 \}$ by default. With the efficient implementation of xFormers (Lefaudeux et al., 2022), ControVideo could produce both short and long videos with one NVIDIA RTX 2080Ti in about 2 and 10 minutes, respectively.
122
+
123
+ Table 1: Quantitative comparisons of ControlVideo with other methods. We evaluate them on 125 motion-prompt pairs in terms of consistency, and the best results are bolded.
124
+
125
+ <table><tr><td>METHOD</td><td>Structure Condition</td><td>FC(×10-2)</td><td>PC(×10-2)</td><td>WE(×10-2)</td></tr><tr><td>Tune-A-Video Wu et al. (2022b)</td><td>DDIM Inversion</td><td>94.53</td><td>31.57</td><td>18.16</td></tr><tr><td>Text2Video-Zero Khachatryan et al. (2023) ControlVideo (ours)</td><td>Canny Edge Canny Edge</td><td>95.17 96.83</td><td>30.74 30.75</td><td>8.76 2.75</td></tr><tr><td>Text2Video-Zero Khachatryan et al. (2023) ControlVideo (ours)</td><td>Depth Map Depth Map</td><td>95.99 97.22</td><td>31.69 31.81</td><td>10.36 5.81</td></tr></table>
126
+
127
+ Datasets. To evaluate our ControlVideo, we collect 25 object-centric videos from DAVIS dataset (Pont-Tuset et al., 2017) and manually annotate their source descriptions. Then, for each source description, ChatGPT (OpenAI, 2022) is utilized to generate five editing prompts automatically, resulting in 125 video-prompt pairs in total. Finally, we employ Canny and MiDaS DPT-Hybrid model (Ranftl et al., 2020) to estimate the edges and depth maps of source videos, and form 125 motion-prompt pairs as our evaluation dataset. More details are provided in Appendix A.
128
+
129
+ Metrics. We evaluate the video quality from three perspectives. (i) Frame consistency (FC): the average cosine similarity between all pairs of consecutive frames, and (ii) Prompt consistency (PC): the average cosine similarity between input prompt and all video frames. (iii) Warping error (WE) (Lai et al., 2018): the average error between all frames and their warped frames using optical flow.
130
+
131
+ Baselines. We compare our ControlVideo with three publicly available methods: (i) Tune-AVideo (Wu et al., 2022b) extends Stable Diffusion to the video counterpart by finetuning it on a source video. During inference, it uses the DDIM inversion codes of source videos to provide structure guidance. (ii) Text2Video-Zero (Khachatryan et al., 2023) is based on ControlNet, and employs the first-only cross-frame attention on Stable Diffusion without finetuning. (iii) Follow-Your-Pose (Ma et al., 2023) is initialized with Stable Diffusion, and is finetuned on LAION-Pose (Ma et al., 2023) to support human pose conditions. After that, it is trained on millions of videos (Xue et al., 2022) to enable temporally-consistent video generation.
132
+
133
+ # 4.2 QUALITATIVE AND QUANTITATIVE COMPARISONS
134
+
135
+ Qualitative results. Fig. 3 first illustrates the visual comparisons of synthesized videos conditioned on both (a) depth maps and (b) canny edges. As shown in Fig. 3 (a), our ControlVideo demonstrates better consistency in both appearance and structure than alternative competitors. Tune-A-Video fails to keep the temporal consistency of both appearance and fine-grained structure, e.g., the color of coat and the structure of road. With the motion information from depth maps, Text2Video-Zero achieves promising consistency in structure, but still struggles with incoherent appearance in videos e.g., the color of coat. Besides, ControlVideo also performs more robustly when dealing with large motion inputs. As illustrated in Fig. 3 (b), Tune-A-Video ignores the structure information from source videos. Text2Video-Zero adopts the first-only cross-frame mechanism to trade off frame quality and appearance consistency, and generates later frames with visible artifacts. In contrast, with the proposed fully cross-frame mechanism and interleaved-frame smoother, our ControlVideo can handle large motion to generate high-quality and consistent videos.
136
+
137
+ Fig. 4 further shows the comparison conditioned on human poses. From Fig. 4, Tune-A-Video only maintains the coarse structures of the source video, i.e., human position. Text2Video-Zero and Follow-Your-Pose produce video frames with inconsistent appearance, e.g., changing faces of iron man (in row 4) or disappearing objects in the background (in row 5). In comparison, our ControlVideo performs more consistent video generation, demonstrating its superiority. More qualitative comparisons are provided in Appendix D.
138
+
139
+ Table 2: User preference study. The numbers denote the percentage of raters who favor the videos synthesized by our ControlVideo over other methods.
140
+
141
+ <table><tr><td>Method Comparison</td><td>Video Quality</td><td>Temporal Consistency</td><td>Text Alignment</td></tr><tr><td>Ours vs. Tune-A-Video Wu et al. (2022b)</td><td>73.6%</td><td>83.2%</td><td>68.0%</td></tr><tr><td>Ours vs. Text2Video-Zero Khachatryan et al. (2023)</td><td>76.0%</td><td>81.6%</td><td>65.6%</td></tr></table>
142
+
143
+ ![](images/d80c47a0e5e135476ad15387cd5c235ac3e5dc78f1d8d4a8a062bb3245191e87.jpg)
144
+ Figure 4: Qualitative comparisons on poses. Tune-A-Video only preserves original human positions, while Text2Video-Zero and FollowYour-Pose produce frames with appearance incoherence. Our ControlVideo achieves better consistency in both structure and appearance. See videos at qualitative comparisons.
145
+
146
+ ![](images/1dac4c1bcf0219c6994391946d507e7cf5ee9c3569df7ab1ab968a0c48f34306.jpg)
147
+ Figure 5: Qualitative ablation studies on cross-frame mechanisms and interleaved-frame smoother. Fully cross-frame interaction produces video frames with higher quality and consistency than other mechanisms, and adding the smoother further enhances the video smoothness. See corresponding videos for better comparison.
148
+
149
+ Quantitative results. We have also compared our ControlVideo with existing methods quantitatively on 125 video-prompt pairs. From Table 1, our ControlVideo conditioned on depth outperforms the state-of-the-art methods in terms of all metrics, which is consistent with the qualitative results. In contrast, despite finetuning on a source video, Tune-A-Video still struggles to produce temporally coherent videos. Although conditioned on the same structure information, Text2VideoZero obtains worse frame consistency and warping error than ControlVideo. For each method, the depth-conditioned models generate videos with higher frame and prompt consistency than the canny-condition counterpart, since depth maps provide smoother motion information.
150
+
151
+ # 4.3 USER STUDY
152
+
153
+ We then perform the user study to compare our ControlVideo conditioned on depth maps with other competing methods. In specific, we provide each rater a structure sequence, a text prompt, and synthesized videos from two different methods (in random order). Then we ask them to select the better synthesized videos for each of three measurements: (i) video quality, (ii) temporal consistency throughout all frames, and (iii) text alignment between prompts and synthesized videos. The evaluation set consists of 125 representative structure-prompt pairs. Each pair is evaluated by 5 raters, and we take a majority vote for the final result. From Table 2, the raters strongly favor our synthesized videos from all three perspectives, especially in temporal consistency. On the other hand, Tune-A-Video fails to generate consistent and high-quality videos with only DDIM inversion for structural guidance, and Text2Video-Zero also produces videos with lower quality and coherency.
154
+
155
+ Table 3: Quantitative ablation studies on cross-frame mechanisms and interleaved-frame smoother. The results indicate that our fully cross-frame mechanism achieves better frame consistency than other mechanisms, and the interleaved-frame smoother significantly improves the frame consistency.
156
+ a steamship on the ocean, at sunset, sketch style
157
+
158
+ <table><tr><td>Cross-Frame Mechanism</td><td>FC(×10-2)</td><td>PC (×10-2)</td><td>WE(×10-2)</td><td>Time Cost (min)</td></tr><tr><td>Individual</td><td>89.94</td><td>30.79</td><td>20.13</td><td>1.2</td></tr><tr><td>First-only</td><td>94.92</td><td>30.54</td><td>8.91</td><td>1.2</td></tr><tr><td>Sparse-Causal</td><td>95.06</td><td>30.59</td><td>7.05</td><td>1.5</td></tr><tr><td>Fully</td><td>95.36</td><td>30.76</td><td>5.93</td><td>3.0</td></tr><tr><td>Fully + Smoother</td><td>96.83</td><td>30.79</td><td>2.75</td><td>3.5</td></tr></table>
159
+
160
+ ![](images/5831b0842b887e81d40a454484c1f1e84c71afb1d4e70c088e7d698fb2be789e.jpg)
161
+ Figure 6: A long video produced with our hierarchical sampling. Motion sequences are shown on the top left. Using the efficient sampler, our ControlVideo generates a high-quality long video with the holistic consistency. See videos at long video generation.
162
+
163
+ # 4.4 ABLATION STUDY
164
+
165
+ Effect of fully cross-frame interaction. To demonstrate the effectiveness of the fully cross-frame interaction, we conduct a comparison with the following variants: i) individual: no interaction between all frames, ii) first-only: all frames attend to the first one, iii) sparse-causal: each frame attends to the first and former frames, iv) fully: our fully cross-frame, refer to Sec. 3. Note that, all the above models are extended from ControlNet without any finetuning. The qualitative and quantitative results are shown in Fig. 5 and Table 3, respectively. From Fig. 5, the individual cross-frame mechanism suffers from severe temporal inconsistency, e.g., colorful and black-and-white frames. The first-only and sparse-causal mechanisms reduce some appearance inconsistency by adding crossframe interaction. However, they still produce videos with structural inconsistency and visible artifacts, e.g., the orientation of the elephant and duplicate nose (row 3 in Fig. 5). In contrast, due to less generation gap with ControlNet, our fully cross-frame interaction performs better appearance coherency and video quality. Though the introduced interaction brings an extra $1 \sim 2 \times$ time cost, it is acceptable for a high-quality video generation.
166
+
167
+ Effect of interleaved-frame smoother. We further analyze the effect of the proposed interleavedframe smoother. From Table 3 and last two rows of Fig. 5, our interleaved-frame smoother greatly improves the video smoothness, e.g., mitigating structural flickers in red boxes. We provide more ablation studies on the timestep choices of the smoother in Appendix C and ablation studies.
168
+
169
+ # 4.5 EXTENSION TO LONG-VIDEO GENERATION
170
+
171
+ Producing a long video usually requires an advanced GPU with high memory. With the proposed hierarchical sampler, our ControlVideo achieves long video generation (more than 100 frames) in a memory-efficient manner. As shown in Fig. 6, our ControlVideo can produce a long video with consistently high quality. Notably, benefiting from our efficient sampling, it only takes approximately ten minutes to generate 100 frames with resolution $5 1 2 \times 5 1 2$ in one NVIDIA RTX 2080Ti. More visualizations of long videos can be found in Appendix D.
172
+
173
+ # 5 RELATED WORK
174
+
175
+ Text-to-image synthesis. Through pre-training on billions of image-text pairs, large-scale generative models (Nichol et al., 2021; Balaji et al., 2022; Saharia et al., 2022; Ramesh et al., 2022; Rombach et al., 2022; Ramesh et al., 2021; Chang et al., 2023; Ding et al., 2021; 2022; Yu et al., 2022; Sauer et al., 2023; Kang et al., 2023; Huang et al., 2023) have made remarkable progress in creative and photo-realistic visual generation. Various frameworks have been explored to enhance image quality, including GANs (Goodfellow et al., 2020; Sauer et al., 2023; Kang et al., 2023), autoregressive models (Nichol et al., 2021; Chang et al., 2023; Ding et al., 2021; 2022; Yu et al., 2022), and diffusion models (Ho et al., 2020; Balaji et al., 2022; Saharia et al., 2022; Ramesh et al., 2022; Rombach et al., 2022). Among these generative models, diffusion-based models are well open-sourced and popularly applied to several downstream tasks, such as image editing (Hertz et al., 2022; Meng et al., 2021) and customized generation (Gal et al., 2022; Wei et al., 2023; Kumari et al., 2022; Ruiz et al., 2022). Besides text prompts, several works (Zhang & Agrawala, 2023; Mou et al., 2023) also introduce additional structure conditions to pre-trained text-to-image diffusion models for controllable text-to-image generation. Our ControlVideo is implemented based on the controllable text-to-image models to inherit their ability of high-quality and consistent generation.
176
+
177
+ Text-to-video synthesis. Large text-to-video generative models usually extend text-to-image models by adding temporal consistency. Earlier works (Wu et al., 2022a; Hong et al., 2022; Wu et al., 2021; Villegas et al., 2022) adopt an autoregressive framework to synthesize videos according to given descriptions. Capitalizing on the success of diffusion models in image generation, recent works (Ho et al., 2022a;b; Singer et al., 2022) propose to leverage their potential to produce high-quality videos. Nevertheless, training such large-scale video generative models requires extensive video-text pairs and computational resources. To reduce the training burden, Gen-1 (Esser et al., 2023) and FollowYour-Pose (Ma et al., 2023) provide coarse temporal information (e.g., motion sequences) for video generation, yet are still costly for most researchers and users. By replacing self-attention with the sparser cross-frame mechanisms, Tune-A-Video (Wu et al., 2022b) and Text2Video-Zero (Khachatryan et al., 2023) keep considerable consistency in appearance with little finetuning. ControlVideo also adapts text-to-image diffusion models without any training, but generates videos with better temporal consistency and continuity.
178
+
179
+ # 6 DISCUSSION
180
+
181
+ In this paper, we present a training-free framework, namely ControlVideo, towards consistent and continuous controllable text-to-video generation. ControlVideo, inflated from ControlNet, introduces an interleaved-frame smoother to ensure video continuity. Particularly, interleaved-frame smoother alternately smooths out the latents of three-frame clips, and stabilizes each clip by updating the middle frame with the interpolation among other two frames in latent space. Moreover, we empirically demonstrate the superior performance of fully cross-frame interaction, while presenting hierarchical sampler for long-video generation in commodity GPUs. Quantitative and qualitative experiments on extensive motion-prompt pairs demonstrate that ControlVideo achieves state-of-the-arts in terms of frame consistency and video continuity.
182
+
183
+ Broader impact. Large-scale diffusion models have made tremendous progress in text-to-video synthesis, yet these models are costly and unavailable to the public. ControlVideo focuses on trainingfree controllable text-to-video generation, and takes an essential step in efficient video creation. Concretely, ControlVideo could synthesize high-quality videos with commodity hardware, hence, being accessible to most researchers and users. For example, artists may leverage our approach to create fascinating videos with less time. Moreover, ControlVideo provides insights into the tasks involved in videoss, e.g., video rendering, video editing, and video-to-video translation. On the flip side, albeit we do not intend to use our model for harmful purposes, it might be misused and bring some potential negative impacts, such as producing deceptive, harmful, or explicit videos. Despite the above concerns, we believe that they could be well minimized with some steps. For example, an NSFW filter can be employed to filter out unhealthy and violent content. Also, we hope that the government could establish and improve relevant regulations to restrict the abuse of video creation.
184
+
185
+ # ACKNOWLEDGEMENT
186
+
187
+ This work was supported by National Key RD Program of China under Grant No. 2021ZD0112100, and the National Natural Science Foundation of China (NSFC) under Grant No. U19A2073.
188
+
189
+ REFERENCES
190
+ Yogesh Balaji, Seungjun Nah, Xun Huang, Arash Vahdat, Jiaming Song, Karsten Kreis, Miika Aittala, Timo Aila, Samuli Laine, Bryan Catanzaro, et al. ediffi: Text-to-image diffusion models with an ensemble of expert denoisers. arXiv preprint arXiv:2211.01324, 2022.
191
+ Huiwen Chang, Han Zhang, Jarred Barber, AJ Maschinot, Jose Lezama, Lu Jiang, Ming-Hsuan Yang, Kevin Murphy, William T Freeman, Michael Rubinstein, et al. Muse: Text-to-image generation via masked generative transformers. arXiv preprint arXiv:2301.00704, 2023.
192
+ Ming Ding, Zhuoyi Yang, Wenyi Hong, Wendi Zheng, Chang Zhou, Da Yin, Junyang Lin, Xu Zou, Zhou Shao, Hongxia Yang, et al. Cogview: Mastering text-to-image generation via transformers. NeurIPS, 2021.
193
+ Ming Ding, Wendi Zheng, Wenyi Hong, and Jie Tang. Cogview2: Faster and better text-to-image generation via hierarchical transformers. arXiv preprint arXiv:2204.14217, 2022.
194
+ Patrick Esser, Johnathan Chiu, Parmida Atighehchian, Jonathan Granskog, and Anastasis Germanidis. Structure and content-guided video synthesis with diffusion models. arXiv preprint arXiv:2302.03011, 2023.
195
+ Rinon Gal, Yuval Alaluf, Yuval Atzmon, Or Patashnik, Amit H Bermano, Gal Chechik, and Daniel Cohen-Or. An image is worth one word: Personalizing text-to-image generation using textual inversion. arXiv preprint arXiv:2208.01618, 2022.
196
+ Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial networks. Communications of the ACM, 2020.
197
+ Amir Hertz, Ron Mokady, Jay Tenenbaum, Kfir Aberman, Yael Pritch, and Daniel Cohen-Or. Promptto-prompt image editing with cross attention control. arXiv preprint arXiv:2208.01626, 2022.
198
+ Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffusion probabilistic models. NeurIPS, 2020.
199
+ Jonathan Ho, William Chan, Chitwan Saharia, Jay Whang, Ruiqi Gao, Alexey Gritsenko, Diederik P Kingma, Ben Poole, Mohammad Norouzi, David J Fleet, et al. Imagen video: High definition video generation with diffusion models. arXiv preprint arXiv:2210.02303, 2022a.
200
+ Jonathan Ho, Tim Salimans, Alexey Gritsenko, William Chan, Mohammad Norouzi, and David J Fleet. Video diffusion models. arXiv preprint arXiv:2204.03458, 2022b.
201
+ Wenyi Hong, Ming Ding, Wendi Zheng, Xinghan Liu, and Jie Tang. Cogvideo: Large-scale pretraining for text-to-video generation via transformers. arXiv preprint arXiv:2205.15868, 2022.
202
+ Tianyu Huang, Yihan Zeng, Bowen Dong, Hang Xu, Songcen Xu, Rynson WH Lau, and Wangmeng Zuo. Textfield3d: Towards enhancing open-vocabulary 3d generation with noisy text fields. arXiv preprint arXiv:2309.17175, 2023.
203
+ Zhewei Huang, Tianyuan Zhang, Wen Heng, Boxin Shi, and Shuchang Zhou. Real-time intermediate flow estimation for video frame interpolation. In ECCV, 2022.
204
+ Minguk Kang, Jun-Yan Zhu, Richard Zhang, Jaesik Park, Eli Shechtman, Sylvain Paris, and Taesung Park. Scaling up gans for text-to-image synthesis. In CVPR, 2023.
205
+ Levon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang Wang, Shant Navasardyan, and Humphrey Shi. Text2video-zero: Text-to-image diffusion models are zero-shot video generators. arXiv preprint arXiv:2303.13439, 2023.
206
+
207
+ Nupur Kumari, Bingliang Zhang, Richard Zhang, Eli Shechtman, and Jun-Yan Zhu. Multi-concept customization of text-to-image diffusion. arXiv preprint arXiv:2212.04488, 2022.
208
+
209
+ Wei-Sheng Lai, Jia-Bin Huang, Oliver Wang, Eli Shechtman, Ersin Yumer, and Ming-Hsuan Yang. Learning blind video temporal consistency. In Proceedings of the European conference on computer vision (ECCV), pp. 170–185, 2018.
210
+ Benjamin Lefaudeux, Francisco Massa, Diana Liskovich, Wenhan Xiong, Vittorio Caggiano, Sean Naren, Min Xu, Jieru Hu, Marta Tintore, Susan Zhang, Patrick Labatut, and Daniel Haziza. xformers: A modular and hackable transformer modelling library. https://github.com/ facebookresearch/xformers, 2022.
211
+ Yue Ma, Yingqing He, Xiaodong Cun, Xintao Wang, Ying Shan, Xiu Li, and Qifeng Chen. Follow your pose: Pose-guided text-to-video generation using pose-free videos. arXiv preprint arXiv:2304.01186, 2023.
212
+ Chenlin Meng, Yang Song, Jiaming Song, Jiajun Wu, Jun-Yan Zhu, and Stefano Ermon. Sdedit: Image synthesis and editing with stochastic differential equations. arXiv preprint arXiv:2108.01073, 2021.
213
+ Chong Mou, Xintao Wang, Liangbin Xie, Jian Zhang, Zhongang Qi, Ying Shan, and Xiaohu Qie. T2i-adapter: Learning adapters to dig out more controllable ability for text-to-image diffusion models. arXiv preprint arXiv:2302.08453, 2023.
214
+ Minheng Ni, Zitong Huang, Kailai Feng, and Wangmeng Zuo. Imaginarynet: Learning object detectors without real images and annotations. arXiv preprint arXiv:2210.06886, 2022.
215
+ Alex Nichol, Prafulla Dhariwal, Aditya Ramesh, Pranav Shyam, Pamela Mishkin, Bob McGrew, Ilya Sutskever, and Mark Chen. Glide: Towards photorealistic image generation and editing with text-guided diffusion models. arXiv preprint arXiv:2112.10741, 2021.
216
+ TB OpenAI. Chatgpt: Optimizing language models for dialogue. OpenAI, 2022.
217
+ Jordi Pont-Tuset, Federico Perazzi, Sergi Caelles, Pablo Arbelaez, Alex Sorkine-Hornung, and ´ Luc Van Gool. The 2017 davis challenge on video object segmentation. arXiv preprint arXiv:1704.00675, 2017.
218
+ Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, and Qifeng Chen. Fatezero: Fusing attentions for zero-shot text-based video editing. arXiv preprint arXiv:2303.09535, 2023.
219
+ Aditya Ramesh, Mikhail Pavlov, Gabriel Goh, Scott Gray, Chelsea Voss, Alec Radford, Mark Chen, and Ilya Sutskever. Zero-shot text-to-image generation. In ICML, 2021.
220
+ Aditya Ramesh, Prafulla Dhariwal, Alex Nichol, Casey Chu, and Mark Chen. Hierarchical textconditional image generation with clip latents. arXiv preprint arXiv:2204.06125, 2022.
221
+ Rene Ranftl, Katrin Lasinger, David Hafner, Konrad Schindler, and Vladlen Koltun. Towards robust ´ monocular depth estimation: Mixing datasets for zero-shot cross-dataset transfer. TPAMI, 2020.
222
+ Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bjorn Ommer. High-¨ resolution image synthesis with latent diffusion models. In CVPR, 2022.
223
+ Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In MICCAI, 2015.
224
+ Nataniel Ruiz, Yuanzhen Li, Varun Jampani, Yael Pritch, Michael Rubinstein, and Kfir Aberman. Dreambooth: Fine tuning text-to-image diffusion models for subject-driven generation. arXiv preprint arXiv:2208.12242, 2022.
225
+ Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022.
226
+ Axel Sauer, Tero Karras, Samuli Laine, Andreas Geiger, and Timo Aila. Stylegan-t: Unlocking the power of gans for fast large-scale text-to-image synthesis. arXiv preprint arXiv:2301.09515, 2023.
227
+ Uriel Singer, Adam Polyak, Thomas Hayes, Xi Yin, Jie An, Songyang Zhang, Qiyuan Hu, Harry Yang, Oron Ashual, Oran Gafni, et al. Make-a-video: Text-to-video generation without text-video data. arXiv preprint arXiv:2209.14792, 2022.
228
+ Jiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. arXiv preprint arXiv:2010.02502, 2020a.
229
+ Jiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. arXiv preprint arXiv:2010.02502, 2020b.
230
+ Ruben Villegas, Mohammad Babaeizadeh, Pieter-Jan Kindermans, Hernan Moraldo, Han Zhang, Mohammad Taghi Saffar, Santiago Castro, Julius Kunze, and Dumitru Erhan. Phenaki: Variable length video generation from open domain textual description. arXiv preprint arXiv:2210.02399, 2022.
231
+ Wen Wang, kangyang Xie, Zide Liu, Hao Chen, Yue Cao, Xinlong Wang, and Chunhua Shen. Zeroshot video editing using off-the-shelf image diffusion models. arXiv preprint arXiv:2303.17599, 2023.
232
+ Yuxiang Wei, Yabo Zhang, Zhilong Ji, Jinfeng Bai, Lei Zhang, and Wangmeng Zuo. Elite: Encoding visual concepts into textual embeddings for customized text-to-image generation. arXiv preprint arXiv:2302.13848, 2023.
233
+ Chenfei Wu, Lun Huang, Qianxi Zhang, Binyang Li, Lei Ji, Fan Yang, Guillermo Sapiro, and Nan Duan. Godiva: Generating open-domain videos from natural descriptions. arXiv preprint arXiv:2104.14806, 2021.
234
+ Chenfei Wu, Jian Liang, Lei Ji, Fan Yang, Yuejian Fang, Daxin Jiang, and Nan Duan. Nuwa: Visual ¨ synthesis pre-training for neural visual world creation. In ECCV, 2022a.
235
+ Jay Zhangjie Wu, Yixiao Ge, Xintao Wang, Weixian Lei, Yuchao Gu, Wynne Hsu, Ying Shan, Xiaohu Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning of image diffusion models for text-to-video generation. arXiv preprint arXiv:2212.11565, 2022b.
236
+ Hongwei Xue, Tiankai Hang, Yanhong Zeng, Yuchong Sun, Bei Liu, Huan Yang, Jianlong Fu, and Baining Guo. Advancing high-resolution video-language representation with large-scale video transcriptions. In CVPR, 2022.
237
+ Jiahui Yu, Yuanzhong Xu, Jing Yu Koh, Thang Luong, Gunjan Baid, Zirui Wang, Vijay Vasudevan, Alexander Ku, Yinfei Yang, Burcu Karagol Ayan, et al. Scaling autoregressive models for contentrich text-to-image generation. arXiv preprint arXiv:2206.10789, 2022.
238
+ Lvmin Zhang and Maneesh Agrawala. Adding conditional control to text-to-image diffusion models. arXiv preprint arXiv:2302.05543, 2023.
239
+
240
+ # A. DATASET DETAILS
241
+
242
+ In Table 4, we select 25 representative videos from DAVIS dataset (Pont-Tuset et al., 2017) and manually annotate their source captions. After that, we ask ChatGPT to generate five edited prompts for each source caption, following the instruction like: Please generate five new sentences that similar to “A man dances on the road”, while being more diverse and highly detailed. Finally, we obtain 125 video-prompt pairs in total, and use them to evaluate both canny and depth conditioned generation.
243
+
244
+ # B. USER STUDY DETAILS
245
+
246
+ We conduct a user study to compare ControlVideo against two other methods on 125 samples, and ask five raters to answer questions in each sample. In Fig. 7, there are three questions involving in (i) video quality, (ii) temporal consistency, and (iii) text alignment. The raters are given unlimited time to make the selection. After collecting their answers, we take a majority vote as the final result for each sample, and present statistics in Table 2.
247
+
248
+ # C. MORE ABLATION STUDIES
249
+
250
+ During inference, we adopt DDIM sampling with $T = 5 0$ timesteps, which iteratively denoises a Gaussian noise from $T$ to 0.
251
+
252
+ Which timesteps does interleaved-frame smoother perform at? In Fig. 8, we explore three timestep choices at different noise levels, including $\{ 4 8 , 4 9 \}$ at large noise level, $\{ 3 0 , 3 1 \bar { \} }$ at middle noise level, and $\{ 0 , 1 \}$ at little noise level. When using the smoother at timesteps $\{ 4 8 , 4 9 \}$ , the processed video is still unstable, since structure sequences bring additional flickers at the following timesteps. At timesteps $\{ 0 , 1 \}$ nearby image distribution, applying the interleaved-frame smoother leads to visible distortion in some frames. In contrast, performing smoothing operation at middle timesteps $\{ 3 0 , 3 1 \}$ promisingly deflickers the video, while preserving the quality and individuality of interpolated frames.
253
+
254
+ How many timesteps are used in interleaved-frame smoother? Fig. 9 shows the smoothed videos using interleaved-frame smoother at different numbers of timesteps. Applying the smoother at two consecutive timesteps (i.e., 2 steps) could smooth the entire video with little video quality degradation. As the number of smoothing steps increases, the processed video is much smoother, but some frames become slightly blurred. Thus, for higher quality and efficiency, we set the number of smoothing timesteps as 2 by default.
255
+
256
+ Non-deterministic DDPM-style sampler. ControlVideo can also employ a non-deterministic DDPM-style sampler during inference. Following Eq.12 in DDIM (Song et al., 2020b), one can predict $z _ { t - 1 }$ from ${ \boldsymbol { z } } _ { t }$ via (i.e., line 10 of Alg. 1 in paper):
257
+
258
+ $$
259
+ z _ { t - 1 } \gets \sqrt { \alpha _ { t - 1 } } \tilde { z } _ { t \to 0 } + \sqrt { 1 - \alpha _ { t - 1 } } \cdot \epsilon _ { \theta } ( z _ { t } , t , c , \tau ) + \sigma _ { t } \epsilon _ { t } ,
260
+ $$
261
+
262
+ where $\epsilon _ { t }$ and $\sigma _ { t }$ controls the level of random noise. DDPM results presents the generated videos of ControlVideo at different noise levels. Notably, as the noise level increases, ControlVideo generates more photo-realistic videos with dynamic details, e.g., ripples in the water.
263
+
264
+ # D. MORE VISUALIZATIONS AND COMPARISONS
265
+
266
+ Fig. 10, Fig. 11, and Fig. 12 show more video visualizations conditioned on canny edges, depth maps, and human poses. Fig. 14, Fig. 15, and Fig. 16 present qualitative comparisons conditioned on canny edges, depth maps, and human poses. Fig. 13 provides an additional long video. More comparisons with video editing methods (Qi et al., 2023; Wang et al., 2023) are shown in this link.
267
+
268
+ Firstly, Vid2Vid-Zero and FateZero are designed for video editing by a hybrid of fully and sparsecasual cross-frame attention, and does not investigate different attention mechanisms in depth. In contrast, our ControlVideo focuses on continuous controllable text-to-video generation, and first empirically investigate the superiority of fully cross-frame attention. Secondly, Fig. 18 shows their qualitative comparisons on video editing. As one can see, the edited videos of ControlVideo not only have more consistent structure with source videos, but also aligns better with text prompts.
269
+
270
+ Table 4: Names and captions of selected videos from DAVIS dataset.
271
+
272
+ # Between Method 1 & 2 :
273
+
274
+ ![](images/c5e387d34be8b3c0b93aee09f685e24171376650a44074d7f68e069e25d6d8b6.jpg)
275
+ Figure 7: The instruction of user study. A user study sample consists of a text prompt, structure sequence, and synthesized videos from two different methods (in random order). The raters are asked to answer the above three questions for each sample.
276
+
277
+ 1. Which video has higher quality ?
278
+ 2. Which video has better temporal consistency across all frames?
279
+ 3. Which video aligns better with text prompt?
280
+
281
+ # E. LIMITATIONS.
282
+
283
+ While our ControlVideo enables consistent and high-quality video generation, it still struggles with producing videos beyond input motion sequences. For example, in Fig. 17, given sequential poses of Michael Jackson’s moonwalk, it is difficult to generate a vivid video according to text prompts like Iron man runs on the street. In this link, when input text prompts (e.g., rabbit) seriously conflict with input motion (e.g., ), the synthesized videos usually tend to align with input motion, ignoring the implicit structure in text prompts. To increase the ratio of text prompts over structure, we decrease the scale of ControlNet $\lambda$ to 0.3 ( $\lambda = 1$ by default). Therefore, it can be seen $\lambda = 0 . 3$ that achieves a better trade-off between two input conditions than $\lambda = 1$ . In the future, we will explore how to adaptively modify input motions according to text prompts, so that users can create more vivid videos.
284
+
285
+ ![](images/1cc77370796c781d5eac52f2bb3d67956168ff3ef10f9c2fccac9a465c1bc05f.jpg)
286
+ A dusty old jeep was making its way down the winding forest road, creaking and groaning with each bump and turn.
287
+ Figure 8: Ablation on timestep choices in interleaved-frame smoother. We apply interleavedframe smoother at different timesteps, including $\{ 4 8 , 4 9 \}$ at large noise level, $\{ 3 0 , 3 1 \}$ at middle noise level, and $\{ 0 , 1 \}$ at little noise level. Among them, using the smoother at timesteps $\{ 3 0 , 3 1 \}$ promisingly mitigates the flicker effect while ensuring high quality. Results best seen at $50 \%$ zoom.
288
+
289
+ ![](images/1f621020166128d9f9d0a58b8c65dd34ce2cb9f405c4b2184a8d3f0bb5899c8d.jpg)
290
+ A sleek black jeep was speeding along the narrow forest road, dodging trees and rocks with ease.
291
+ Figure 9: Ablation on the number of timesteps used in interleaved-frame smoother. Applying the smoother at two consecutive timesteps (i.e., 2 steps) effectively reduces the flickers in structure. As we increase the number of smoothing steps, the processed video becomes smoother, but some frames are slightly blurred. Therefore, we set the number of smoothing steps as two by default. Results best seen at $50 \%$ zoom.
292
+
293
+ ![](images/5a5910fbbd4ad8aaafebc4ea5c03c6ee917d56beba91a746e9a78e03a6a7c148.jpg)
294
+ Figure 10: More video visualizations conditioned on canny edges. Results best seen at $50 \%$ zoom.
295
+
296
+ ![](images/2cf0952da37fcfb973d7d3a30a66d33efc530f74e6b5482843901118c0736493.jpg)
297
+ Figure 11: More video visualizations conditioned on depth maps. Results best seen at $50 \%$ zoom.
298
+
299
+ Bottom: Wonder Woman in a desert, Pop Art style.
300
+
301
+ ![](images/edaa8ff27d73074eafff7fee3ee37a09d651f507a2e1fff43fa3d20c970bb157.jpg)
302
+ Top: Hulk is jumping on the street, cartoon style
303
+ Bottom: The Simpsons in the city, Hockney style.
304
+ Top: Goku in a mountain range, surreal style.
305
+ Top: A man, wearing pink clothes, moonwalk at sunset.
306
+ Figure 12: More video visualizations conditioned on human poses. Results best seen at $50 \%$ zoom.
307
+
308
+ Bottom: James bond moonwalk on the beach, animation style.
309
+
310
+ ![](images/ae0be126190267c573b161a409a3714fbac0df2f02242d6b6464e0f224a5b180.jpg)
311
+ Hulk is dancing on the beach, cartoon style.
312
+ Figure 13: Additional long video visualization. Results best seen at $50 \%$ zoom.
313
+
314
+ ![](images/98b2b95ddf40dc44b7df6621f1c07e09ac69002449fc3385ad31aa1c676e13d9.jpg)
315
+ Figure 14: More qualitative comparisons conditioned on canny edges. Results best seen at $50 \%$ zoom.
316
+
317
+ ![](images/226f88c39b4b0c84dde0cac7902c01d34efec8ea241efe3246e64ccdaf4795a4.jpg)
318
+ Figure 15: More qualitative comparisons conditioned on depth maps. Results best seen at $50 \%$ zoom.
319
+
320
+ ![](images/4605680307d5e360af89d69a874f3dec185392cfe082e89b9eda044b82ead317.jpg)
321
+ Figure 16: More qualitative comparisons conditioned on human poses. Results best seen at $50 \%$ zoom.
322
+
323
+ ![](images/71d28866116d0ff2097ca8dbeb2a32a188a5b46c20dd155fc5c7a5cc8d495ee6.jpg)
324
+ Figure 17: Limitation visualizations. ControlVideo struggles with producing videos beyond input motion sequences. The motion of text prompt Iron man runs on the street does not align with the given sequential poses of Michael Jackson’s moonwalk, which degrades the video quality and consistency. See videos at limitations.
325
+
326
+ ![](images/ea8cf74902f9be79151ade294cf1ae1a0b8da5e3ed535f0d3cf54179ac528ba4.jpg)
327
+ Figure 18: Qualitative comparisons with Vid2Vid-Zero. Inconsistent objects and prompts are colored in red.
parse/test/5a79AqFr0c/5a79AqFr0c_content_list.json ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "type": "text",
4
+ "text": "CONTROLVIDEO: TRAINING-FREE CONTROLLABLE TEXT-TO-VIDEO GENERATION ",
5
+ "text_level": 1,
6
+ "page_idx": 0
7
+ },
8
+ {
9
+ "type": "text",
10
+ "text": "Yabo Zhang1 Yuxiang Wei1 Dongsheng Jiang2 Xiaopeng Zhang2 Wangmeng Zuo1 $( \\boxtimes )$ Qi Tian2 ",
11
+ "page_idx": 0
12
+ },
13
+ {
14
+ "type": "text",
15
+ "text": "1Harbin Institute of Technology 2Huawei Cloud ",
16
+ "page_idx": 0
17
+ },
18
+ {
19
+ "type": "text",
20
+ "text": "ABSTRACT ",
21
+ "text_level": 1,
22
+ "page_idx": 0
23
+ },
24
+ {
25
+ "type": "text",
26
+ "text": "Text-driven diffusion models have unlocked unprecedented abilities in image generation, whereas their video counterpart lags behind due to the excessive training cost. To avert the training burden, we propose a training-free ControlVideo to produce high-quality videos based on the provided text prompts and motion sequences. Specifically, ControlVideo adapts a pre-trained text-to-image model (i.e., ControlNet) for controllable text-to-video generation. To generate continuous videos without flicker effects, we propose an interleaved-frame smoother to smooth the intermediate frames. In particular, interleaved-frame smoother splits the whole video with successive three-frame clips, and stabilizes each clip by updating the middle frame with the interpolation among other two frames in latent space. Furthermore, a fully cross-frame interaction mechanism is exploited to further enhance the frame consistency, while a hierarchical sampler is employed to produce long videos efficiently. Extensive experiments demonstrate that our ControlVideo outperforms the state-of-the-arts both quantitatively and qualitatively. It is worth noting that, thanks to the efficient designs, ControlVideo could generate both short and long videos within several minutes using one NVIDIA 2080Ti. Code and videos are available at this link. ",
27
+ "page_idx": 0
28
+ },
29
+ {
30
+ "type": "text",
31
+ "text": "1 INTRODUCTION ",
32
+ "text_level": 1,
33
+ "page_idx": 0
34
+ },
35
+ {
36
+ "type": "text",
37
+ "text": "Large-scale diffusion models have made a tremendous breakthrough on text-to-image synthesis (Nichol et al., 2021; Rombach et al., 2022; Balaji et al., 2022; Ramesh et al., 2022; Saharia et al., 2022) and their creative applications (Gal et al., 2022; Wei et al., 2023; Ni et al., 2022; Hertz et al., 2022). Several studies (Ho et al., 2022b;a; Singer et al., 2022; Esser et al., 2023; Hong et al., 2022) attempt to replicate this success in the video counterpart, i.e., modeling higher-dimensional complex video distributions in the wild world. However, training such a text-to-video model requires massive amounts of high-quality videos and computational resources, which limits further research and applications by relevant communities. ",
38
+ "page_idx": 0
39
+ },
40
+ {
41
+ "type": "text",
42
+ "text": "In this work, we study a new and efficient form to avert the excessive training requirements: controllable text-to-video generation with text-to-image models. As shown in Fig. 1, our method, termed ControlVideo, takes textual description and motion sequence (e.g., depth or edge maps) as conditions to generate videos. Instead of learning the video distribution from scratch, ControlVideo adapts the pre-trained text-to-image models (e.g., ControlNet (Zhang & Agrawala, 2023)) for high-quality video generation. With the structural information from motion sequence and the superior generation capability of image models, it is feasible to produce a vivid video without additional training. ",
43
+ "page_idx": 0
44
+ },
45
+ {
46
+ "type": "text",
47
+ "text": "However, as shown in Fig. 1, due to the lack of temporal interaction, individually producing each frame with ControlNet (Zhang & Agrawala, 2023) fails to ensure both (i) frame consistency and (ii) video continuity. Frame consistency requires all frames to be generated with a coherent appearance, while video continuity ensures smooth transitions between frames. Tune-A-Video (Wu et al., 2022b) and Text2Video-Zero (Khachatryan et al., 2023) facilitate appearance consistency by extending self-attention to sparser cross-frame attention. Nonetheless, such a cross-frame interaction is not sufficient to guarantee video continuity, and visible flickers appear in their synthesized videos (as shown in Fig. 1 and corresponding videos). ",
48
+ "page_idx": 0
49
+ },
50
+ {
51
+ "type": "image",
52
+ "img_path": "images/d1c94a87f431ed8decf8708008be42280186424c7cb94567abd7cf4cf5dcc95b.jpg",
53
+ "image_caption": [
54
+ "Figure 1: Training-free controllable text-to-video generation. Left: We visualize the frames and x-t slice (pixels in red line of original frame) of Text2Video-Zero, and observe visible discontinuity in $x$ -t slice. Right: ControlVideo, adapted from ControlNet, achieves more continuous $x { - } t$ slice across time, along with improved appearance consistency than Text2Video-Zero. See videos for better view. "
55
+ ],
56
+ "image_footnote": [],
57
+ "page_idx": 1
58
+ },
59
+ {
60
+ "type": "text",
61
+ "text": "Intuitively, a continuous video could be considered as multiple continuous three-frame clips, so the problem of ensuring the video continuity is converted to ensuring all three-frame clips continuous. Driven by this analysis, we propose an interleaved-frame smoother to enable continuous video generation. Specifically, interleaved-frame smoother divides all three-frame clips into even and odd clips based on indices of middle frames, and separately smooths out their corresponding latents at different denoising steps. To stabilize the latent of each clip, we first convert it to predicted RGB frames with DDIM, followed by replacing the middle frame with the interpolated frame. Note that, the smoother is only applied at a few timesteps, and the quality and individuality of interpolated frames can be well retained by the following denoising steps. ",
62
+ "page_idx": 1
63
+ },
64
+ {
65
+ "type": "text",
66
+ "text": "We further investigate the cross-frame mechanisms in terms of effectiveness and efficiency. Firstly, we explore fully cross-frame interaction that concatenates all frames to become a “larger image”, and first empirically demonstrate its superior consistency and quality than sparser counterparts (see Sec. 4.4). Secondly, applying existing cross-frame mechanisms for long-video generation suffers from either heavy computational burden or long-term inconsistency. Therefore, a hierarchical sampler is presented to produce a long video in a top-down way. In specific, it pre-generates the key frames with fully cross-frame attention for long-range coherence, followed by efficiently generating the short clips conditioned on pairs of key frames. ",
67
+ "page_idx": 1
68
+ },
69
+ {
70
+ "type": "text",
71
+ "text": "We conduct the experiments on extensively collected motion-prompt pairs, and show that ControlVideo outperforms alternative competitors qualitatively and quantitatively. Thanks to the efficient designs, ControlVideo produces short and long videos in several minutes using one NVIDIA 2080Ti. ",
72
+ "page_idx": 1
73
+ },
74
+ {
75
+ "type": "text",
76
+ "text": "In summary, our contributions are presented as follows: ",
77
+ "page_idx": 1
78
+ },
79
+ {
80
+ "type": "text",
81
+ "text": "• We propose training-free ControlVideo with interleaved-frame smoother for consistent and continuous controllable text-to-video generation. \n• Interleaved-frame smoother alternately smooths out the latents of three-frame clips, effectively stabilizing the entire video during sampling. \n• We empirically demonstrate the superior consistency and quality of fully cross-frame interaction, while presenting a hierarchical sampler for long-video generation in commodity GPUs. ",
82
+ "page_idx": 1
83
+ },
84
+ {
85
+ "type": "text",
86
+ "text": "2 BACKGROUND ",
87
+ "text_level": 1,
88
+ "page_idx": 1
89
+ },
90
+ {
91
+ "type": "text",
92
+ "text": "Latent diffusion model (LDM) (Rombach et al., 2022) is an efficient variant of diffusion models (Ho et al., 2020) by applying the diffusion process in the latent space. LDM uses an encoder to compress an image $_ { \\textbf { \\em x } }$ into latent code $z = ( { \\pmb x } )$ . It learns the distribution of image latent codes $z _ { 0 } \\sim p _ { d a t a } ( z _ { 0 } )$ in a DDPM formulation (Ho et al., 2020), including a forward and a backward process. The forward diffusion process gradually adds gaussian noise at each timestep $t$ to obtain ${ \\boldsymbol { z } } _ { t }$ : ",
93
+ "page_idx": 1
94
+ },
95
+ {
96
+ "type": "equation",
97
+ "img_path": "images/a5cb6ae96f61044d0fd8e242d97d486685d609e3f6aae6234ad20f4560cf0eee.jpg",
98
+ "text": "$$\nq ( z _ { t } | z _ { t - 1 } ) = \\mathcal { N } ( z _ { t } ; \\sqrt { 1 - \\beta _ { t } } z _ { t - 1 } , \\beta _ { t } I ) ,\n$$",
99
+ "text_format": "latex",
100
+ "page_idx": 1
101
+ },
102
+ {
103
+ "type": "image",
104
+ "img_path": "images/be5a86338f5f0690c18fbffc176104780b244c71015a3a6e2bcaf751230024ca.jpg",
105
+ "image_caption": [
106
+ "Figure 2: Overview of ControlVideo. For consistency in appearance, ControlVideo adapts ControlNet to the video counterpart by adding cross-frame interaction into self-attention modules. To further improve video continuity, interleaved-frame smoother is introduced to stabilize video latents during denosing (see Alg. 1 for details). "
107
+ ],
108
+ "image_footnote": [],
109
+ "page_idx": 2
110
+ },
111
+ {
112
+ "type": "text",
113
+ "text": "where $\\{ \\beta _ { t } \\} _ { t = 1 } ^ { T }$ are the scale of noises, and $T$ denotes the number of diffusion timesteps. The backward denoising process reverses the above diffusion process to predict less noisy $z _ { t - 1 }$ : ",
114
+ "page_idx": 2
115
+ },
116
+ {
117
+ "type": "equation",
118
+ "img_path": "images/2b0f54ffa0f01bc6794306dbb8572448fa74cb384e33fc93c8bbc3de91b9cfbc.jpg",
119
+ "text": "$$\np _ { \\theta } ( z _ { t - 1 } | z _ { t } ) = \\mathcal { N } ( z _ { t - 1 } ; \\mu _ { \\theta } ( z _ { t } , t ) , \\Sigma _ { \\theta } ( z _ { t } , t ) ) .\n$$",
120
+ "text_format": "latex",
121
+ "page_idx": 2
122
+ },
123
+ {
124
+ "type": "text",
125
+ "text": "The $\\mu _ { \\theta }$ and $\\Sigma _ { \\theta }$ are implemented with a denoising model $\\epsilon _ { \\theta }$ with learnable parameters $\\theta$ . When generating new samples, we start from $z _ { T } \\sim \\mathcal { N } ( 0 , 1 )$ and employ DDIM sampling to predict $z _ { t - 1 }$ of previous timestep: ",
126
+ "page_idx": 2
127
+ },
128
+ {
129
+ "type": "equation",
130
+ "img_path": "images/30380d65eff514274763db2594ab67123df1cf7fdf4836ee6b39219613997c26.jpg",
131
+ "text": "$$\n\\begin{array} { r } { z _ { t - 1 } = \\sqrt { \\alpha _ { t - 1 } } \\underbrace { \\left( \\frac { z _ { t } - \\sqrt { 1 - \\alpha _ { t } } \\epsilon _ { \\theta } ( z _ { t } , t ) } { \\sqrt { \\alpha _ { t } } } \\right) } _ { \\substack { \\mathrm { ~ \\triangleq ~ p r e d i c t e d } z _ { 0 } \\mathrm { , ~ } } } + \\underbrace { \\sqrt { 1 - \\alpha _ { t - 1 } } \\cdot \\epsilon _ { \\theta } ( z _ { t } , t ) } _ { \\substack { \\mathrm { ~ \\triangleq ~ d i r e c t i o n ~ p o i n t i n g ~ t o ~ } z _ { t } \\mathrm { , ~ } } } , } \\end{array}\n$$",
132
+ "text_format": "latex",
133
+ "page_idx": 2
134
+ },
135
+ {
136
+ "type": "text",
137
+ "text": "where $\\begin{array} { r } { \\alpha _ { t } = \\prod _ { i = 1 } ^ { t } ( 1 - \\beta _ { i } ) } \\end{array}$ . We use $z _ { t 0 }$ to represent “predicted $z _ { \\mathrm { 0 } } ^ { \\mathrm { , , } }$ at timestep $t$ for simplicity. Note that we use Stable Diffusion (SD) $\\epsilon _ { \\theta } ( z _ { t } , t , \\tau )$ as our base model, which is an instantiation of text-guided LDMs pre-trained on billions of image-text pairs. $\\tau$ denotes the text prompt. ",
138
+ "page_idx": 2
139
+ },
140
+ {
141
+ "type": "text",
142
+ "text": "ControlNet (Zhang & Agrawala, 2023) enables SD to support more controllable input conditions during text-to-image synthesis, e.g., depth maps, poses, edges, etc. The ControlNet uses the same U-Net (Ronneberger et al., 2015) architecture as SD and finetunes its weights to support taskspecific conditions, converting $\\epsilon _ { \\theta } ( z _ { t } , t , \\tau )$ to $\\epsilon _ { \\theta } ( z _ { t } , t , c , \\tau )$ , where $^ c$ denotes additional conditions. To distinguish the U-Net architectures of SD and ControlNet, we denote the former as the main $U _ { ☉ }$ -Net while the latter as the auxiliary $U$ -Net. ",
143
+ "page_idx": 2
144
+ },
145
+ {
146
+ "type": "text",
147
+ "text": "3 CONTROLVIDEO ",
148
+ "text_level": 1,
149
+ "page_idx": 2
150
+ },
151
+ {
152
+ "type": "text",
153
+ "text": "Controllable text-to-video generation aims to produce a video of length $N$ conditioned on motion sequences $\\boldsymbol { c } = \\{ c ^ { i } \\} _ { i = 0 } ^ { N - 1 }$ and a text prompt $\\tau$ . As illustrated in Fig. 2, we propose ControlVideo with interleaved-frame smoother towards consistent and continuous video generation. ControlVideo, adapted from ControlNet, adds cross-frame interaction to self-attention modules for frame consistency (in Sec. 3.1). To ensure video continuity, interleaved-frame smoother divides all three-frame clips into even and odd clips, and separately smooths out their corresponding latents at different denoising steps (in Sec. 3.2). Finally, we further investigate the cross-frame mechanisms in terms of effectiveness and efficiency, including fully cross-frame interaction and hierarchical sampler (in Sec. 3.3). ",
154
+ "page_idx": 2
155
+ },
156
+ {
157
+ "type": "text",
158
+ "text": "3.1 PRELIMINARY ",
159
+ "text_level": 1,
160
+ "page_idx": 2
161
+ },
162
+ {
163
+ "type": "text",
164
+ "text": "The main challenge of adapting text-to-image models to the video counterpart is to ensure temporal consistency. Leveraging the controllability of ControlNet, motion sequences could provide coarselevel consistency in structure. Nonetheless, due to the lack of temporal interaction, individually producing each frame with ControlNet leads to drastic inconsistency in appearance (see row 2 in ",
165
+ "page_idx": 2
166
+ },
167
+ {
168
+ "type": "text",
169
+ "text": "Algorithm 1 Interleaved-frame smoother ",
170
+ "text_level": 1,
171
+ "page_idx": 3
172
+ },
173
+ {
174
+ "type": "text",
175
+ "text": "Require: $z _ { t } = \\{ z _ { t } ^ { i } \\} _ { i = 0 } ^ { N - 1 }$ , $\\boldsymbol { c } = \\{ c ^ { i } \\} _ { i = 0 } ^ { N - 1 }$ , τ , timestep t. \n1: zt→0 ← zt− 1−αtϵθ(zt,t,c,τ )√ . ▷ predict clean latents 2: $\\pmb { x } _ { t 0 } \\mathscr { D } ( \\pmb { z } _ { t 0 } ) ; \\tilde { \\pmb { x } } _ { t 0 } \\pmb { x } _ { t 0 }$ ▷ convert latents to $R G B$ space 3: if $( t \\ \\mathrm { ~ m o d ~ } 2 ) = 0$ then $\\triangleright$ smooth all even three-frame clips $\\cdot$ 4: for $\\cdot$ from 0 to $\\cdot$ do \n5: x˜2kt→0 ← Interpolate(x2k−1t→0 , x2k+1t→0 ) oth all odd three-frame clips \n6: else if $( t \\ \\mathrm { ~ m o d ~ } 2 ) = 1$ then $\\triangleright$ $( \\tilde { x } _ { t 0 } ^ { 2 k } , \\tilde { x } _ { t 0 } ^ { 2 k + 1 } , \\tilde { x } _ { t 0 } ^ { 2 k + 2 } )$ $k$ $N / 2$ \n$\\begin{array} { r l r } { \\} : } & { { } \\lfloor } & { \\tilde { \\boldsymbol { x } } _ { t 0 } ^ { 2 k + 1 } \\mathrm { I n t e r p o l a t e } ( \\boldsymbol { x } _ { t 0 } ^ { 2 k } , \\boldsymbol { x } _ { t 0 } ^ { 2 k + 2 } ) } \\end{array}$ \n9: $\\tilde { z } _ { t 0 } \\mathcal { E } ( \\tilde { x } _ { t 0 } )$ ▷ convert frames to latent space 10: $z _ { t - 1 } \\gets \\sqrt { \\alpha _ { t - 1 } } \\tilde { z } _ { t \\to 0 } + \\sqrt { 1 - \\alpha _ { t - 1 } } \\cdot \\epsilon _ { \\theta } ( z _ { t } , t , c , \\tau ) .$ . ▷ predict less noisy latent 11: return zt−1 ",
176
+ "page_idx": 3
177
+ },
178
+ {
179
+ "type": "text",
180
+ "text": "Fig. 5). Similar to previous works (Wu et al., 2022b; Khachatryan et al., 2023), we also extend original self-attention of SD U-Net to cross-frame attention, so that the video content could be temporally shared via inter-frame interaction. ",
181
+ "page_idx": 3
182
+ },
183
+ {
184
+ "type": "text",
185
+ "text": "In specific, ControlVideo inflates the main U-Net from Stable Diffusion along the temporal axis, while keeping the auxiliary U-Net from ControlNet. Analogous to (Ho et al., 2022b; Wu et al., 2022b; Khachatryan et al., 2023), it directly converts 2D convolution layers to 3D counterpart by replacing $3 \\times 3$ kernels with $1 \\times 3 \\times 3$ kernels. Self-attention is converted to cross-frame attention by querying from other frames as: ",
186
+ "page_idx": 3
187
+ },
188
+ {
189
+ "type": "equation",
190
+ "img_path": "images/efcf020bf43e4bf5ad815d356a5495dd4fab1f7931dfc1eaac168aced53a6ad7.jpg",
191
+ "text": "$$\n\\mathrm { A t t e n t i o n } ( Q , K , V ) = \\mathrm { S o f t m a x } \\big ( \\frac { Q K ^ { T } } { \\sqrt { d } } \\big ) \\cdot V , \\mathrm { ~ w h e r e ~ } Q = W ^ { Q } z _ { t } ^ { i } , ~ K = W ^ { K } \\tilde { z } _ { t } , ~ V = W ^ { V } \\tilde { z } _ { t } ,\n$$",
192
+ "text_format": "latex",
193
+ "page_idx": 3
194
+ },
195
+ {
196
+ "type": "text",
197
+ "text": "where $W ^ { Q } , W ^ { K }$ , and $W ^ { V }$ project ${ \\boldsymbol { z } } _ { t }$ into query, key, and value, respectively. $ { \\boldsymbol { z } } _ { t } ^ { i }$ and $\\widetilde { z } _ { t }$ denote ith latent frame and the latents of reference frames at timestep $t$ e. We will discuss the choices of cross-frame mechanisms (i.e., reference frames) in Sec. 3.3 ",
198
+ "page_idx": 3
199
+ },
200
+ {
201
+ "type": "text",
202
+ "text": "3.2 INTERLEAVED-FRAME SMOOTHER ",
203
+ "text_level": 1,
204
+ "page_idx": 3
205
+ },
206
+ {
207
+ "type": "text",
208
+ "text": "Albeit cross-frame interaction promisingly keeps frame consistency in appearance, they are still visibly flickering in structure. Discrete motion sequences only ensure coarse-level structural consistency, not sufficient to keep the continuous inter-frame transition. Intuitively, a continuous video could be considered as multiple continuous three-frame clips, so we simplify the problem of ensuring the video continuity to ensuring all three-frame clips continuous. ",
209
+ "page_idx": 3
210
+ },
211
+ {
212
+ "type": "text",
213
+ "text": "Inspired by this, we propose an interleaved-frame smoother to enable continuous video generation. In Alg. 1, interleaved-frame smoother divides all three-frame clips into even and odd clips based on indices of middle frames, and individually smooths their corresponding latents at different timesteps. To stabilize the latent of each clip, we first convert it to predicted RGB frames with DDIM, following by replacing middle frame with the interpolated frame. ",
214
+ "page_idx": 3
215
+ },
216
+ {
217
+ "type": "text",
218
+ "text": "Specifically, at timestep $t$ , we first predict the clean video latent $z _ { t 0 }$ according to ${ \\boldsymbol { z } } _ { t }$ ",
219
+ "page_idx": 3
220
+ },
221
+ {
222
+ "type": "equation",
223
+ "img_path": "images/edd6f7b13ba48b86192971510711687b24c977f60ccf4332342eafc8db8863d7.jpg",
224
+ "text": "$$\nz _ { t 0 } = \\frac { z _ { t } - \\sqrt { 1 - \\alpha _ { t } } \\epsilon _ { \\theta } ( z _ { t } , t , c , \\tau ) } { \\sqrt { \\alpha _ { t } } } .\n$$",
225
+ "text_format": "latex",
226
+ "page_idx": 3
227
+ },
228
+ {
229
+ "type": "text",
230
+ "text": "After projecting $z _ { t 0 }$ into a RGB video ${ \\pmb x } _ { t 0 } = \\mathcal { D } ( { \\pmb z } _ { t 0 } )$ , we convert it to a more smoothed video $\\tilde { \\mathbf { x } } _ { t 0 }$ by replacing each middle frame with the interpolated one. Based on smoothed video latent $\\tilde { z } _ { t 0 } = \\mathcal { E } ( \\tilde { { x } } _ { t 0 } )$ , we compute the less noisy latent $z _ { t - 1 }$ following DDIM denoising in Eq. 3: ",
231
+ "page_idx": 3
232
+ },
233
+ {
234
+ "type": "equation",
235
+ "img_path": "images/1b038ac1a6ef6451b43c8a60fb82bb4f34d3f7cbeedc269d5ed65cae68951a5a.jpg",
236
+ "text": "$$\nz _ { t - 1 } = \\sqrt { \\alpha _ { t - 1 } } \\tilde { z } _ { t 0 } + \\sqrt { 1 - \\alpha _ { t - 1 } } \\cdot \\epsilon _ { \\theta } ( z _ { t } , t , c , \\tau ) .\n$$",
237
+ "text_format": "latex",
238
+ "page_idx": 3
239
+ },
240
+ {
241
+ "type": "text",
242
+ "text": "We note that the above process is only performed at a few intermediate timesteps, the individuality and quality of interpolated frames are also well retained by the following denoising steps. Additionally, the newly computational burden can be negligible (See Table 3). ",
243
+ "page_idx": 3
244
+ },
245
+ {
246
+ "type": "image",
247
+ "img_path": "images/bd1ecad5220209f938742c14bf7b9e45c444bf29c8c74cb82af70d240a2ebee5.jpg",
248
+ "image_caption": [
249
+ "Figure 3: Qualitative comparisons conditioned on depth maps and canny edges. Our ControlVideo produces videos with better (a) appearance consistency and (b) video quality than others. In contrast, Tune-A-Video fails to inherit structures from source videos, while Text2Video-Zero brings visible artifacts in large motion videos. See videos at qualitative comparisons. "
250
+ ],
251
+ "image_footnote": [],
252
+ "page_idx": 4
253
+ },
254
+ {
255
+ "type": "text",
256
+ "text": "3.3 CROSS-FRAME MECHANISMS FOR EFFECTIVENESS AND EFFICIENCY ",
257
+ "text_level": 1,
258
+ "page_idx": 4
259
+ },
260
+ {
261
+ "type": "text",
262
+ "text": "Fully cross-frame interaction. Previous works (Wu et al., 2022b; Khachatryan et al., 2023) usually replace self-attention with sparser cross-frame mechanisms, e.g., taking the reference frames as first or previous frames. Such mechanisms will increase the discrepancy between the query and key in self-attention modules, resulting in the degradation of video quality and consistency. In contrast, fully cross-frame interaction considers all frames as reference (i.e., becoming a “large image”), so has a less generation gap with text-to-image models. We conduct comparison experiments on above mechanisms in Fig. 5 and Table 3. Despite slightly more computational burden, fully cross-frame interaction empirically shows better consistency and quality than the sparser counterparts. ",
263
+ "page_idx": 4
264
+ },
265
+ {
266
+ "type": "text",
267
+ "text": "Hierarchical sampler. Applying existing cross-frame mechanisms for long-video generation suffers from either heavy computational burden or long-term inconsistency, limiting the practicability of ControlVideo. For more efficient long-video synthesis, we introduce a hierarchical sampler to produce a long video clip-by-clip, which is implemented with two types of cross-frame mechanisms. At each timestep, a long video $\\bar { z } _ { t } = \\{ z _ { t } ^ { i } \\} _ { i = 0 } ^ { N - 1 }$ is separated into multiple short video clips with the selected kedenoted as $z _ { t } ^ { k e y } = \\{ z _ { t } ^ { k N _ { c } } \\} _ { k = 0 } ^ { \\frac { N } { N _ { c } } }$ , where each clip is of length , we pre-generate the key fra $N _ { c } - 1$ and the h fully c $k$ th clip isss-frame $\\widehat { \\pmb { z } } _ { t } ^ { k } = \\{ { \\pmb z } _ { t } ^ { j } \\} _ { j = k N _ { c } + 1 } ^ { ( k + 1 ) N _ { c } - 1 }$ Then mes wit ro attention for long-range coherence, where reference frames are = {zkNct } NNck=0. Conditioned on each pair of key frames, i.e., reference frames as $\\{ z _ { t } ^ { k N _ { c } } , z _ { t } ^ { ( k + 1 ) N _ { c } } \\}$ z(k+1)Nct }, we sequentially synthesize their corresponding clip $\\widehat { z } _ { t } ^ { k }$ holding the holistic consistency. ",
268
+ "page_idx": 4
269
+ },
270
+ {
271
+ "type": "text",
272
+ "text": "4 EXPERIMENTS ",
273
+ "text_level": 1,
274
+ "page_idx": 4
275
+ },
276
+ {
277
+ "type": "text",
278
+ "text": "4.1 EXPERIMENTAL SETTINGS ",
279
+ "text_level": 1,
280
+ "page_idx": 4
281
+ },
282
+ {
283
+ "type": "text",
284
+ "text": "Implementation details. ControlVideo is adapted from ControlNet 1 (Zhang & Agrawala, 2023) , and our interleaved-frame smoother employs a lightweight RIFE (Huang et al., 2022) to interpolate the middle frame of each three-frame clip. The synthesized short videos are of length 15, while the long videos usually contain about 100 frames. Unless otherwise noted, their resolution is both $5 1 2 \\times 5 1 2$ . During sampling, we adopt DDIM sampling (Song et al., 2020a) with 50 timesteps, and interleaved-frame smoother is performed on predicted RGB frames at timesteps $\\{ 3 0 , 3 1 \\}$ by default. With the efficient implementation of xFormers (Lefaudeux et al., 2022), ControVideo could produce both short and long videos with one NVIDIA RTX 2080Ti in about 2 and 10 minutes, respectively. ",
285
+ "page_idx": 4
286
+ },
287
+ {
288
+ "type": "table",
289
+ "img_path": "images/7c6847f106fb317fd3455b3b9a36a117ec690add5e3e041420f2b4c7b07d498e.jpg",
290
+ "table_caption": [
291
+ "Table 1: Quantitative comparisons of ControlVideo with other methods. We evaluate them on 125 motion-prompt pairs in terms of consistency, and the best results are bolded. "
292
+ ],
293
+ "table_footnote": [],
294
+ "table_body": "<table><tr><td>METHOD</td><td>Structure Condition</td><td>FC(×10-2)</td><td>PC(×10-2)</td><td>WE(×10-2)</td></tr><tr><td>Tune-A-Video Wu et al. (2022b)</td><td>DDIM Inversion</td><td>94.53</td><td>31.57</td><td>18.16</td></tr><tr><td>Text2Video-Zero Khachatryan et al. (2023) ControlVideo (ours)</td><td>Canny Edge Canny Edge</td><td>95.17 96.83</td><td>30.74 30.75</td><td>8.76 2.75</td></tr><tr><td>Text2Video-Zero Khachatryan et al. (2023) ControlVideo (ours)</td><td>Depth Map Depth Map</td><td>95.99 97.22</td><td>31.69 31.81</td><td>10.36 5.81</td></tr></table>",
295
+ "page_idx": 5
296
+ },
297
+ {
298
+ "type": "text",
299
+ "text": "",
300
+ "page_idx": 5
301
+ },
302
+ {
303
+ "type": "text",
304
+ "text": "Datasets. To evaluate our ControlVideo, we collect 25 object-centric videos from DAVIS dataset (Pont-Tuset et al., 2017) and manually annotate their source descriptions. Then, for each source description, ChatGPT (OpenAI, 2022) is utilized to generate five editing prompts automatically, resulting in 125 video-prompt pairs in total. Finally, we employ Canny and MiDaS DPT-Hybrid model (Ranftl et al., 2020) to estimate the edges and depth maps of source videos, and form 125 motion-prompt pairs as our evaluation dataset. More details are provided in Appendix A. ",
305
+ "page_idx": 5
306
+ },
307
+ {
308
+ "type": "text",
309
+ "text": "Metrics. We evaluate the video quality from three perspectives. (i) Frame consistency (FC): the average cosine similarity between all pairs of consecutive frames, and (ii) Prompt consistency (PC): the average cosine similarity between input prompt and all video frames. (iii) Warping error (WE) (Lai et al., 2018): the average error between all frames and their warped frames using optical flow. ",
310
+ "page_idx": 5
311
+ },
312
+ {
313
+ "type": "text",
314
+ "text": "Baselines. We compare our ControlVideo with three publicly available methods: (i) Tune-AVideo (Wu et al., 2022b) extends Stable Diffusion to the video counterpart by finetuning it on a source video. During inference, it uses the DDIM inversion codes of source videos to provide structure guidance. (ii) Text2Video-Zero (Khachatryan et al., 2023) is based on ControlNet, and employs the first-only cross-frame attention on Stable Diffusion without finetuning. (iii) Follow-Your-Pose (Ma et al., 2023) is initialized with Stable Diffusion, and is finetuned on LAION-Pose (Ma et al., 2023) to support human pose conditions. After that, it is trained on millions of videos (Xue et al., 2022) to enable temporally-consistent video generation. ",
315
+ "page_idx": 5
316
+ },
317
+ {
318
+ "type": "text",
319
+ "text": "4.2 QUALITATIVE AND QUANTITATIVE COMPARISONS ",
320
+ "text_level": 1,
321
+ "page_idx": 5
322
+ },
323
+ {
324
+ "type": "text",
325
+ "text": "Qualitative results. Fig. 3 first illustrates the visual comparisons of synthesized videos conditioned on both (a) depth maps and (b) canny edges. As shown in Fig. 3 (a), our ControlVideo demonstrates better consistency in both appearance and structure than alternative competitors. Tune-A-Video fails to keep the temporal consistency of both appearance and fine-grained structure, e.g., the color of coat and the structure of road. With the motion information from depth maps, Text2Video-Zero achieves promising consistency in structure, but still struggles with incoherent appearance in videos e.g., the color of coat. Besides, ControlVideo also performs more robustly when dealing with large motion inputs. As illustrated in Fig. 3 (b), Tune-A-Video ignores the structure information from source videos. Text2Video-Zero adopts the first-only cross-frame mechanism to trade off frame quality and appearance consistency, and generates later frames with visible artifacts. In contrast, with the proposed fully cross-frame mechanism and interleaved-frame smoother, our ControlVideo can handle large motion to generate high-quality and consistent videos. ",
326
+ "page_idx": 5
327
+ },
328
+ {
329
+ "type": "text",
330
+ "text": "Fig. 4 further shows the comparison conditioned on human poses. From Fig. 4, Tune-A-Video only maintains the coarse structures of the source video, i.e., human position. Text2Video-Zero and Follow-Your-Pose produce video frames with inconsistent appearance, e.g., changing faces of iron man (in row 4) or disappearing objects in the background (in row 5). In comparison, our ControlVideo performs more consistent video generation, demonstrating its superiority. More qualitative comparisons are provided in Appendix D. ",
331
+ "page_idx": 5
332
+ },
333
+ {
334
+ "type": "table",
335
+ "img_path": "images/47c023f74e078faa85a85c67508f4310ea9c2fecc7c1a0196ef7912c21e0bf5c.jpg",
336
+ "table_caption": [
337
+ "Table 2: User preference study. The numbers denote the percentage of raters who favor the videos synthesized by our ControlVideo over other methods. "
338
+ ],
339
+ "table_footnote": [],
340
+ "table_body": "<table><tr><td>Method Comparison</td><td>Video Quality</td><td>Temporal Consistency</td><td>Text Alignment</td></tr><tr><td>Ours vs. Tune-A-Video Wu et al. (2022b)</td><td>73.6%</td><td>83.2%</td><td>68.0%</td></tr><tr><td>Ours vs. Text2Video-Zero Khachatryan et al. (2023)</td><td>76.0%</td><td>81.6%</td><td>65.6%</td></tr></table>",
341
+ "page_idx": 6
342
+ },
343
+ {
344
+ "type": "image",
345
+ "img_path": "images/d80c47a0e5e135476ad15387cd5c235ac3e5dc78f1d8d4a8a062bb3245191e87.jpg",
346
+ "image_caption": [
347
+ "Figure 4: Qualitative comparisons on poses. Tune-A-Video only preserves original human positions, while Text2Video-Zero and FollowYour-Pose produce frames with appearance incoherence. Our ControlVideo achieves better consistency in both structure and appearance. See videos at qualitative comparisons. "
348
+ ],
349
+ "image_footnote": [],
350
+ "page_idx": 6
351
+ },
352
+ {
353
+ "type": "image",
354
+ "img_path": "images/1dac4c1bcf0219c6994391946d507e7cf5ee9c3569df7ab1ab968a0c48f34306.jpg",
355
+ "image_caption": [
356
+ "Figure 5: Qualitative ablation studies on cross-frame mechanisms and interleaved-frame smoother. Fully cross-frame interaction produces video frames with higher quality and consistency than other mechanisms, and adding the smoother further enhances the video smoothness. See corresponding videos for better comparison. "
357
+ ],
358
+ "image_footnote": [],
359
+ "page_idx": 6
360
+ },
361
+ {
362
+ "type": "text",
363
+ "text": "Quantitative results. We have also compared our ControlVideo with existing methods quantitatively on 125 video-prompt pairs. From Table 1, our ControlVideo conditioned on depth outperforms the state-of-the-art methods in terms of all metrics, which is consistent with the qualitative results. In contrast, despite finetuning on a source video, Tune-A-Video still struggles to produce temporally coherent videos. Although conditioned on the same structure information, Text2VideoZero obtains worse frame consistency and warping error than ControlVideo. For each method, the depth-conditioned models generate videos with higher frame and prompt consistency than the canny-condition counterpart, since depth maps provide smoother motion information. ",
364
+ "page_idx": 6
365
+ },
366
+ {
367
+ "type": "text",
368
+ "text": "4.3 USER STUDY ",
369
+ "text_level": 1,
370
+ "page_idx": 6
371
+ },
372
+ {
373
+ "type": "text",
374
+ "text": "We then perform the user study to compare our ControlVideo conditioned on depth maps with other competing methods. In specific, we provide each rater a structure sequence, a text prompt, and synthesized videos from two different methods (in random order). Then we ask them to select the better synthesized videos for each of three measurements: (i) video quality, (ii) temporal consistency throughout all frames, and (iii) text alignment between prompts and synthesized videos. The evaluation set consists of 125 representative structure-prompt pairs. Each pair is evaluated by 5 raters, and we take a majority vote for the final result. From Table 2, the raters strongly favor our synthesized videos from all three perspectives, especially in temporal consistency. On the other hand, Tune-A-Video fails to generate consistent and high-quality videos with only DDIM inversion for structural guidance, and Text2Video-Zero also produces videos with lower quality and coherency. ",
375
+ "page_idx": 6
376
+ },
377
+ {
378
+ "type": "table",
379
+ "img_path": "images/38f742f0c241e64a957542908e88d705e4b849251511ae35e8e4765401e43f01.jpg",
380
+ "table_caption": [
381
+ "Table 3: Quantitative ablation studies on cross-frame mechanisms and interleaved-frame smoother. The results indicate that our fully cross-frame mechanism achieves better frame consistency than other mechanisms, and the interleaved-frame smoother significantly improves the frame consistency. ",
382
+ "a steamship on the ocean, at sunset, sketch style "
383
+ ],
384
+ "table_footnote": [],
385
+ "table_body": "<table><tr><td>Cross-Frame Mechanism</td><td>FC(×10-2)</td><td>PC (×10-2)</td><td>WE(×10-2)</td><td>Time Cost (min)</td></tr><tr><td>Individual</td><td>89.94</td><td>30.79</td><td>20.13</td><td>1.2</td></tr><tr><td>First-only</td><td>94.92</td><td>30.54</td><td>8.91</td><td>1.2</td></tr><tr><td>Sparse-Causal</td><td>95.06</td><td>30.59</td><td>7.05</td><td>1.5</td></tr><tr><td>Fully</td><td>95.36</td><td>30.76</td><td>5.93</td><td>3.0</td></tr><tr><td>Fully + Smoother</td><td>96.83</td><td>30.79</td><td>2.75</td><td>3.5</td></tr></table>",
386
+ "page_idx": 7
387
+ },
388
+ {
389
+ "type": "image",
390
+ "img_path": "images/5831b0842b887e81d40a454484c1f1e84c71afb1d4e70c088e7d698fb2be789e.jpg",
391
+ "image_caption": [
392
+ "Figure 6: A long video produced with our hierarchical sampling. Motion sequences are shown on the top left. Using the efficient sampler, our ControlVideo generates a high-quality long video with the holistic consistency. See videos at long video generation. "
393
+ ],
394
+ "image_footnote": [],
395
+ "page_idx": 7
396
+ },
397
+ {
398
+ "type": "text",
399
+ "text": "4.4 ABLATION STUDY ",
400
+ "text_level": 1,
401
+ "page_idx": 7
402
+ },
403
+ {
404
+ "type": "text",
405
+ "text": "Effect of fully cross-frame interaction. To demonstrate the effectiveness of the fully cross-frame interaction, we conduct a comparison with the following variants: i) individual: no interaction between all frames, ii) first-only: all frames attend to the first one, iii) sparse-causal: each frame attends to the first and former frames, iv) fully: our fully cross-frame, refer to Sec. 3. Note that, all the above models are extended from ControlNet without any finetuning. The qualitative and quantitative results are shown in Fig. 5 and Table 3, respectively. From Fig. 5, the individual cross-frame mechanism suffers from severe temporal inconsistency, e.g., colorful and black-and-white frames. The first-only and sparse-causal mechanisms reduce some appearance inconsistency by adding crossframe interaction. However, they still produce videos with structural inconsistency and visible artifacts, e.g., the orientation of the elephant and duplicate nose (row 3 in Fig. 5). In contrast, due to less generation gap with ControlNet, our fully cross-frame interaction performs better appearance coherency and video quality. Though the introduced interaction brings an extra $1 \\sim 2 \\times$ time cost, it is acceptable for a high-quality video generation. ",
406
+ "page_idx": 7
407
+ },
408
+ {
409
+ "type": "text",
410
+ "text": "Effect of interleaved-frame smoother. We further analyze the effect of the proposed interleavedframe smoother. From Table 3 and last two rows of Fig. 5, our interleaved-frame smoother greatly improves the video smoothness, e.g., mitigating structural flickers in red boxes. We provide more ablation studies on the timestep choices of the smoother in Appendix C and ablation studies. ",
411
+ "page_idx": 7
412
+ },
413
+ {
414
+ "type": "text",
415
+ "text": "4.5 EXTENSION TO LONG-VIDEO GENERATION",
416
+ "text_level": 1,
417
+ "page_idx": 7
418
+ },
419
+ {
420
+ "type": "text",
421
+ "text": "Producing a long video usually requires an advanced GPU with high memory. With the proposed hierarchical sampler, our ControlVideo achieves long video generation (more than 100 frames) in a memory-efficient manner. As shown in Fig. 6, our ControlVideo can produce a long video with consistently high quality. Notably, benefiting from our efficient sampling, it only takes approximately ten minutes to generate 100 frames with resolution $5 1 2 \\times 5 1 2$ in one NVIDIA RTX 2080Ti. More visualizations of long videos can be found in Appendix D. ",
422
+ "page_idx": 7
423
+ },
424
+ {
425
+ "type": "text",
426
+ "text": "5 RELATED WORK ",
427
+ "text_level": 1,
428
+ "page_idx": 8
429
+ },
430
+ {
431
+ "type": "text",
432
+ "text": "Text-to-image synthesis. Through pre-training on billions of image-text pairs, large-scale generative models (Nichol et al., 2021; Balaji et al., 2022; Saharia et al., 2022; Ramesh et al., 2022; Rombach et al., 2022; Ramesh et al., 2021; Chang et al., 2023; Ding et al., 2021; 2022; Yu et al., 2022; Sauer et al., 2023; Kang et al., 2023; Huang et al., 2023) have made remarkable progress in creative and photo-realistic visual generation. Various frameworks have been explored to enhance image quality, including GANs (Goodfellow et al., 2020; Sauer et al., 2023; Kang et al., 2023), autoregressive models (Nichol et al., 2021; Chang et al., 2023; Ding et al., 2021; 2022; Yu et al., 2022), and diffusion models (Ho et al., 2020; Balaji et al., 2022; Saharia et al., 2022; Ramesh et al., 2022; Rombach et al., 2022). Among these generative models, diffusion-based models are well open-sourced and popularly applied to several downstream tasks, such as image editing (Hertz et al., 2022; Meng et al., 2021) and customized generation (Gal et al., 2022; Wei et al., 2023; Kumari et al., 2022; Ruiz et al., 2022). Besides text prompts, several works (Zhang & Agrawala, 2023; Mou et al., 2023) also introduce additional structure conditions to pre-trained text-to-image diffusion models for controllable text-to-image generation. Our ControlVideo is implemented based on the controllable text-to-image models to inherit their ability of high-quality and consistent generation. ",
433
+ "page_idx": 8
434
+ },
435
+ {
436
+ "type": "text",
437
+ "text": "Text-to-video synthesis. Large text-to-video generative models usually extend text-to-image models by adding temporal consistency. Earlier works (Wu et al., 2022a; Hong et al., 2022; Wu et al., 2021; Villegas et al., 2022) adopt an autoregressive framework to synthesize videos according to given descriptions. Capitalizing on the success of diffusion models in image generation, recent works (Ho et al., 2022a;b; Singer et al., 2022) propose to leverage their potential to produce high-quality videos. Nevertheless, training such large-scale video generative models requires extensive video-text pairs and computational resources. To reduce the training burden, Gen-1 (Esser et al., 2023) and FollowYour-Pose (Ma et al., 2023) provide coarse temporal information (e.g., motion sequences) for video generation, yet are still costly for most researchers and users. By replacing self-attention with the sparser cross-frame mechanisms, Tune-A-Video (Wu et al., 2022b) and Text2Video-Zero (Khachatryan et al., 2023) keep considerable consistency in appearance with little finetuning. ControlVideo also adapts text-to-image diffusion models without any training, but generates videos with better temporal consistency and continuity. ",
438
+ "page_idx": 8
439
+ },
440
+ {
441
+ "type": "text",
442
+ "text": "6 DISCUSSION ",
443
+ "text_level": 1,
444
+ "page_idx": 8
445
+ },
446
+ {
447
+ "type": "text",
448
+ "text": "In this paper, we present a training-free framework, namely ControlVideo, towards consistent and continuous controllable text-to-video generation. ControlVideo, inflated from ControlNet, introduces an interleaved-frame smoother to ensure video continuity. Particularly, interleaved-frame smoother alternately smooths out the latents of three-frame clips, and stabilizes each clip by updating the middle frame with the interpolation among other two frames in latent space. Moreover, we empirically demonstrate the superior performance of fully cross-frame interaction, while presenting hierarchical sampler for long-video generation in commodity GPUs. Quantitative and qualitative experiments on extensive motion-prompt pairs demonstrate that ControlVideo achieves state-of-the-arts in terms of frame consistency and video continuity. ",
449
+ "page_idx": 8
450
+ },
451
+ {
452
+ "type": "text",
453
+ "text": "Broader impact. Large-scale diffusion models have made tremendous progress in text-to-video synthesis, yet these models are costly and unavailable to the public. ControlVideo focuses on trainingfree controllable text-to-video generation, and takes an essential step in efficient video creation. Concretely, ControlVideo could synthesize high-quality videos with commodity hardware, hence, being accessible to most researchers and users. For example, artists may leverage our approach to create fascinating videos with less time. Moreover, ControlVideo provides insights into the tasks involved in videoss, e.g., video rendering, video editing, and video-to-video translation. On the flip side, albeit we do not intend to use our model for harmful purposes, it might be misused and bring some potential negative impacts, such as producing deceptive, harmful, or explicit videos. Despite the above concerns, we believe that they could be well minimized with some steps. For example, an NSFW filter can be employed to filter out unhealthy and violent content. Also, we hope that the government could establish and improve relevant regulations to restrict the abuse of video creation. ",
454
+ "page_idx": 8
455
+ },
456
+ {
457
+ "type": "text",
458
+ "text": "ACKNOWLEDGEMENT ",
459
+ "text_level": 1,
460
+ "page_idx": 9
461
+ },
462
+ {
463
+ "type": "text",
464
+ "text": "This work was supported by National Key RD Program of China under Grant No. 2021ZD0112100, and the National Natural Science Foundation of China (NSFC) under Grant No. U19A2073. ",
465
+ "page_idx": 9
466
+ },
467
+ {
468
+ "type": "text",
469
+ "text": "REFERENCES \nYogesh Balaji, Seungjun Nah, Xun Huang, Arash Vahdat, Jiaming Song, Karsten Kreis, Miika Aittala, Timo Aila, Samuli Laine, Bryan Catanzaro, et al. ediffi: Text-to-image diffusion models with an ensemble of expert denoisers. arXiv preprint arXiv:2211.01324, 2022. \nHuiwen Chang, Han Zhang, Jarred Barber, AJ Maschinot, Jose Lezama, Lu Jiang, Ming-Hsuan Yang, Kevin Murphy, William T Freeman, Michael Rubinstein, et al. Muse: Text-to-image generation via masked generative transformers. arXiv preprint arXiv:2301.00704, 2023. \nMing Ding, Zhuoyi Yang, Wenyi Hong, Wendi Zheng, Chang Zhou, Da Yin, Junyang Lin, Xu Zou, Zhou Shao, Hongxia Yang, et al. Cogview: Mastering text-to-image generation via transformers. NeurIPS, 2021. \nMing Ding, Wendi Zheng, Wenyi Hong, and Jie Tang. Cogview2: Faster and better text-to-image generation via hierarchical transformers. arXiv preprint arXiv:2204.14217, 2022. \nPatrick Esser, Johnathan Chiu, Parmida Atighehchian, Jonathan Granskog, and Anastasis Germanidis. Structure and content-guided video synthesis with diffusion models. arXiv preprint arXiv:2302.03011, 2023. \nRinon Gal, Yuval Alaluf, Yuval Atzmon, Or Patashnik, Amit H Bermano, Gal Chechik, and Daniel Cohen-Or. An image is worth one word: Personalizing text-to-image generation using textual inversion. arXiv preprint arXiv:2208.01618, 2022. \nIan Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial networks. Communications of the ACM, 2020. \nAmir Hertz, Ron Mokady, Jay Tenenbaum, Kfir Aberman, Yael Pritch, and Daniel Cohen-Or. Promptto-prompt image editing with cross attention control. arXiv preprint arXiv:2208.01626, 2022. \nJonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffusion probabilistic models. NeurIPS, 2020. \nJonathan Ho, William Chan, Chitwan Saharia, Jay Whang, Ruiqi Gao, Alexey Gritsenko, Diederik P Kingma, Ben Poole, Mohammad Norouzi, David J Fleet, et al. Imagen video: High definition video generation with diffusion models. arXiv preprint arXiv:2210.02303, 2022a. \nJonathan Ho, Tim Salimans, Alexey Gritsenko, William Chan, Mohammad Norouzi, and David J Fleet. Video diffusion models. arXiv preprint arXiv:2204.03458, 2022b. \nWenyi Hong, Ming Ding, Wendi Zheng, Xinghan Liu, and Jie Tang. Cogvideo: Large-scale pretraining for text-to-video generation via transformers. arXiv preprint arXiv:2205.15868, 2022. \nTianyu Huang, Yihan Zeng, Bowen Dong, Hang Xu, Songcen Xu, Rynson WH Lau, and Wangmeng Zuo. Textfield3d: Towards enhancing open-vocabulary 3d generation with noisy text fields. arXiv preprint arXiv:2309.17175, 2023. \nZhewei Huang, Tianyuan Zhang, Wen Heng, Boxin Shi, and Shuchang Zhou. Real-time intermediate flow estimation for video frame interpolation. In ECCV, 2022. \nMinguk Kang, Jun-Yan Zhu, Richard Zhang, Jaesik Park, Eli Shechtman, Sylvain Paris, and Taesung Park. Scaling up gans for text-to-image synthesis. In CVPR, 2023. \nLevon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang Wang, Shant Navasardyan, and Humphrey Shi. Text2video-zero: Text-to-image diffusion models are zero-shot video generators. arXiv preprint arXiv:2303.13439, 2023. ",
470
+ "page_idx": 9
471
+ },
472
+ {
473
+ "type": "text",
474
+ "text": "Nupur Kumari, Bingliang Zhang, Richard Zhang, Eli Shechtman, and Jun-Yan Zhu. Multi-concept customization of text-to-image diffusion. arXiv preprint arXiv:2212.04488, 2022. ",
475
+ "page_idx": 10
476
+ },
477
+ {
478
+ "type": "text",
479
+ "text": "Wei-Sheng Lai, Jia-Bin Huang, Oliver Wang, Eli Shechtman, Ersin Yumer, and Ming-Hsuan Yang. Learning blind video temporal consistency. In Proceedings of the European conference on computer vision (ECCV), pp. 170–185, 2018. \nBenjamin Lefaudeux, Francisco Massa, Diana Liskovich, Wenhan Xiong, Vittorio Caggiano, Sean Naren, Min Xu, Jieru Hu, Marta Tintore, Susan Zhang, Patrick Labatut, and Daniel Haziza. xformers: A modular and hackable transformer modelling library. https://github.com/ facebookresearch/xformers, 2022. \nYue Ma, Yingqing He, Xiaodong Cun, Xintao Wang, Ying Shan, Xiu Li, and Qifeng Chen. Follow your pose: Pose-guided text-to-video generation using pose-free videos. arXiv preprint arXiv:2304.01186, 2023. \nChenlin Meng, Yang Song, Jiaming Song, Jiajun Wu, Jun-Yan Zhu, and Stefano Ermon. Sdedit: Image synthesis and editing with stochastic differential equations. arXiv preprint arXiv:2108.01073, 2021. \nChong Mou, Xintao Wang, Liangbin Xie, Jian Zhang, Zhongang Qi, Ying Shan, and Xiaohu Qie. T2i-adapter: Learning adapters to dig out more controllable ability for text-to-image diffusion models. arXiv preprint arXiv:2302.08453, 2023. \nMinheng Ni, Zitong Huang, Kailai Feng, and Wangmeng Zuo. Imaginarynet: Learning object detectors without real images and annotations. arXiv preprint arXiv:2210.06886, 2022. \nAlex Nichol, Prafulla Dhariwal, Aditya Ramesh, Pranav Shyam, Pamela Mishkin, Bob McGrew, Ilya Sutskever, and Mark Chen. Glide: Towards photorealistic image generation and editing with text-guided diffusion models. arXiv preprint arXiv:2112.10741, 2021. \nTB OpenAI. Chatgpt: Optimizing language models for dialogue. OpenAI, 2022. \nJordi Pont-Tuset, Federico Perazzi, Sergi Caelles, Pablo Arbelaez, Alex Sorkine-Hornung, and ´ Luc Van Gool. The 2017 davis challenge on video object segmentation. arXiv preprint arXiv:1704.00675, 2017. \nChenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, and Qifeng Chen. Fatezero: Fusing attentions for zero-shot text-based video editing. arXiv preprint arXiv:2303.09535, 2023. \nAditya Ramesh, Mikhail Pavlov, Gabriel Goh, Scott Gray, Chelsea Voss, Alec Radford, Mark Chen, and Ilya Sutskever. Zero-shot text-to-image generation. In ICML, 2021. \nAditya Ramesh, Prafulla Dhariwal, Alex Nichol, Casey Chu, and Mark Chen. Hierarchical textconditional image generation with clip latents. arXiv preprint arXiv:2204.06125, 2022. \nRene Ranftl, Katrin Lasinger, David Hafner, Konrad Schindler, and Vladlen Koltun. Towards robust ´ monocular depth estimation: Mixing datasets for zero-shot cross-dataset transfer. TPAMI, 2020. \nRobin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bjorn Ommer. High-¨ resolution image synthesis with latent diffusion models. In CVPR, 2022. \nOlaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In MICCAI, 2015. \nNataniel Ruiz, Yuanzhen Li, Varun Jampani, Yael Pritch, Michael Rubinstein, and Kfir Aberman. Dreambooth: Fine tuning text-to-image diffusion models for subject-driven generation. arXiv preprint arXiv:2208.12242, 2022. \nChitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022. \nAxel Sauer, Tero Karras, Samuli Laine, Andreas Geiger, and Timo Aila. Stylegan-t: Unlocking the power of gans for fast large-scale text-to-image synthesis. arXiv preprint arXiv:2301.09515, 2023. \nUriel Singer, Adam Polyak, Thomas Hayes, Xi Yin, Jie An, Songyang Zhang, Qiyuan Hu, Harry Yang, Oron Ashual, Oran Gafni, et al. Make-a-video: Text-to-video generation without text-video data. arXiv preprint arXiv:2209.14792, 2022. \nJiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. arXiv preprint arXiv:2010.02502, 2020a. \nJiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. arXiv preprint arXiv:2010.02502, 2020b. \nRuben Villegas, Mohammad Babaeizadeh, Pieter-Jan Kindermans, Hernan Moraldo, Han Zhang, Mohammad Taghi Saffar, Santiago Castro, Julius Kunze, and Dumitru Erhan. Phenaki: Variable length video generation from open domain textual description. arXiv preprint arXiv:2210.02399, 2022. \nWen Wang, kangyang Xie, Zide Liu, Hao Chen, Yue Cao, Xinlong Wang, and Chunhua Shen. Zeroshot video editing using off-the-shelf image diffusion models. arXiv preprint arXiv:2303.17599, 2023. \nYuxiang Wei, Yabo Zhang, Zhilong Ji, Jinfeng Bai, Lei Zhang, and Wangmeng Zuo. Elite: Encoding visual concepts into textual embeddings for customized text-to-image generation. arXiv preprint arXiv:2302.13848, 2023. \nChenfei Wu, Lun Huang, Qianxi Zhang, Binyang Li, Lei Ji, Fan Yang, Guillermo Sapiro, and Nan Duan. Godiva: Generating open-domain videos from natural descriptions. arXiv preprint arXiv:2104.14806, 2021. \nChenfei Wu, Jian Liang, Lei Ji, Fan Yang, Yuejian Fang, Daxin Jiang, and Nan Duan. Nuwa: Visual ¨ synthesis pre-training for neural visual world creation. In ECCV, 2022a. \nJay Zhangjie Wu, Yixiao Ge, Xintao Wang, Weixian Lei, Yuchao Gu, Wynne Hsu, Ying Shan, Xiaohu Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning of image diffusion models for text-to-video generation. arXiv preprint arXiv:2212.11565, 2022b. \nHongwei Xue, Tiankai Hang, Yanhong Zeng, Yuchong Sun, Bei Liu, Huan Yang, Jianlong Fu, and Baining Guo. Advancing high-resolution video-language representation with large-scale video transcriptions. In CVPR, 2022. \nJiahui Yu, Yuanzhong Xu, Jing Yu Koh, Thang Luong, Gunjan Baid, Zirui Wang, Vijay Vasudevan, Alexander Ku, Yinfei Yang, Burcu Karagol Ayan, et al. Scaling autoregressive models for contentrich text-to-image generation. arXiv preprint arXiv:2206.10789, 2022. \nLvmin Zhang and Maneesh Agrawala. Adding conditional control to text-to-image diffusion models. arXiv preprint arXiv:2302.05543, 2023. ",
480
+ "page_idx": 10
481
+ },
482
+ {
483
+ "type": "text",
484
+ "text": "",
485
+ "page_idx": 11
486
+ },
487
+ {
488
+ "type": "text",
489
+ "text": "A. DATASET DETAILS ",
490
+ "text_level": 1,
491
+ "page_idx": 12
492
+ },
493
+ {
494
+ "type": "text",
495
+ "text": "In Table 4, we select 25 representative videos from DAVIS dataset (Pont-Tuset et al., 2017) and manually annotate their source captions. After that, we ask ChatGPT to generate five edited prompts for each source caption, following the instruction like: Please generate five new sentences that similar to “A man dances on the road”, while being more diverse and highly detailed. Finally, we obtain 125 video-prompt pairs in total, and use them to evaluate both canny and depth conditioned generation. ",
496
+ "page_idx": 12
497
+ },
498
+ {
499
+ "type": "text",
500
+ "text": "B. USER STUDY DETAILS ",
501
+ "text_level": 1,
502
+ "page_idx": 12
503
+ },
504
+ {
505
+ "type": "text",
506
+ "text": "We conduct a user study to compare ControlVideo against two other methods on 125 samples, and ask five raters to answer questions in each sample. In Fig. 7, there are three questions involving in (i) video quality, (ii) temporal consistency, and (iii) text alignment. The raters are given unlimited time to make the selection. After collecting their answers, we take a majority vote as the final result for each sample, and present statistics in Table 2. ",
507
+ "page_idx": 12
508
+ },
509
+ {
510
+ "type": "text",
511
+ "text": "C. MORE ABLATION STUDIES ",
512
+ "text_level": 1,
513
+ "page_idx": 12
514
+ },
515
+ {
516
+ "type": "text",
517
+ "text": "During inference, we adopt DDIM sampling with $T = 5 0$ timesteps, which iteratively denoises a Gaussian noise from $T$ to 0. ",
518
+ "page_idx": 12
519
+ },
520
+ {
521
+ "type": "text",
522
+ "text": "Which timesteps does interleaved-frame smoother perform at? In Fig. 8, we explore three timestep choices at different noise levels, including $\\{ 4 8 , 4 9 \\}$ at large noise level, $\\{ 3 0 , 3 1 \\bar { \\} }$ at middle noise level, and $\\{ 0 , 1 \\}$ at little noise level. When using the smoother at timesteps $\\{ 4 8 , 4 9 \\}$ , the processed video is still unstable, since structure sequences bring additional flickers at the following timesteps. At timesteps $\\{ 0 , 1 \\}$ nearby image distribution, applying the interleaved-frame smoother leads to visible distortion in some frames. In contrast, performing smoothing operation at middle timesteps $\\{ 3 0 , 3 1 \\}$ promisingly deflickers the video, while preserving the quality and individuality of interpolated frames. ",
523
+ "page_idx": 12
524
+ },
525
+ {
526
+ "type": "text",
527
+ "text": "How many timesteps are used in interleaved-frame smoother? Fig. 9 shows the smoothed videos using interleaved-frame smoother at different numbers of timesteps. Applying the smoother at two consecutive timesteps (i.e., 2 steps) could smooth the entire video with little video quality degradation. As the number of smoothing steps increases, the processed video is much smoother, but some frames become slightly blurred. Thus, for higher quality and efficiency, we set the number of smoothing timesteps as 2 by default. ",
528
+ "page_idx": 12
529
+ },
530
+ {
531
+ "type": "text",
532
+ "text": "Non-deterministic DDPM-style sampler. ControlVideo can also employ a non-deterministic DDPM-style sampler during inference. Following Eq.12 in DDIM (Song et al., 2020b), one can predict $z _ { t - 1 }$ from ${ \\boldsymbol { z } } _ { t }$ via (i.e., line 10 of Alg. 1 in paper): ",
533
+ "page_idx": 12
534
+ },
535
+ {
536
+ "type": "equation",
537
+ "img_path": "images/2186be5668d2caed8ade85830b2cce7bbec48b5ce2e9f1000b9fe78499128923.jpg",
538
+ "text": "$$\nz _ { t - 1 } \\gets \\sqrt { \\alpha _ { t - 1 } } \\tilde { z } _ { t \\to 0 } + \\sqrt { 1 - \\alpha _ { t - 1 } } \\cdot \\epsilon _ { \\theta } ( z _ { t } , t , c , \\tau ) + \\sigma _ { t } \\epsilon _ { t } ,\n$$",
539
+ "text_format": "latex",
540
+ "page_idx": 12
541
+ },
542
+ {
543
+ "type": "text",
544
+ "text": "where $\\epsilon _ { t }$ and $\\sigma _ { t }$ controls the level of random noise. DDPM results presents the generated videos of ControlVideo at different noise levels. Notably, as the noise level increases, ControlVideo generates more photo-realistic videos with dynamic details, e.g., ripples in the water. ",
545
+ "page_idx": 12
546
+ },
547
+ {
548
+ "type": "text",
549
+ "text": "D. MORE VISUALIZATIONS AND COMPARISONS ",
550
+ "text_level": 1,
551
+ "page_idx": 12
552
+ },
553
+ {
554
+ "type": "text",
555
+ "text": "Fig. 10, Fig. 11, and Fig. 12 show more video visualizations conditioned on canny edges, depth maps, and human poses. Fig. 14, Fig. 15, and Fig. 16 present qualitative comparisons conditioned on canny edges, depth maps, and human poses. Fig. 13 provides an additional long video. More comparisons with video editing methods (Qi et al., 2023; Wang et al., 2023) are shown in this link. ",
556
+ "page_idx": 12
557
+ },
558
+ {
559
+ "type": "text",
560
+ "text": "Firstly, Vid2Vid-Zero and FateZero are designed for video editing by a hybrid of fully and sparsecasual cross-frame attention, and does not investigate different attention mechanisms in depth. In contrast, our ControlVideo focuses on continuous controllable text-to-video generation, and first empirically investigate the superiority of fully cross-frame attention. Secondly, Fig. 18 shows their qualitative comparisons on video editing. As one can see, the edited videos of ControlVideo not only have more consistent structure with source videos, but also aligns better with text prompts. ",
561
+ "page_idx": 12
562
+ },
563
+ {
564
+ "type": "table",
565
+ "img_path": "",
566
+ "table_caption": [
567
+ "Table 4: Names and captions of selected videos from DAVIS dataset. "
568
+ ],
569
+ "table_footnote": [],
570
+ "page_idx": 13
571
+ },
572
+ {
573
+ "type": "text",
574
+ "text": "Between Method 1 & 2 : ",
575
+ "text_level": 1,
576
+ "page_idx": 13
577
+ },
578
+ {
579
+ "type": "image",
580
+ "img_path": "images/c5e387d34be8b3c0b93aee09f685e24171376650a44074d7f68e069e25d6d8b6.jpg",
581
+ "image_caption": [
582
+ "Figure 7: The instruction of user study. A user study sample consists of a text prompt, structure sequence, and synthesized videos from two different methods (in random order). The raters are asked to answer the above three questions for each sample. "
583
+ ],
584
+ "image_footnote": [],
585
+ "page_idx": 13
586
+ },
587
+ {
588
+ "type": "text",
589
+ "text": "1. Which video has higher quality ? \n2. Which video has better temporal consistency across all frames? \n3. Which video aligns better with text prompt? ",
590
+ "page_idx": 13
591
+ },
592
+ {
593
+ "type": "text",
594
+ "text": "E. LIMITATIONS. ",
595
+ "text_level": 1,
596
+ "page_idx": 13
597
+ },
598
+ {
599
+ "type": "text",
600
+ "text": "While our ControlVideo enables consistent and high-quality video generation, it still struggles with producing videos beyond input motion sequences. For example, in Fig. 17, given sequential poses of Michael Jackson’s moonwalk, it is difficult to generate a vivid video according to text prompts like Iron man runs on the street. In this link, when input text prompts (e.g., rabbit) seriously conflict with input motion (e.g., ), the synthesized videos usually tend to align with input motion, ignoring the implicit structure in text prompts. To increase the ratio of text prompts over structure, we decrease the scale of ControlNet $\\lambda$ to 0.3 ( $\\lambda = 1$ by default). Therefore, it can be seen $\\lambda = 0 . 3$ that achieves a better trade-off between two input conditions than $\\lambda = 1$ . In the future, we will explore how to adaptively modify input motions according to text prompts, so that users can create more vivid videos. ",
601
+ "page_idx": 13
602
+ },
603
+ {
604
+ "type": "image",
605
+ "img_path": "images/1cc77370796c781d5eac52f2bb3d67956168ff3ef10f9c2fccac9a465c1bc05f.jpg",
606
+ "image_caption": [
607
+ "A dusty old jeep was making its way down the winding forest road, creaking and groaning with each bump and turn. ",
608
+ "Figure 8: Ablation on timestep choices in interleaved-frame smoother. We apply interleavedframe smoother at different timesteps, including $\\{ 4 8 , 4 9 \\}$ at large noise level, $\\{ 3 0 , 3 1 \\}$ at middle noise level, and $\\{ 0 , 1 \\}$ at little noise level. Among them, using the smoother at timesteps $\\{ 3 0 , 3 1 \\}$ promisingly mitigates the flicker effect while ensuring high quality. Results best seen at $50 \\%$ zoom. "
609
+ ],
610
+ "image_footnote": [],
611
+ "page_idx": 14
612
+ },
613
+ {
614
+ "type": "image",
615
+ "img_path": "images/1f621020166128d9f9d0a58b8c65dd34ce2cb9f405c4b2184a8d3f0bb5899c8d.jpg",
616
+ "image_caption": [
617
+ "A sleek black jeep was speeding along the narrow forest road, dodging trees and rocks with ease. ",
618
+ "Figure 9: Ablation on the number of timesteps used in interleaved-frame smoother. Applying the smoother at two consecutive timesteps (i.e., 2 steps) effectively reduces the flickers in structure. As we increase the number of smoothing steps, the processed video becomes smoother, but some frames are slightly blurred. Therefore, we set the number of smoothing steps as two by default. Results best seen at $50 \\%$ zoom. "
619
+ ],
620
+ "image_footnote": [],
621
+ "page_idx": 14
622
+ },
623
+ {
624
+ "type": "image",
625
+ "img_path": "images/5a5910fbbd4ad8aaafebc4ea5c03c6ee917d56beba91a746e9a78e03a6a7c148.jpg",
626
+ "image_caption": [
627
+ "Figure 10: More video visualizations conditioned on canny edges. Results best seen at $50 \\%$ zoom. "
628
+ ],
629
+ "image_footnote": [],
630
+ "page_idx": 15
631
+ },
632
+ {
633
+ "type": "image",
634
+ "img_path": "images/2cf0952da37fcfb973d7d3a30a66d33efc530f74e6b5482843901118c0736493.jpg",
635
+ "image_caption": [
636
+ "Figure 11: More video visualizations conditioned on depth maps. Results best seen at $50 \\%$ zoom. "
637
+ ],
638
+ "image_footnote": [],
639
+ "page_idx": 16
640
+ },
641
+ {
642
+ "type": "text",
643
+ "text": "Bottom: Wonder Woman in a desert, Pop Art style. ",
644
+ "page_idx": 17
645
+ },
646
+ {
647
+ "type": "image",
648
+ "img_path": "images/edaa8ff27d73074eafff7fee3ee37a09d651f507a2e1fff43fa3d20c970bb157.jpg",
649
+ "image_caption": [
650
+ "Top: Hulk is jumping on the street, cartoon style ",
651
+ "Bottom: The Simpsons in the city, Hockney style. ",
652
+ "Top: Goku in a mountain range, surreal style. ",
653
+ "Top: A man, wearing pink clothes, moonwalk at sunset. ",
654
+ "Figure 12: More video visualizations conditioned on human poses. Results best seen at $50 \\%$ zoom. "
655
+ ],
656
+ "image_footnote": [],
657
+ "page_idx": 17
658
+ },
659
+ {
660
+ "type": "text",
661
+ "text": "Bottom: James bond moonwalk on the beach, animation style. ",
662
+ "page_idx": 17
663
+ },
664
+ {
665
+ "type": "image",
666
+ "img_path": "images/ae0be126190267c573b161a409a3714fbac0df2f02242d6b6464e0f224a5b180.jpg",
667
+ "image_caption": [
668
+ "Hulk is dancing on the beach, cartoon style. ",
669
+ "Figure 13: Additional long video visualization. Results best seen at $50 \\%$ zoom. "
670
+ ],
671
+ "image_footnote": [],
672
+ "page_idx": 17
673
+ },
674
+ {
675
+ "type": "image",
676
+ "img_path": "images/98b2b95ddf40dc44b7df6621f1c07e09ac69002449fc3385ad31aa1c676e13d9.jpg",
677
+ "image_caption": [
678
+ "Figure 14: More qualitative comparisons conditioned on canny edges. Results best seen at $50 \\%$ zoom. "
679
+ ],
680
+ "image_footnote": [],
681
+ "page_idx": 18
682
+ },
683
+ {
684
+ "type": "image",
685
+ "img_path": "images/226f88c39b4b0c84dde0cac7902c01d34efec8ea241efe3246e64ccdaf4795a4.jpg",
686
+ "image_caption": [
687
+ "Figure 15: More qualitative comparisons conditioned on depth maps. Results best seen at $50 \\%$ zoom. "
688
+ ],
689
+ "image_footnote": [],
690
+ "page_idx": 18
691
+ },
692
+ {
693
+ "type": "image",
694
+ "img_path": "images/4605680307d5e360af89d69a874f3dec185392cfe082e89b9eda044b82ead317.jpg",
695
+ "image_caption": [
696
+ "Figure 16: More qualitative comparisons conditioned on human poses. Results best seen at $50 \\%$ zoom. "
697
+ ],
698
+ "image_footnote": [],
699
+ "page_idx": 19
700
+ },
701
+ {
702
+ "type": "image",
703
+ "img_path": "images/71d28866116d0ff2097ca8dbeb2a32a188a5b46c20dd155fc5c7a5cc8d495ee6.jpg",
704
+ "image_caption": [
705
+ "Figure 17: Limitation visualizations. ControlVideo struggles with producing videos beyond input motion sequences. The motion of text prompt Iron man runs on the street does not align with the given sequential poses of Michael Jackson’s moonwalk, which degrades the video quality and consistency. See videos at limitations. "
706
+ ],
707
+ "image_footnote": [],
708
+ "page_idx": 19
709
+ },
710
+ {
711
+ "type": "image",
712
+ "img_path": "images/ea8cf74902f9be79151ade294cf1ae1a0b8da5e3ed535f0d3cf54179ac528ba4.jpg",
713
+ "image_caption": [
714
+ "Figure 18: Qualitative comparisons with Vid2Vid-Zero. Inconsistent objects and prompts are colored in red. "
715
+ ],
716
+ "image_footnote": [],
717
+ "page_idx": 20
718
+ }
719
+ ]
parse/test/5a79AqFr0c/5a79AqFr0c_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/5a79AqFr0c/5a79AqFr0c_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Fq8tKtjACC/Fq8tKtjACC.md ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TEXTBOOKS ARE ALL YOU NEED
2
+
3
+ Anonymous authors Paper under double-blind review
4
+
5
+ # ABSTRACT
6
+
7
+ We introduce phi-1, a new large language model for code, with significantly smaller size than competing models: phi-1 is a Transformer-based model with 1.3B parameters, trained for 4 days on 8 A100s, using a selection of “textbook quality” data from the web (6B tokens) and synthetically generated textbooks and exercises with GPT-3.5 (1B tokens). Despite this small scale, phi-1 attains pass $@ 1$ accuracy $5 0 . 6 \%$ on HumanEval and $5 5 . 5 \%$ on MBPP. It also displays surprising emergent properties compared to phi-1-base, our model before our finetuning stage on a coding exercises dataset, and phi-1-small, a model with 350M parameters trained with the same pipeline that still achieves $4 5 \%$ on HumanEval.
8
+
9
+ # 1 INTRODUCTION
10
+
11
+ The art of training large artificial neural networks has made extraordinary progress in the last decade, especially after the discovery of the Transformer architecture Vaswani et al. (2017), yet the science behind this success remains limited. Amidst a vast and confusing array of results, a semblance of order emerged around the same time as Transformers were introduced, namely that performance improves somewhat predictably as one scales up either the amount of compute or the size of the network Hestness et al. (2017), a phenomenon which is now referred to as scaling laws Kaplan et al. (2020). The subsequent exploration of scale in deep learning was guided by these scaling laws Brown et al. (2020), and discoveries of variants of these laws led to rapid jump in performances Hoffmann et al. (2022). In this work, following the footsteps of Eldan and Li Eldan & Li (2023), we explore the improvement that can be obtained along a different axis: the quality of the data. It has long been known that higher quality data leads to better results, e.g., data cleaning is an important part of modern dataset creation Raffel et al. (2020), and it can yield other side benefits such as somewhat smaller datasets Longpre et al. (2023); Yu et al. (2023) or allowing for more passes on the data Muennighoff et al. (2023). The recent work of Eldan and Li on TinyStories (a high quality dataset synthetically generated to teach English to neural networks) showed that in fact the effect of high quality data extends well past this: improving data quality can dramatically change the shape of the scaling laws, potentially allowing to match the performance of large-scale models with much leaner training/models. In this work we go beyond the initial foray of Eldan and Li to show that high quality data can even improve the SOTA of large language models (LLMs), while dramatically reducing the dataset size and training compute. Importantly, smaller models requiring less training can significantly reduce the environmental cost of LLMs Bender et al. (2021).
12
+
13
+ We focus our attention on LLMs trained for code, and specifically writing simple Python functions from their docstrings as in Chen et al. (2021). The evaluation benchmark proposed in the latter work, HumanEval, has been widely adopted for comparing LLMs’ performance on code. We demonstrate the power of high quality data in breaking existing scaling laws by training a 1.3B-parameter model, which we call phi-1, for roughly 8 passes over 7B tokens (slightly over 50B total tokens seen) followed by finetuning on less than 200M tokens. Roughly speaking we pretrain on “textbook quality” data, both synthetically generated (with GPT-3.5) and filtered from web sources, and we finetune on “textbook-exercise-like” data. Despite being several orders of magnitude smaller than competing models, both in terms of dataset and model size (see Table 1), we attain $5 0 . 6 \%$ pass $@ 1$ accuracy on HumanEval and $5 5 . 5 \%$ pass $@ 1$ accuracy on MBPP (Mostly Basic Python Programs), which are one of the best self-reported numbers using only one LLM generation. In Section 2, we give some details of our training process, and we discuss evidence for the importance of our data selection process in achieving this result. Moreover, despite being trained on much fewer tokens compared to existing models, phi-1 still displays emergent properties. In Section 3 we discuss these
14
+
15
+ <table><tr><td>Date</td><td>Model</td><td>Model size (Parameters)</td><td>Dataset size (Tokens)</td><td>HumanEval (Pass@1)</td><td>MBPP (Pass@1)</td></tr><tr><td>2021Jul</td><td>Codex-300M Chen et al. (2021)</td><td>300M</td><td>100B</td><td>13.2%</td><td>-</td></tr><tr><td>2021 Jul</td><td>Codex-12B Chen et al. (2021)</td><td>12B</td><td>100B</td><td>28.8%</td><td>=</td></tr><tr><td>2022Mar</td><td>CodeGen-Mono-350MNijkamp et al.(2023b)</td><td>350M</td><td>577B</td><td>12.8%</td><td>1</td></tr><tr><td>2022Mar</td><td>CodeGen-Mono-16.1B Nijkamp et al.(2023b)</td><td>16.1B</td><td>577B</td><td>29.3%</td><td>35.3%</td></tr><tr><td>2022 Apr</td><td>PaLM-Coder Chowdhery et al. (2022)</td><td>540B</td><td>780B</td><td>35.9%</td><td>47.0%</td></tr><tr><td>2022 Sep</td><td>CodeGeeX Zheng et al. (2023)</td><td>13B</td><td>850B</td><td>22.9%</td><td>24.4%</td></tr><tr><td>2022 Nov</td><td>GPT-3.5 OpenAI (2023)</td><td>175B</td><td>N.A.</td><td>47%</td><td></td></tr><tr><td>2022 Dec</td><td>SantaCoder Allal et al. (2023)</td><td>1.1B</td><td>236B</td><td>14.0%</td><td>35.0%</td></tr><tr><td>2023Mar</td><td>GPT-4 OpenAI (2023)</td><td>N.A.</td><td>N.A.</td><td>67%</td><td>1</td></tr><tr><td>2023 Apr</td><td>Replit Replit (2023)</td><td>2.7B</td><td>525B</td><td>21.9%</td><td>=</td></tr><tr><td>2023Apr</td><td>Replit-Finetuned Replit (2023)</td><td>2.7B</td><td>525B</td><td>30.5%</td><td></td></tr><tr><td>2023May</td><td>CodeGen2-1B Nijkamp et al. (2023a)</td><td>1B</td><td>N.A.</td><td>10.3%</td><td></td></tr><tr><td>2023 May</td><td>CodeGen2-7B Nijkamp et al. (2023a)</td><td>7B</td><td>N.A.</td><td>19.1%</td><td></td></tr><tr><td>2023May</td><td>StarCoder Li et al. (2023)</td><td>15.5B</td><td>1T</td><td>33.6%</td><td>52.7%</td></tr><tr><td>2023May</td><td>StarCoder-Prompted Li et al.(2023)</td><td>15.5B</td><td>1T</td><td>40.8%</td><td>49.5%</td></tr><tr><td>2023 May</td><td>PaLM 2-S Anil et al. (2023)</td><td>N.A.</td><td>N.A.</td><td>37.6%</td><td>50.0%</td></tr><tr><td>2023 May</td><td>CodeT5+ Wang et al. (2023)</td><td>2B</td><td>52B</td><td>24.2%</td><td>1</td></tr><tr><td>2023May</td><td>InstructCodeT5+ Wang et al.(2023)</td><td>16B</td><td>52B</td><td>35.0%</td><td></td></tr><tr><td>2023Jun</td><td>WizardCoder Luo et al. (2023)</td><td>16B</td><td>1T</td><td>57.3%</td><td>51.8%</td></tr><tr><td>2023Jun</td><td>phi-1</td><td>1.3B</td><td>7B</td><td>50.6%</td><td>55.5%</td></tr></table>
16
+
17
+ Table 1: We use self-reported scores whenever available. Despite being trained at vastly smaller scale, phi-1 outperforms several competing models on HumanEval and MBPP.
18
+
19
+ emergent properties, and in particular we confirm the hypothesis that the number of parameters plays a key role in emergence (see e.g., Wei et al. (2022)), by comparing the outputs of phi-1 with those of phi-1-small, a model trained with the same pipeline but with only 350M parameters. The methodology used in this section is reminiscent of the Sparks of AGI paper Bubeck et al. (2023) for beyond-benchmark evaluation. Finally in Section 4 we discuss alternative benchmarks to evaluate the model and in Section 5 we study possible contamination of our training data with respect to HumanEval. We release the model for usage and evaluation by the broader community, but omit some details of the synthetic data generation, for proprietary reasons1.
20
+
21
+ More related works. Our work is part of the recent program of using LLMs for program synthesis, see Chen et al. (2021); Nijkamp et al. (2022) for more references on this. Our approach is also part of the emerging trend of using existing LLMs to synthesize data for the training of new generations of LLMs, Wang et al. (2022); Taori et al. (2023); Mukherjee et al. (2023); Lin et al. (2023); Jung et al. (2023). There is an ongoing debate about whether such “recursive training” might lead to narrower scope for the resulting LLM Shumailov et al. (2023); Gudibande et al. (2023), see Mukherjee et al. (2023) for a counterviewpoint. Note that in this paper we focus on a narrow task, similarly to Jung et al. (2023), where it is plausible to improve upon the teacher LLM (as is argued in the latter paper).
22
+
23
+ # 2 TRAINING DETAILS AND THE IMPORTANCE OF HIGH-QUALITY DATA
24
+
25
+ As alluded to in the title of the paper, the central ingredient our model relies on textbook-quality training data. We devote this section primarily to our data curation ideas 2.
26
+
27
+ Previous work used standard sources of text and code data for code generation, such as The Stack Kocetkov et al. (2022) and other web-based datasets (e.g., StackOverflow). While these form large and diverse corpus covering broad range of topics and use cases, we argue that these sources are not optimal for teaching the model how to reason and plan algorithmically. Based on manual inspection we observe that many of these snippets are not very instructive for learning the basics of coding:
28
+
29
+ • Many samples are not self-contained, meaning that they depend on other modules or files that are external to the snippet, making them hard to understand without additional context.
30
+ • Typical examples do not involve any meaningful computation, but rather consist of trivial or boilerplate code, such as defining constants, parameters, or configuring GUI elements.
31
+ • Samples that do contain algorithmic logic are often buried inside complex or poorly documented functions, making them difficult to follow or learn from.
32
+ • The examples are skewed towards certain topics or use cases, resulting in an unbalanced distribution of coding concepts and skills across the dataset.
33
+
34
+ ![](images/6d763b34a506d5c744e84aab37a82f7a9de1f8b3bdcaf6ccdc32d1839f0a61dd.jpg)
35
+ Figure 1: Pass $@ 1$ accuracy $( \% )$ on HumanEval. The grouping of bar plots correspond to the usual scaling dimensions of either increasing the compute time (more passes on the data, here from 26B tokens seen to 76B) or increasing the number of parameters of the model (here from 350M to 1.3B). Each column within a group corresponds to different training datasets: (A) The first (orange) column represents the performance of models trained on the standard datasets of deduplicated Python files from The Stack and StackOverflow; (B) The second (light green) column represents the performance of models trained with our new dataset composition CodeTextbook; (C) Finally, the third (dark green) column corresponds to the respective second column models finetuned on our new CodeExercises dataset. For the 1.3B models, phi-1 and phi-1-base are checkpoints after training on 51B tokens and The Stack $^ +$ model was trained for 76B tokens. We highlight that even without any finetuning, our phi-1-base model trained on CodeTextbook dataset achieves $2 9 \%$ HumanEval performance with a mere 1.3B parameter model. The previous smallest model that achieves close to $30 \%$ performance on HumanEval was Replit-Finetuned at 2.7B parameters, which was trained with 100 times more training tokens than us Replit (2023). On top of this, finetuning on our CodeExercises dataset to obtain phi-1 not only gives us our top performance of $51 \%$ on HumanEval, but also unlocks unexpected coding capabilities (see Section 3).
36
+
37
+ One can only imagine how frustrating and inefficient it would be for a human learner to try to acquire coding skills from these datasets, as they would have to deal with a lot of noise, ambiguity, and incompleteness in the data. We hypothesize that these issues also affect the performance of language models, as they reduce the quality and quantity of the signal that maps natural language to code. We conjecture that language models would benefit from a training set that has the same qualities as a good “textbook”: it should be clear, self-contained, instructive, and balanced.
38
+
39
+ In this work, we address this challenge directly and show that by intentionally selecting and generating high-quality data, we can achieve state-of-the-art results on code-generation tasks with a much smaller model and less compute than existing approaches. Our training relies on three main datasets:
40
+
41
+ • A filtered code-language dataset, which is a subset of The Stack and StackOverflow, obtained by using a language model-based classifier (consisting of about 6B tokens). • A synthetic textbook dataset of ${ < } 1 \mathbf { B }$ tokens of GPT-3.5 generated Python textbooks. • A small synthetic exercises dataset of $\mathord { \sim } 1 8 0 \mathbf { M }$ tokens of Python exercises and solutions.
42
+
43
+ We describe those datasets in more detail in the next subsections. Taken together, the above datasets contain less than 7B tokens. We refer to the combination of filtered code-language and synthetic textbook datasets as “CodeTextbook” and use it in the pretraining phase to obtain our base model phi-1-base—this model already achieves a competitive HumanEval performance of $2 9 \%$ . Then we use the 180M token synthetic exercises dataset, referred to as “CodeExercises”, to finetune our phi1-base model to obtain phi-1. Despite the small size of the “CodeExercises” dataset, finetuning with this dataset is crucial not only for large improvements in generating simple Python function as shown in Figure 1, but more broadly to unlock many interesting emergent capabilities in our phi-1 model that are not observed in phi-1-base (see Section 3).
44
+
45
+ # 2.1 FILTERING OF EXISTING CODE DATASETS USING A TRANSFORMER-BASED CLASSIFIER
46
+
47
+ We begin with publicly available Python code datasets: we use the Python subset of the deduplicated version of The Stack and the StackOverflow, which together contain over 35 million files/samples, totalling over 35B tokens. We annotate the quality of a small subset of these files (about $1 0 0 \mathrm { k }$ samples) using GPT-4: given a code snippet, the model is prompted to “determine its educational value for a student whose goal is to learn basic coding concepts”.
48
+
49
+ We then use this annotated dataset to train a random forest classifier that predicts the quality of a file/sample using its output embedding from a pretrained codegen model as features. We note that unlike GPT-3.5, which we use extensively to generate synthetic content (discussed below), we use GPT-4 minimally only for annotations on the quality of a small subset of The Stack and StackOverflow samples. We thus view our usage of GPT-4 as merely a way to avoid tedious humanannotation efforts Dubois et al. (2023).
50
+
51
+ ![](images/008198bd8bc80c39caf5939c62445e4deaee1e61fa6a2db476416e6621152e86.jpg)
52
+
53
+ Our filtering boosts model performance significantly even without the synthetic datasets discussed below: for 350M parameter models trained on unfiltered Stack (deduplicated python) and StackOverflow, the HumanEval performance saturates at $1 2 . 1 9 \%$ even after training for 96k steps (200B tokens), while training on the filtered subset achieves $1 7 . 6 8 \%$ on HumanEval after $3 6 \mathrm { k }$ steps. We further improve this to $2 0 . 1 2 \%$ (reported in Figure 1) by training on a combination of the filtered dataset and the synthetic textbooks dataset discussed below.
54
+
55
+ # 2.2 CREATION OF SYNTHETIC TEXTBOOK-QUALITY DATASETS
56
+
57
+ One of the main challenges in creating a high-quality dataset for code generation is ensuring that the examples are diverse and non-repetitive. By diversity, we mean that the examples should cover a wide range of coding concepts, skills, and scenarios, and that they should vary in their level of difficulty, complexity, and style. Diversity is important for several reasons: it exposes the language model to different ways of expressing and solving problems in code, it reduces the risk of overfitting or memorizing specific patterns or solutions, and it increases the generalization and robustness of the model to unseen or novel tasks. However, achieving diversity is not trivial, especially when using synthetic data generated by another language model. Simply prompting the model to produce a coding textbook or a set of exercises, even with some variation in the instructions or the parameters, will likely result in a very homogeneous and redundant dataset, where the same concepts and solutions are repeated over and over with minor changes. This is because language models tend to follow the most probable or common paths given their training data and their priors, and they lack the creativity or the incentive to explore alternative or novel ways of generating code. Therefore, one needs to find the right “trick” that will induce the language model to be more creative and diverse in its output, while still maintaining the quality and the coherence of the examples. Inspired by Eldan & Li (2023), where a diverse set of short stories were created by including a random subset of words chosen from some fixed vocabulary in the prompt and requiring that they would be somehow combined in the generated text, we look for ways to inject randomness into the prompt in a way that gives rise to the generation of a diverse dataset.
58
+
59
+ # THE SYNTHETIC TEXTBOOK DATASET
60
+
61
+ This dataset consists of less that 1B tokens of GPT-3.5 generated Python textbooks, synthesized to provide a high-quality source of natural language heavy text interleaved with relevant code snippets. We further targeted the content of these textbooks to cover topics that promote reasoning and basic algorithmic skills. Here, diversity is obtained by providing constraints on topics and target audience of the generated textbook. The following is an example text from the synthetic textbook:
62
+
63
+ ![](images/d1219eaa38d9f315b8ae06cf33910f6a6f5e5a9dbec42db43a2c78dabfe85cba.jpg)
64
+
65
+ # THE CODEEXERCISES DATASET
66
+
67
+ This is a small synthetic exercises dataset consisting of less than 180M tokens of Python exercises and solutions. Each exercise is a docstring of a function that needs to be completed. The goal of this dataset is to align the model to perform function completion tasks based on natural language instructions. This dataset was also generated by GPT-3.5, where the main means of eliciting diversity is by constraining the function names. For this dataset in particular, we conduct explicit decontamination and alternative evaluations in the following sections to ensure that problems similar to those from HumanEval benchmark are not seen during finetuning. Example exercise:
68
+
69
+ ![](images/cc639997f694aed0368ec6d2c44f84e0be17de347438c4880f3e39d2a4c4b79e.jpg)
70
+
71
+ # 3 SPIKES OF MODEL CAPABILITY AFTER FINETUNING ON CODEEXERCISES
72
+
73
+ Figure 1 showed that the largest improvement in HumanEval resulted from finetuning on the small CodeExercises dataset $\mathbf { \chi } { < } 2 0 0 \mathbf { M }$ tokens). CodeExercises consist exclusively of short Python tasks using only basic Python libraries. In this section, we demonstrate that, quite remarkably the model after finetuning also exhibits a substantial improvement in executing tasks that are not featured in the finetuning dataset. This includes managing intricate algorithmic tasks and using external libraries. This suggests that our finetuning process might have helped the model in reorganizing and consolidating the knowledge acquired during pretraining, even if such knowledge is not explicitly present in our CodeExercises dataset. In this section we will focus on qualitatively comparing and contrasting the capabilities of our finetuned model phi-1 and its pretrained base model phi-1-base.
74
+
75
+ # 3.1 FINETUNING IMPROVES THE MODEL’S UNDERSTANDING
76
+
77
+ Using a simple Python function that we created ourselves, we observe in Figure 2 that the model shows a much higher level of understanding and compliance with instructions after finetuning. In particular, phi-1-base struggles with the logical relationships in the prompts, while phi-1 can interpret the question and generate the answer correctly. In this example, even our 350M phi-1-small model shows some level of understanding of the problem even though the final solution is wrong.
78
+
79
+ ![](images/9762dd2e6610971bd23c8bffb6c8f188f907610286d228dbe07ce8dde9d87966.jpg)
80
+ Figure 2: Model performance with a multi-step algorithmic prompt, comparing the effects of finetuning and scale. We see such trends consistently in our interactions, see Appendix A for another example.
81
+
82
+ # 3.2 FINETUNING IMPROVES THE MODEL’S ABILITY TO USE EXTERNAL LIBRARIES
83
+
84
+ We demonstrate here that finetuning on CodeExercises unexpectedly improves the model’s ability to use external libraries such as Pygame, Tkinter, and pytorch, eventhough our exercises do not contain these libraries. This suggests that our finetuning not only improves the tasks we targeted, but also makes unrelated tasks easier to distill from pretraining. As an example, Figure 3 shows a PyGame example that asks the model to generate code to move a ball, where we see that phi-1 shows phenomenal improvement over phi-1-base model. See Appendix A for additional examples.
85
+
86
+ # 4 EVALUATION ON UNCONVENTIONAL PROBLEMS WITH LLM GRADING
87
+
88
+ A potential concern with the surprisingly good performance of phi-1 on HumanEval (see Table 1 and Figure 1) is that there might be memorization stemming from contamination of the synthetic CodeExercises dataset. We study this potential contamination directly in Section 5, while this section addresses the concern with a new evaluation that is designed to be unconventional enough to be unlikely to appear in our training data. To minimize bias and leakage, the new evaluation problems were created by a dedicated team that did not access the CodeExercises dataset or the final model. They created 50 new problems in the format as HumanEval with instructions to design problems that are unlikely to appear in real-world code bases or as coding exercises. Here is an example:
89
+
90
+ # Prompt:
91
+
92
+ """ Write a PyGame. There is a ball. At every iteration, (1). The x-axis of the ball increases by a random integer between (-10, 10), (2). The y-axis of the ball increases by a random integer between (-20, 20). The x-axis of the ball should stay inside 0-400, and y-axis of the ball should stay inside 0-600. When the user press ’space’, set the $_ x$ -axis of the ball to 200 and y-axis of the ball to 400. """
93
+
94
+ # phi-1
95
+
96
+ # phi-1-base
97
+
98
+ # phi-1-small
99
+
100
+ ![](images/b822403bc2f6f960d581b91a410bde4abfad11685edc2002f5e3f18e1b9ade10.jpg)
101
+ Figure 3: The above code snippets show the main loop of a simple PyGame program that bounces a ball on the screen. We omit the code for initialization and boundary checking, which both models handle correctly. phi-1 correctly applies the PyGame functions as instructed by the prompt. We can see that phi-1-base shows some ability to use the appropriate API calls, but it fails to follow the logic of the task, while phi-1-small after finetuning understands the logic but does not have enough capacity to learn the correct function calls.
102
+
103
+ One of the challenges of evaluating language models on coding tasks is that the output of the model is often binary: either the code passes all the unit tests or it fails. However, this does not capture the nuances of the model’s performance, as it might have produced a code that is almost correct but has a minor error, or a code that is completely wrong but coincidentally passes some tests. Arguably, a more informative way of assessing the model’s coding skills is to compare its output with the correct solution and grade it based on how well it matches the expected logic. This is similar to how humans are evaluated on coding interviews, where the interviewer does not only run the code but also examines the reasoning and the quality of the solution.
104
+
105
+ To evaluate candidate solutions, we therefore adopt the approach of using GPT-4 to grade the solution (such as in Eldan & Li (2023)). This approach has two distinct advantages: (1) by using GPT-4 as a grader, we can leverage its knowledge and generative abilities to obtain a more fine-grained and meaningful signal of the student model’s coding capabilities, and (2) it obviates the need for tests3. Our prompt instructs the LLM to evaluate a student’s solution first in a short verbal evaluation followed by grades from 0 to 10.
106
+
107
+ See Table 2 for our results with phi-1 and competing models. The grades on our new unconventional problems give the same ranking as HumanEval (see Table 1). phi-1 again achieves a score significantly higher than StarCoder, as it did on HumanEval. Given that the new problems have had no chance to contaminate the training data and, furthermore, were designed to be outside the training distribution, these results greatly increase our confidence in the validity of phi-1’s performance.
108
+
109
+ Table 2: LLM graded Understanding scores on 50 new unconventional coding problems.
110
+
111
+ <table><tr><td>Model</td><td>Size</td><td>Train tokens</td><td>Score</td><td>HumanEval</td></tr><tr><td>CodeGen-Mono-350MNijkamp et al. (2023b)</td><td>350M</td><td>577B</td><td>19%</td><td>13%</td></tr><tr><td>CodeGen-Mono-16.1B Nijkamp et al. (2023b)</td><td>16.1B</td><td>577B</td><td>38%</td><td>29%</td></tr><tr><td>Replit Replit (2023)</td><td>2.7B</td><td>525B</td><td>37%</td><td>22%</td></tr><tr><td>StarCoder Li et al. (2023)</td><td>15.5B</td><td>1T</td><td>51%</td><td>34%</td></tr><tr><td>phi-1-base</td><td>1.3B</td><td>7B</td><td>37%</td><td>29%</td></tr><tr><td>phi-1-small</td><td>350M</td><td>7B</td><td>45%</td><td>45%</td></tr><tr><td>phi-1</td><td>1.3B</td><td>7B</td><td>52%</td><td>51%</td></tr></table>
112
+
113
+ # 5 DATA PRUNING FOR UNBIASED PERFORMANCE EVALUATION
114
+
115
+ In Figure 1, we see that training on CodeExercises leads to a substantial boost in the performance of the model on the HumanEval benchmark. To investigate this boost, we propose to prune the CodeExercises dataset by removing files that are “similar” to those in HumanEval. This process can be viewed as a “strong form” of data decontamination. We then retrain our model on such pruned data, and still observe strong performance on HumanEval. In particular, even after aggressively pruning more than $40 \%$ of the CodeExercises dataset (this even prunes files that are only vaguely similar to HumanEval, see Appendix C), the retrained phi-1 still outperforms StarCoder.
116
+
117
+ We believe that such data pruning experiment is a fair way to evaluate performance, and is more insightful than standard “contamination” studies in the literature that are usually based on measures of overlap between training and test data (e.g., Section 4.8 of Austin et al. (2021)). For sake of completeness we start this section by conducting a standard contamination experiment, which shows that CodeExercises is not contaminated by HumanEval in this standard sense.
118
+
119
+ # 5.1 N-GRAM OVERLAP
120
+
121
+ N-gram measures the similarity of text segments based on the shared n-word sequences. We calculate the n-gram overlap between the docstrings of each humaneval question and each exercise in the CodeExercises dataset that was generated. We found 4 humaneval questions with 13-gram overlap with at least one of the entries in our dataset. After further investigating, we found out that all the 4 overlap cases in the 13-gram are all false positives (see examples shown in Appendix C).
122
+
123
+ # 5.2 EMBEDDING AND SYNTAX-BASED SIMILARITY ANALYSIS
124
+
125
+ As we just saw, the n-grams are not refined enough to find similar code snippets between HumanEval and CodeExercises. Instead we use a combination of embedding and syntax-based distances. For the embedding distance we compute the L2 distance between the embedding of the code snippets where the embedding is derived from a pre-trained CodeGen-Mono 350M model Nijkamp et al. (2023b). We observe that the embedding distance is successful in capturing code pairs where the overall code semantics are similar, which can be inferred via the Python Docstring, function/class names, as well as the code structure. For the syntax-based distance we calculate the (string) edit distance between the abstract syntax trees (ASTs) of two given code snippets. The AST distance successfully identifies overlapping sections between code pairs while being agnostic to non-syntax text such as variable/function naming, comments, and Python Docstrings. See Appendix C for examples of code pairs that are captured at various $\tau$ and embedding distances.
126
+
127
+ For our pruning experiments on CodeExercises, we fix a threshold for the embedding distance, and we test several match rate $\tau$ for the AST distance. We vary $\tau$ between 0.95 and 0.8, which corresponds to $4 \%$ to $40 \%$ of problems in CodeExercises, respectively. Table 3 summarizes the performance of our retrained phi-1 on pruned datasets (with $\tau = 0 . 9 5 , 0 . 9 , 0 . 8 5$ and 0.8) versus the original phi-1 trained on full CodeExercises and the $1 5 . 5 B$ -parameter StarCoder-prompted. We divide the HumanEval problems into two subsets (“similar” and “non-similar”) based on whether or not they have at least one close match (for this given $\tau$ ) inside the original CodeExercises dataset. We then report the accuracy of the models on each subset of HumanEval separately. As one can see, even after heavily pruning our dataset, phi-1 still outperforms StarCoder-Prompted by a large margin, which validates that our performance boost is not due to dataset “contamination”, even when the latter term is understood loosely.
128
+
129
+ Table 3: Percentage of similar versus non-similar HumanEval problems correctly solved by different models. Similarity is determined based on whether or not the corresponding HumanEval problem has any close matches inside the CodeExercises dataset (for a given $\tau$ ). The problem count denotes the number of HumanEval problems within each subset. Here, $\tau$ is the threshold on AST-based match rate between codes for similarity check.
130
+
131
+ <table><tr><td>T</td><td></td><td>Problem</td><td>phi-1</td><td>phi-1 retrainaed</td><td>StarCetar. [202pted</td></tr><tr><td rowspan="3">0.95</td><td>similar</td><td>71</td><td>81.7%</td><td>74.6%</td><td>57.7%</td></tr><tr><td>non-similar</td><td>93</td><td>26.9%</td><td>32.3%</td><td>29.0%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>50.6%</td><td>41.5%</td></tr><tr><td rowspan="3">0.9</td><td>similar</td><td>93</td><td>63.4%</td><td>51.6%</td><td>48.4%</td></tr><tr><td>non-similar</td><td>71</td><td>33.8%</td><td>36.6%</td><td>32.4%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>45.1%</td><td>41.5%</td></tr><tr><td rowspan="3">0.85</td><td>similar</td><td>106</td><td>62.3%</td><td>52.8%</td><td>47.2%</td></tr><tr><td>non-similar</td><td>58</td><td>29.3%</td><td>34.5%</td><td>31.0%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>46.3%</td><td>41.5%</td></tr><tr><td rowspan="3">0.8</td><td>similar</td><td>116</td><td>59.5%</td><td>52.6%</td><td>45.7%</td></tr><tr><td>non-similar</td><td>48</td><td>29.2%</td><td>27.1%</td><td>31.2%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>45.1%</td><td>41.5%</td></tr></table>
132
+
133
+ # 6 CONCLUSION
134
+
135
+ Just as a comprehensive, well-crafted textbook can provide a student with the necessary knowledge to master a new subject, our work demonstrates the remarkable impact of high-quality data in honing a language model’s proficiency in code-generation tasks. By crafting “textbook quality” data we were able to train a model that surpasses almost all open-source models on coding benchmarks such as HumanEval and MBPP despite being $1 0 \mathrm { x }$ smaller in model size and $1 0 0 \mathrm { x }$ smaller in dataset size. We hypothesize that such high quality data dramatically improves the learning efficiency of language models for code as they provide clear, self-contained, instructive, and balanced examples.
136
+
137
+ There remains a number of limitations of our model compared to larger models for code. Firstly, phi1 is specialized in Python coding, which restricts its versatility compared to multi-language models. Secondly, phi-1 lacks the domain-specific knowledge of larger models such as programming with specific APIs or using less common packages. Lastly, due to the structured nature of the datasets and the lack of diversity in terms of language and style, phi-1 is less robust to stylistic variations or errors in the prompt (for instance, its performance substantially degrades with grammatical mistakes in the prompt). We expand on these limitations and other failure modes of phi-1 in Appendix B.
138
+
139
+ None of these limitations seem fundamental, and with more work our approach could be used to tackle each one of them, although it is unclear what scaling might be necessary to overcome them (both for the model size and the dataset size). We also believe that significant gains could be achieved by using GPT-4 to generate the synthetic data instead of GPT-3.5, as we noticed that GPT-3.5 data has a high error rate. It is interesting that phi-1 is able to achieve such high coding proficiency despite those errors (a similar phenomenon was observed in Allen-Zhu & Li (2023) where a language model can be trained on data with $100 \%$ error rate and still generate correct answers at test time).
140
+
141
+ More generally, our work provides evidence that developing good methodology for creating highquality datasets is a central direction of research for advancing natural language processing and related fields (see also Jung et al. (2023) for further evidence). However, creating high-quality datasets is not a trivial task, and it poses several challenges that need to be addressed. One challenge is to ensure that the dataset covers all the relevant content and concepts that one wants the model to learn, and that it does so in a balanced and representative way. Another challenge is to ensure that the dataset is truly diverse and non-repetitive, so that the model does not simply overfit to the data or memorize specific patterns or solutions. This requires finding ways to inject randomness and creativity into the data generation process, while still maintaining the quality and the coherence of the examples. Moreover, even after creating such datasets, we lack a good methodology to measure and evaluate the amount of diversity and redundancy in the data. For example, if we have a dataset with coding exercises, it is hard to determine how many different variations of each exercise exist, and how they are distributed across the dataset. Finally, as language models themselves will be used to curate data for future language models, it further increases the urgency on the ethical and social implications of training such models, such as the accountability, the transparency, and the bias of the data and the models that are involved in this process.
142
+
143
+ REFERENCES
144
+ Loubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, et al. Santacoder: don’t reach for the stars! arXiv preprint arXiv:2301.03988, 2023.
145
+ Zeyuan Allen-Zhu and Yuanzhi Li. Physics of language models: Part 1, context-free grammar. arXiv preprint arXiv:2305.13673, 2023.
146
+ Rohan Anil, Andrew M Dai, Orhan Firat, Melvin Johnson, Dmitry Lepikhin, Alexandre Passos, Siamak Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng Chen, et al. Palm 2 technical report. arXiv preprint arXiv:2305.10403, 2023.
147
+ Jacob Austin, Augustus Odena, Maxwell Nye, Maarten Bosma, Henryk Michalewski, David Dohan, Ellen Jiang, Carrie Cai, Michael Terry, Quoc Le, et al. Program synthesis with large language models. arXiv preprint arXiv:2108.07732, 2021.
148
+ Mohammad Bavarian, Heewoo Jun, Nikolas Tezak, John Schulman, Christine McLeavey, Jerry Tworek, and Mark Chen. Efficient training of language models to fill in the middle. arXiv preprint arXiv:2207.14255, 2022.
149
+ Emily M Bender, Timnit Gebru, Angelina McMillan-Major, and Shmargaret Shmitchell. On the dangers of stochastic parrots: Can language models be too big? In Proceedings of the 2021 ACM Conference on Fairness, Accountability, and Transparency, pp. 610–623, 2021.
150
+ Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, and Samuel Weinbach. GPTNeoX-20B: An open-source autoregressive language model. In Proceedings of the ACL Workshop on Challenges & Perspectives in Creating Large Language Models, 2022. URL https: //arxiv.org/abs/2204.06745.
151
+ Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel Ziegler, Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. Language models are few-shot learners. In Advances in Neural Information Processing Systems, volume 33, pp. 1877–1901, 2020.
152
+ Sebastien Bubeck, Varun Chandrasekaran, Ronen Eldan, Johannes Gehrke, Eric Horvitz, Ece Ka-´ mar, Peter Lee, Yin Tat Lee, Yuanzhi Li, Scott Lundberg, et al. Sparks of artificial general intelligence: Early experiments with gpt-4. arXiv preprint arXiv:2303.12712, 2023.
153
+ Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, et al. Evaluating large language models trained on code. arXiv preprint arXiv:2107.03374, 2021.
154
+ Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311, 2022.
155
+ Tri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Re. Flashattention: Fast and memory- ´ efficient exact attention with io-awareness. Advances in Neural Information Processing Systems, 35:16344–16359, 2022.
156
+ Yann Dubois, Xuechen Li, Rohan Taori, Tianyi Zhang, Ishaan Gulrajani, Jimmy Ba, Carlos Guestrin, Percy Liang, and Tatsunori B Hashimoto. Alpacafarm: A simulation framework for methods that learn from human feedback. arXiv preprint arXiv:2305.14387, 2023.
157
+ Ronen Eldan and Yuanzhi Li. Tinystories: How small can language models be and still speak coherent english? arXiv preprint arXiv:2305.07759, 2023.
158
+ Arnav Gudibande, Eric Wallace, Charlie Snell, Xinyang Geng, Hao Liu, Pieter Abbeel, Sergey Levine, and Dawn Song. The false promise of imitating proprietary llms. arXiv preprint arXiv:2305.15717, 2023.
159
+ Joel Hestness, Sharan Narang, Newsha Ardalani, Gregory Diamos, Heewoo Jun, Hassan Kianinejad, Md Mostofa Ali Patwary, Yang Yang, and Yanqi Zhou. Deep learning scaling is predictable, empirically. arXiv preprint arXiv:1712.00409, 2017.
160
+ Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, Tom Hennigan, Eric Noland, Katherine Millican, George van den Driessche, Bogdan Damoc, Aurelia Guy, Simon Osindero, Karen Simonyan, Erich Elsen, Oriol Vinyals, Jack William Rae, and Laurent Sifre. An empirical analysis of compute-optimal large language model training. In Alice H. Oh, Alekh Agarwal, Danielle Belgrave, and Kyunghyun Cho (eds.), Advances in Neural Information Processing Systems, 2022.
161
+ Jaehun Jung, Peter West, Liwei Jiang, Faeze Brahman, Ximing Lu, Jillian Fisher, Taylor Sorensen, and Yejin Choi. Impossible distillation: from low-quality model to high-quality dataset & model for summarization and paraphrasing. arXiv preprint arXiv:2305.16635, 2023.
162
+ 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. arXiv preprint arXiv:2001.08361, 2020.
163
+ Denis Kocetkov, Raymond Li, Loubna Ben Allal, Jia Li, Chenghao Mou, Carlos Munoz Ferran-˜ dis, Yacine Jernite, Margaret Mitchell, Sean Hughes, Thomas Wolf, et al. The stack: 3 tb of permissively licensed source code. arXiv preprint arXiv:2211.15533, 2022.
164
+ Aitor Lewkowycz, Anders Andreassen, David Dohan, Ethan Dyer, Henryk Michalewski, Vinay Ramasesh, Ambrose Slone, Cem Anil, Imanol Schlag, Theo Gutman-Solo, Yuhuai Wu, Behnam Neyshabur, Guy Gur-Ari, and Vedant Misra. Solving quantitative reasoning problems with language models. In S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh (eds.), Advances in Neural Information Processing Systems, volume 35, pp. 3843–3857. Curran Associates, Inc., 2022. URL https://proceedings.neurips.cc/paper_files/paper/2022/ file/18abbeef8cfe9203fdf9053c9c4fe191-Paper-Conference.pdf.
165
+ Raymond Li, Loubna Ben Allal, Yangtian Zi, Niklas Muennighoff, Denis Kocetkov, Chenghao Mou, Marc Marone, Christopher Akiki, Jia Li, Jenny Chim, et al. Starcoder: may the source be with you! arXiv preprint arXiv:2305.06161, 2023.
166
+ Zinan Lin, Sivakanth Gopi, Janardhan Kulkarni, Harsha Nori, and Sergey Yekhanin. Differentially private synthetic data via foundation model apis 1: Images. arXiv preprint arXiv:2305.15560, 2023.
167
+ Jiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and Lingming Zhang. Is your code generated by chatgpt really correct? rigorous evaluation of large language models for code generation. arXiv preprint arXiv:2305.01210, 2023.
168
+ Shayne Longpre, Gregory Yauney, Emily Reif, Katherine Lee, Adam Roberts, Barret Zoph, Denny Zhou, Jason Wei, Kevin Robinson, David Mimno, et al. A pretrainer’s guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity. arXiv preprint arXiv:2305.13169, 2023.
169
+ Ziyang Luo, Can Xu, Pu Zhao, Qingfeng Sun, Xiubo Geng, Wenxiang Hu, Chongyang Tao, Jing Ma, Qingwei Lin, and Daxin Jiang. Wizardcoder: Empowering code large language models with evol-instruct, 2023.
170
+ Niklas Muennighoff, Alexander M Rush, Boaz Barak, Teven Le Scao, Aleksandra Piktus, Nouamane Tazi, Sampo Pyysalo, Thomas Wolf, and Colin Raffel. Scaling data-constrained language models. arXiv preprint arXiv:2305.16264, 2023.
171
+ Subhabrata Mukherjee, Arindam Mitra, Ganesh Jawahar, Sahaj Agarwal, Hamid Palangi, and Ahmed Awadallah. Orca: Progressive learning from complex explanation traces of gpt-4. arXiv preprint arXiv:2306.02707, 2023.
172
+ 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. arXiv preprint, 2022.
173
+ Erik Nijkamp, Hiroaki Hayashi, Caiming Xiong, Silvio Savarese, and Yingbo Zhou. Codegen2: Lessons for training llms on programming and natural languages. arXiv preprint arXiv:2305.02309, 2023a.
174
+ 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, 2023b.
175
+ OpenAI. Gpt-4 technical report, 2023. arXiv preprint arXiv:2303.08774 [cs.CL].
176
+ 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. The Journal of Machine Learning Research, 21(1):5485–5551, 2020.
177
+ Replit. Replit dev day. https://twitter.com/Replit/status/ 1651344184593506304, 2023.
178
+ Ilia Shumailov, Zakhar Shumaylov, Yiren Zhao, Yarin Gal, Nicolas Papernot, and Ross Anderson. Model dementia: Generated data makes models forget. arXiv preprint arXiv:2305.17493, 2023.
179
+ Jianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. arXiv preprint arXiv:2104.09864, 2021.
180
+ Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, and Tatsunori B. Hashimoto. Stanford alpaca: An instruction-following llama model. https://github.com/tatsu-lab/stanford_alpaca, 2023.
181
+ Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Ł ukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems, volume 30, 2017.
182
+ Yizhong Wang, Yeganeh Kordi, Swaroop Mishra, Alisa Liu, Noah A Smith, Daniel Khashabi, and Hannaneh Hajishirzi. Self-instruct: Aligning language model with self generated instructions. arXiv preprint arXiv:2212.10560, 2022.
183
+ Yue Wang, Hung Le, Akhilesh Deepak Gotmare, Nghi DQ Bui, Junnan Li, and Steven CH Hoi. Codet5+: Open code large language models for code understanding and generation. arXiv preprint arXiv:2305.07922, 2023.
184
+ Jason Wei, Yi Tay, Rishi Bommasani, Colin Raffel, Barret Zoph, Sebastian Borgeaud, Dani Yogatama, Maarten Bosma, Denny Zhou, Donald Metzler, Ed H. Chi, Tatsunori Hashimoto, Oriol Vinyals, Percy Liang, Jeff Dean, and William Fedus. Emergent abilities of large language models. Transactions on Machine Learning Research, 2022. Survey Certification.
185
+ Da Yu, Sivakanth Gopi, Janardhan Kulkarni, Zinan Lin, Saurabh Naik, Tomasz Lukasz Religa, Jian Yin, and Huishuai Zhang. Selective pre-training for private fine-tuning. arXiv preprint arXiv:2305.13865, 2023.
186
+ Qinkai Zheng, Xiao Xia, Xu Zou, Yuxiao Dong, Shan Wang, Yufei Xue, Zihan Wang, Lei Shen, Andi Wang, Yang Li, Teng Su, Zhilin Yang, and Jie Tang. Codegeex: A pre-trained model for code generation with multilingual evaluations on humaneval-x, 2023.
187
+
188
+ # A ADDITIONAL EXAMPLES FOR SECTION 3
189
+
190
+ In Section 3, we discussed with a couple examples on how finetuned modes shows a substantial improvement over the base model in executing tasks that are not featured in the finetuning dataset. Here we provide additional examples and details to further illustrate improvements in the areas of model understanding in managing intricate algorithmic tasks and using external libraries.
191
+
192
+ # A.1 FINETUNING IMPROVES THE MODEL’S UNDERSTANDING ABILITY
193
+
194
+ The example below is challenging due to the prevalence of various logical operators such as “and” and “not” that link numerous statements. Prior to finetuning, the model is confused by the logic embedded in the statement. It struggles to differentiate between “elements” and “indices”, and is unsure about which array to use. Conversely, the finetuned model is adept at accurately identifying all relevant arrays and indices, while correctly implementing the logical operators.
195
+
196
+ # Prompt:
197
+
198
+ """ Input is an array A, an array B, an array C, an array E, a numpy matrix D. I want to find all the indices of D whose elements are in the union of B and C and whose row index is not in A and column index is in D. Loop through the elements in D. Return the list of indices. """
199
+
200
+ # phi-1
201
+
202
+ indices = []
203
+ for i in range(D.shape[0]): for j in range(D.shape [1]): if D[i][j] in B or D [i][j] in C: if i not in A and j in D: indices. append((i,j))
204
+ return indices
205
+
206
+ # phi-1-base
207
+
208
+ # phi-1-small
209
+
210
+ indices = []
211
+ for i in range(len(D)): for j in range(len(D[i]) ): if D[i][j] in B and D[i][j] not in A: indices.append(j )
212
+ return indices
213
+ indices = []
214
+ for i in range(D.shape[1]): if D[0][i] in B and D [0][i] not in A and D[i ][0] in C and D[i][0] not in E: indices.append(i)
215
+ return indices
216
+
217
+ # A.2 FINETUNING IMPROVES THE MODEL’S ABILITY TO USE EXTERNAL LIBRARIES
218
+
219
+ In Section 3, we demonstrate with an example prompt using PyGame library that our finetuned phi1 model remarkably improves over phi-1-base even though our finetuning CodeExercises does not contain examples involving PyGame packages. For reference, Figure 4 shows the distribution of package imports in our CodeExercises dataset.
220
+
221
+ ![](images/875c455fe828a359404a5503156891b6ec52c389b0eb93689ecb8708e731f563.jpg)
222
+ Figure 4: The number of imports among 879486 exercises in the finetuning (ignored libraries imported ${ < } 1 0$ times). The plot itself is generated by phi-1 from dictionary of imports with the prompt: “I have a dictionary, first sort the dictionary using the value, from largest to smallest. Then generate a pyplot bar plot. First set font size to be 7, then rotate the x-axis label by 90 degree, the $\mathbf { X } ^ { }$ -axis is the key, y-axis is the value of the dictionary. Use log-scale on y-axis. Moreover, set the y-axis label to be ‘Log Number of Times’ and $\mathbf { X }$ -axis label to be ‘Imports’. Set dpi to be 1000.”
223
+
224
+ In the following, we provide additional examples to show how our finetuning with CodeExercises dataset unexpectedly improves the model’s ability to use external libraries such as Tkinter, pyplot, and pytorch, eventhough our exercises do not contain these libraries.
225
+
226
+ TKinter example. Our second example is a TKinter application where we ask the model to update a textfield accordingly when the user clicks buttons.
227
+
228
+ # Prompt:
229
+
230
+ """ Write a tkinter application, there is a textfield on top, a submit button at the button and a recover button next to it. When pressing the submit button, get the text from the textfield and save it to a global string s. If the text contains the word "pew" update the textfield text to "pewpewpew?", otherwise, add "no pew..." to the end. When pressing the recover button, replace the text in the textfield with s.
231
+ """
232
+
233
+ # phi-1
234
+
235
+ global s
236
+ s = ""
237
+ def submit(): global s text $=$ textfield.get() if "pew" in text: textfield.delete(0, tk.END) textfield.insert(0, "pewpewpew. ) else: textfield.delete(0, tk.END) textfield.insert(0, text $^ +$ "no pew ") s $=$ text
238
+ def recover(): global s textfield.delete(0, tk.END) textfield.insert(0, s)
239
+ textfield $=$ tk.Entry(root)
240
+ textfield.pack()
241
+ submit_button $=$ tk.Button(root, text=" Submit", command=submit)
242
+ submit_button.pack()
243
+ recover_button $=$ tk.Button(root, text=" Recover", command=recover)
244
+ recover_button.pack()
245
+ root.mainloop()
246
+
247
+ # phi-1-base
248
+
249
+ global s
250
+ s $=$ s.replace("pew", "pewpewpew")
251
+ if "pew" in s: s $=$ s.replace("pew", "pewpewpew")
252
+ else: s = s + "no pew.. 1
253
+ text.delete(0.0, END)
254
+ text.insert(0.0, s)
255
+ def main(): global s s $=$ "pewpewpew" text.delete(0.0, END) text.insert(0.0, s) text.tag_add("button", "<Button-1>", "< Button-3>") text.tag_add("button", "<Button-2>", "< Button-4>") # The model keeps adding buttons from here.
256
+
257
+ # phi-1-small
258
+
259
+ import tkinter as tk
260
+ root $=$ tk.Tk()
261
+ global s
262
+ text = ""
263
+ while True: event, values $=$ tk.popup() if event $= =$ "submit": text $+ =$ values.split()[0] + " 1 elif event $= =$ "textfield": s $+ =$ values.split()[0] $^ +$ " " elif event $= =$ "submit-button-text": text $=$ values.split()[0] $^ +$ " " elif event $= =$ "text-button-text": s $=$ text if "pew" in text: text $=$ text.replace("pew", "pewpewpew") if "no pew" in text: break
264
+ tk.destroy()
265
+
266
+ The three models’ completions show a huge gap in their prompt understanding. Both phi-1-base and phi-1-small fail to use the correct Tkinter APIs and make up meaningless function calls. On the other hand, phi-1 implements the GUI and all the functions correctly (except that it did not copy “pewpewpew?” correctly).
267
+
268
+ Chat mode example. Finally, we show that phi-1 has a better chat capability than phi-1-base despite that chat data is exclusive in pretraining, but not in the finetuning.
269
+
270
+ # Prompt:
271
+
272
+ Student: I have a Python pyplot, and rotate it, what should I do? phi-1
273
+
274
+ I want to increase its resolution TA:
275
+
276
+ # phi-1-base
277
+
278
+ 1. Set the 'dpi' parameter to the desired
279
+ resolution (e.g. 300 for 300 DPI)
280
+ 2. Use the 'rotate' function from the '
281
+ matplotlib.pyplot' module to rotate the plot
282
+ by 90 degrees clockwise
283
+ Here's an example:
284
+ import matplotlib.pyplot as plt
285
+ fig, ax $=$ plt.subplots()
286
+ ax.plot([1, 2, 3], [4, 5, 6])
287
+ # Set the resolution to 300 DPI
288
+ ax.set_dpi(300)
289
+ # Rotate the plot by 90 degrees clockwise
290
+ ax.rotate(90)
291
+
292
+ You can use the \`setp()\` function to set the resolution and the \`set_rotation()\` function to rotate the plot. <|endoftext|>
293
+
294
+ # phi-1-small
295
+
296
+ I am a Python pyplot, and I want to increase its resolution and rotate it, what should I do?
297
+ SECOND:
298
+ I am a Python pyplot, and I want to increase its resolution and rotate it, what should I do?
299
+ THIRD:...
300
+
301
+ Pytorch example. In this PyTorch example, we ask the model to write a modified gradient update:
302
+
303
+ # Prompt:
304
+
305
+ """ Write a pytorch function. The input is a model, take the gradient of each parameter of the model, do an SVD of each gradient to get U, Sigma, V, take the top k singular values of Sigma as Sigmak, then do a update step to the parameter using Uk $\star$ Sigmak $\star \mathrm { V k }$ times the norm of the parameter.
306
+
307
+ # phi-1
308
+
309
+ # phi-1-base
310
+
311
+ # phi-1-small
312
+
313
+ for p in model.parameters(): if p.grad is not None: U, Sigma, $\mathrm { ~ v ~ } = \mathrm { ~ p ~ }$ .grad.svd() Sigmak $=$ Sigma[:k].diag() p.data.add_(torch.mm(U[:,: k], torch.mm(Sigmak, $\mathbb { V } \left[ : \mathbb { k } , : \right]$ ) ). $\mathtt { \cdot m u l \_ m o r m } )$ )
314
+
315
+ self.model $=$ model
316
+ self.k $\mathit { \Theta } = \mathit { \Theta } \mathrm { \ l } \mathit { \Theta }$
317
+ self.eps $=$ eps
318
+ self.max_iter $=$
319
+ max_iter
320
+ self.verbose $=$
321
+ verbose
322
+ self.svd_u $=$ None
323
+ self.svd_sigma $=$ None self.svd_v $=$ None
324
+ self.svd_k $=$ None
325
+ self.svd_u_k $=$ None self.svd_sigma_k $=$
326
+ None
327
+ self.svd_v_k $=$ None ...
328
+ def svd(x): u, s, v = np.linalg.svd(x) return u, s, v
329
+ def update_parameter(parameter, grad): u, s, $\qquad \lor \quad =$ svd(grad) parameter $=$ u[:, :k] np.diag(s[:k]) v[:k, :] parameter $+ =$ np.diag(sigmoid (parameter)) return parameter
330
+
331
+ The code by phi-1-small reveals a lack of understanding of the prompt, leading to multiple significant missteps. First, it uses np.linalg.svd $\mathbf { \tau } ( \mathbf { x } )$ , which is incompatible with PyTorch tensors. Second, it erroneously assigns the SVD result directly to the parameter, deviating from the prompt’s instruction to add it. On the other hand, phi-1-base is completely clueless and only produces a sequence of meaningless definitions. This indicates that improving the model’s logical reasoning ability (even only on simple functions) can greatly enhance the model’s general coding ability.
332
+
333
+ Pyplot example. The final API example is a Pyplot application. The model is generally good with Pyplot, so we design a challenging task to ask the model implement an animation.
334
+
335
+ # Prompt:
336
+
337
+ """Create an x array that are integers from 1 to 20, y array that is equal to the elementwise cos of $_ \textrm { x }$ divided by element-wise sqrt(x + 1). Write a Python code of line plot that animates the change of y according to x \*\*\*step by step\*\*\* with red lines. However, during the animation, when x[i] is larger than 11, change the animation line color from red to green.
338
+ """
339
+
340
+ # phi-1
341
+
342
+ # phi-1-base
343
+
344
+ # phi-1-small
345
+
346
+ ... ... ...
347
+ $\textrm { \scriptsize x } =$ np.arange(1, 21) fig, ax $=$ plt.subplots() fig, ax $=$ plt.subplots()
348
+ y $=$ np.cos(x) / np.sqrt( $\mathrm { ~ ~ { ~ x ~ } ~ } + \mathrm { ~ ~ { ~ 1 ~ } ~ }$ ) $\textrm { \textbf { x } } =$ np.arange(1, 21) x_array $=$ list(range(1, 21)
349
+ fig, ax $=$ plt.subplots() $\begin{array} { r l } { \mathrm { y } } & { { } = } \end{array}$ np.cos(x) / np.sqrt(x + )
350
+ line, $=$ ax.plot([], [], color= 1) y_array $=$ [math.cos(xi/10) 'red') line, $=$ ax.plot([], [], lw for xi in x_array] $^ { = 2 }$ ) def animate(i):
351
+ ax.set_title('Animation of def init(): ... Cosine and Cosine-Square line.set_data([], []) ax.plot(x_array, Root') return line, y_array)
352
+ def animate(i): def animate(i): if x_array[i] > 11: $\mathrm { i f ~ \ x [ \mathrm { i } ] ~ > ~ \mathrm { 1 1 } }$ : $\mathrm { i f ~ \ x [ \mathrm { i } ] ~ > ~ \mathrm { 1 1 } }$ : color $=$ "red" line.set_color('green' line.set_color(' else: ) green') color $=$ "green" else: else: ax.scatter(x_array[i], line.set_color('red') line.set_color('red y_array[i], color=color line.set_data(x[:i+1], y[: ') ) $\dot { 1 } + 1 1$ ) return line, return ax return line, anim $=$ FuncAnimation(fig, ani $=$ animation.
353
+ anim $=$ animation.FuncAnimation animate, init_func $\mathbf { \equiv } = \mathbf { \Phi } _ { \mathrm { - } }$ init FuncAnimation(fig, (fig, animate, frames=len , frames=len(x), animate, frames=len( $( \times )$ , interval=500, blit= interval $= 5 0$ , blit=True) x_array), interval=50, True) blit=True)
354
+ plt.show() plt.show()
355
+
356
+ phi-1-small produces a very incorrect completion. From the API perspective, the model fails to understand the “line plot” requirement and only uses a scatter plot (and even that is implemented wrongly). phi-1-base gets the template correct, but misses the core function to update the line plot every iteration.
357
+
358
+ # B LIMITATION OF PHI-1
359
+
360
+ While finetuning through simple exercises significantly enhances the model’s overall performance, there are certain constraints intrinsic to our model that cannot be overcome solely by finetuning. Firstly, our model has only 1.3B parameters trained with only 7B tokens, this restricts our model’s capacity to manage more complex tasks such as developing an intricate Flask application, in comparison to other models like Starcoder. Beyond our model’s limitations in terms of generality when contrasted with StarCoder or ChatGPT, we’ve also outlined several other weaknesses as follows:
361
+
362
+ Sensitivity to prompt variations. Our model is sensitive to various perturbations of prompts. First, its performance drops significantly as the length of the prompt increases, as it tends to ignore, forget or misinterpret parts of the prompt when it is too long. For example, our model fails when we increase the number of layers from 3 to 4 in the following case. We hypothesize that this issue arises because our exercises predominantly consist of short prompts. Furthermore, its generation may appear qualitatively different with a slightly modified prompt. In this case, with an additional import torch command, the model tends to succeed on the very task that it failed previously.
363
+
364
+ # Prompt:
365
+
366
+ """ Create a neural
367
+ network class in Pytorch with 3 layers. Implement a new "rr" method to this new function: It takes
368
+ input x. Apply the first layer on $_ x$ and assign the output to y, then apply
369
+ the second layer on $_ y$ and assign the output to $_ z$ ,
370
+ then apply the third layer on $_ z$ and assign it to $_ w$ , then sum up $y , z , w$ and
371
+ assign it to $Q$ . Return $Q$ .
372
+ """
373
+
374
+ # Prompt:
375
+
376
+ """ Create a neural network class in Pytorch with 4 layers. Implement a new "rr" method to this new function: It takes input x. Apply the first layer on $_ x$ and assign the output to y, then apply the second layer on $_ y$ and assign the output to $_ z$ , then apply the third layer on $_ z$ and assign it to $_ w$ , then apply the forth layer on w and assign $\mathrm { i t } \ t \circ \ p$ , then sum up $y , z , w , p$ and assign it to $Q$ . Return $Q$ .
377
+
378
+ # """
379
+
380
+ # Prompt:
381
+
382
+ # import torch
383
+
384
+ """ Create a neural network class in Pytorch with 4 layers. Implement a new "rr" method to this new function: It takes input x. Apply the first layer on x and assign the output to $_ y$ , then apply the second layer on $_ y$ and assign the output to $_ z$ , then apply the third layer on $_ z$ and assign it to $_ w$ , then apply the forth layer on w and assign it to p, then sum up $y , z , w , p$ and assign it to $Q$ . Return $Q$ . """
385
+
386
+ class NeuralNetwork(nn. Module): def _init__(self): super( NeuralNetwork, self). _init__() self.layer1 $\begin{array} { r l } { = } & { { } \ \Pi \Pi } \end{array}$ . Linear(2, 5) self.layer2 $\begin{array} { r l } { = } & { { } \ \Pi \Pi } \end{array}$ . Linear(5, 3) self.layer3 $\begin{array} { r l } { = } & { { } \ \Pi \Pi } \end{array}$ . Linear(3, 1) def rr(self, x): $\begin{array} { r l } { \mathrm { y } } & { { } = } \end{array}$ self.layer1(x) $z =$ self.layer2(y) $\begin{array} { r l } { \mathbf { \nabla } \warrow } & { { } = } \end{array}$ self.layer3(z) $\mathrm { ~ ~ Q ~ } = \mathrm { ~ ~ y ~ } + \mathrm { ~ ~ z ~ } + \mathrm { ~ ~ w ~ }$ return Q
387
+
388
+ class NeuralNetwork: def _init__(self): self.layers = [] def add_layer(self, layer): self.layers.append (layer) ... def rr(self, x): y $=$ self.forward(x ) z = self.forward(y ) $\begin{array} { r l } { \mathbb { W } } & { { } = } \end{array}$ self.forward(z ) $\mathrm { ~ p ~ } =$ self.forward(w ) Q = y + z + w + p return Q
389
+
390
+ class NeuralNetwork(torch.nn. Module): def _init__(self): super(NeuralNetwork, self).__init__() self.layer1 $=$ torch.nn. Linear(10, 20) ... def forward(self, x): $\textrm { \textbf { x } } =$ torch.nn.functional. relu(self.layer1(x)) $\begin{array} { r l } { \mathrm { y } } & { { } = } \end{array}$ torch.nn.functional. relu(self.layer2(x)) $z =$ torch.nn.functional. relu(self.layer3(y)) $\begin{array} { r l } { \mathbf { \nabla } \mathsf { W } } & { { } = } \end{array}$ torch.nn.functional. relu(self.layer4(z)) p = torch.nn.functional. relu(self.output(w)) Q = p + y + z + w return Q
391
+
392
+ Sensitivity to natural language inputs. phi-1 demonstrates less robustness in handling natural language compared to ChatGPT or StarCoder, particularly with ambiguous prompts. This may be because we filter out certain types of data from the training process to guarantee textbook-level quality. For instance, our model struggles with the term “unchanged” and has difficulties interpreting a numbered list within the prompt.
393
+
394
+ # Prompt:
395
+
396
+ # Prompt:
397
+
398
+ """ Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). x increases by 2, y decreases by 5; (2). x increases by 1, y decreases by 2, (3). x stays at x, y increase by 4. Simulate the movement of the points.
399
+
400
+ # Prompt:
401
+
402
+ """ Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). move by (2, -5); (2). move by (1, 2); (3). move by (0, 4); Simulate the movement of the points.
403
+
404
+ # """
405
+
406
+ """ Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). x increases by 2, y decreases by 5; (2). x increases by
407
+ 1, y decreases by 2, (3). $_ \textrm { x }$ stays unchanged, y increase by 4. Simulate the movement of the points. """ x, $\begin{array} { r } { \mathrm { ~ y ~ } = ~ 0 , } \end{array}$ , 0 for i in range(10): move $=$ random.choice([1,
408
+ 2, 3]) if move $\mathbf { \Sigma } = \mathbf { \Sigma } \ \bar { \mathbf { \Sigma } }$ : $\times \quad + = \quad 2$ $\texttt { y } \texttt { -- } 5$ elif move $\ c = ~ 2$ : $\mathrm { ~ ~ x ~ } + = \mathrm { ~ ~ 1 ~ }$ y -= 2 elif move $\ c = ~ 3$ : x = 0 y += 4 return f"Alice's final position is $\{ \{ \bf x \} \}$ , {y})."
409
+ x, $\mathrm { ~ y ~ } = \mathrm { ~ 0 ~ }$ , 0
410
+ for i in range(10): move $=$ random.choice([1, 2, 3]) if move $\mathbf { \Sigma } = \mathbf { \Sigma } \mathbf { \Sigma } \perp$ : $\mathrm { ~ ~ x ~ } \ + = \ 2$ $\mathrm { ~ \ y ~ } \mathrel { - } = \mathrm { ~ \ } 5$ elif move $= = 2$ : $\mathrm { ~ ~ x ~ } \mathrel { + } = \mathrm { ~ ~ 1 ~ }$ y -= 2 elif move $\ c = ~ 3$ : $\begin{array} { l l l } { \mathrm { ~ x ~ } } & { = } & { \mathrm { ~ x ~ } } \\ { \mathrm { ~ y ~ } } & { + = } & { 4 } \end{array}$ print(f"Alice moved {move } point to $\cdot$ , {y})")
411
+ x, $\mathrm { ~ y ~ } = \mathrm { ~ 0 ~ }$ , 0
412
+ for i in range(n): move $=$ random.choice ([(1, 2), (2, -5), (1, 2), (3, 0), (0, 4)]) $\begin{array} { r l } { \mathrm { ~ x ~ } } & { { } + = } \end{array}$ move[0] y $+ =$ move[1]
413
+ return f"Alice moved {x} units to the right and {y} units down after {n} iterations "
414
+
415
+ Note: the model hallucinates the moves (1, 2), (3, 0).
416
+
417
+ Bad at counting and spatial reasoning. A primary constraint of our model, particularly when contrasted with alternatives like StarCoder, lies in its performance on tasks involving counting and spatial reasoning. The model struggles to consistently maintain precise data regarding the quantity and positioning of elements within a scene. To illustrate, consider the following example:
418
+
419
+ # Prompt:
420
+
421
+ """ Generate a tkinter application, I want two textfields side by side at the top, three buttons at the bottom, one named $A$ on the left, one named $B$ on the right, one named $C$ at the middle. """
422
+
423
+ # phi-1
424
+
425
+ # phi-1-small
426
+
427
+ ![](images/92fd9e8681034b250b3247d41a8acad3f9c34eda0498fb2e08efb96ec21402bf.jpg)
428
+
429
+ window $=$ tk.Tk()
430
+ window.title("TextFields")
431
+ # Create the left and right textfields
432
+ text1 $=$ tk.Text(window, text="A")
433
+ text1.pack()
434
+ text2 $=$ tk.Text(window, text $=$ "B")
435
+ text2.pack()
436
+ # Create the middle button
437
+ button $=$ tk.Button(window, text="C")
438
+ button.pack()
439
+ # Start the tkinter application
440
+ window.mainloop()
441
+
442
+ # phi-1-base
443
+
444
+ root $=$ tk.Tk()
445
+ root.title("Text Fields")
446
+ root.geometry("300x200")
447
+ root.resizable(False, False)
448
+ root.configure(background="white")
449
+ root.configure(font=("Arial", 12))
450
+ root.configure(foreground="black")
451
+ root.configure(relief="groove")
452
+ root.configure(padx ${ \bf \Lambda } = 1 0$ , pady $= 1 0$ )
453
+ root.configure(state="disabled")
454
+ # The model keeps outputting nonsensical code.
455
+
456
+ Despite the improvement from finetuning, our model still struggles with counting and spatial reasoning. It generates an extra textfield and misplaces the button in the scene.
457
+
458
+ # C APPENDIX FOR SECTION 5
459
+
460
+ # C.1 N-GRAM ANALYSIS
461
+
462
+ Our n-gram overlap analysis shows that our dataset has minimal letter-by-letter overlap with HumanEval. In particular, for our 13-gram analysis, we uncovered 4 matches to HumanEval questions, but all four of these were false positives. An example of such a false positive is given below.
463
+
464
+ # HumanEval:
465
+
466
+ You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list.
467
+
468
+ # CodeExercises:
469
+
470
+ Calculates the power frequency analysis sum of a list of integers. The power frequency analysis sum is calculated by taking the sum of the squares of the frequencies of each unique integer in the list. The frequency of an integer is the number of times it appears in the list.
471
+
472
+ # C.2 EXAMPLES OF AST AND EMBEDDING DISTANCE BASED SIMILARITY
473
+
474
+ In this section, we provide example pairs of codes captured with different AST match rates, denoted as $\tau$ in the paper. Additionally, we provide an example of code pair obtained using embedding distance as a measure of similarity.
475
+
476
+ AST match rate $\mathbf { \mu } = \mathbf { 1 . 0 }$ Here the coding problems require the same reasoning while the wording of the prompts can vary drastically. Particularly, the prompt uses a real-world event, i.e., distance between holes on a line, to implicitly teach the model the basic reasoning task of finding the closest pair of elements in an array.
477
+
478
+ # HumanEval
479
+
480
+ # CodeExercises
481
+
482
+ from typing import List, Tuple
483
+ def find_closest_elements(numbers: List[ float]) $- >$ Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) $> > >$ find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ numbers.sort() min_diff $=$ float('inf') closest_pair $=$ None for i in range(len(numbers) - 1): diff $=$ numbers[i+1] - numbers[i] if diff $<$ min_diff: min_diff $=$ diff closest_pair $=$ (numbers[i], numbers[i+1]) return closest_pair
484
+ from typing import List, Tuple
485
+ def find_closest_two_holes(holes: List[int ]) $- >$ (int, int): """ Finds the two closest holes on a line. Args: holes: A list of integers representing the positions of holes on a line. Returns: A tuple of two integers representing the positions of the two closest holes on the line. """ holes.sort() min_distance $=$ float('inf') closest_holes $=$ None for i in range(len(holes) - 1): distance $=$ holes $[ \dot { 1 } + 1 ]$ - holes[i] if distance $<$ min_distance: min_distance $=$ distance closest_holes $=$ (holes[i], holes[i+1]) return closest_holes
486
+
487
+ AST match rate $\mathbf { \omega = 0 . 9 6 }$ Here the two problems use similar reasoning and coding concepts but their prompts ask for different tasks, i.e., returning a pair of numbers versus computing their average.
488
+
489
+ ![](images/00cc89a6a89679de184c428687c060e2cf281d84a51b3aefd3067fa5213864fb.jpg)
490
+
491
+ AST match rate $\leq \mathbf { 0 . 9 }$ When the AST match rate $\leq 0 . 9$ , the code pairs start getting less similar as shown in the following two examples. Here, the AST match rate is 0.9 and 0.83, respectively.
492
+
493
+ ![](images/427f32eb7db17b1a78f831b2d0b3ecc70a0e9cf36bbda2fbb73effb396f805c5.jpg)
494
+
495
+ ![](images/3098008f8a5cb19a6b0ee7f8bbf5e8015c583725d237a6a57814b767f2311d4c.jpg)
496
+
497
+ Embedding Distance $\bf \delta = 0 . 1 6$ Here the two problems have similar Python Docstrings, function names, as well as the code structure which can be extracted with using the L2 distance between the normalized CodeGen-Mono 350M embedding for each of them.
498
+
499
+ ![](images/1dab7f11bec5bb41379764aba62985053c4e886f675060ff4c05edbb5e500ed6.jpg)
500
+
501
+ # D MODEL ARCHITECTURE AND TRAINING DETAILS
502
+
503
+ We use a decoder only transformer Vaswani et al. (2017) model using the FlashAttention implementation of multi-head attention (MHA) Dao et al. (2022). We also use MHA and MLP layers in parallel configuration following some recent models like CodeGen Nijkamp et al. (2022), PaLM Chowdhery et al. (2022), and GPT-NeoX Black et al. (2022). The architecture for our 1.3B parameter phi-1 model consists of 24 layers, hidden dimension of 2048, MLP-inner dimension of 8192, and 32 attention heads of dimension 64 each. The smaller 350M parameter phi-1-small model consists of 20 layers, hidden dimension of 1024, MLP-inner dimension of 4096, and 16 attention heads of dimension 64 each. We also use a rotary position embedding Su et al. (2021) with rotary dimension 32. These architectural choices were adopted from Nijkamp et al. (2022). We also use the same tokenizer as codegen-350M-mono Nijkamp et al. (2022). Aside from FlashAttention, our models do not use other techniques like Fill-In-the-Middle (FIM) Bavarian et al. (2022), or Multi-Query-Attention (MQA) Raffel et al. (2020) that could further boost efficiency Li et al. (2023).
504
+
505
+ For both pretraining and finetuning, we concatenate our respective datasets into a single dimensional array with “⟨∣endoftext∣⟩” token used for separating the files. We train our models on sequence length of 2048 sliced from our dataset array with next-token prediction loss. We use fp16 training with AdamW optimizer, linear-warmup-linear-decay learning rate schedule, and attention and residual dropout of 0.1. We train on 8 Nvidia-A100 GPUs using deepspeed. Our pretrained base model phi-1-base was obtained in under 4 days of training. Finetuning to obtain phi-1 used an additional 7 hours on the same hardware.
506
+
507
+ Pretraining. phi-1-base was trained on the CodeTextbook dataset (filtered code-language corpus and synthetic textbooks). We use effective batch size 1024 (including data parallelism and gradient accumulation), maximum learning rate 1e-3 with warmup over 750 steps, and weight decay 0.1, for a total of 36,000 steps. We use the checkpoint at 24,000 steps as our phi-1-base – this is equivalent to $\sim 8$ epochs on our CodeTextbook dataset for a total of little over 50B total training tokens. Despite the small size and computation, this model already achieves a $29 \%$ accuracy on HumanEval.
508
+
509
+ Finetuning. phi-1 is obtained by finetuning phi-1-base on the CodeExercises dataset. For finetuning, we use the same setup as pretraining, but different hyperparameters: we use effective batchsize of 256, maximum learning rate 1e-4 with 50 steps of warmup, and weight decay 0.01. We train for total of 6,000 steps and pick the best checkpoint (saved every 1000 steps).
parse/test/Fq8tKtjACC/Fq8tKtjACC_content_list.json ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "type": "text",
4
+ "text": "TEXTBOOKS ARE ALL YOU NEED ",
5
+ "text_level": 1,
6
+ "page_idx": 0
7
+ },
8
+ {
9
+ "type": "text",
10
+ "text": "Anonymous authors Paper under double-blind review ",
11
+ "page_idx": 0
12
+ },
13
+ {
14
+ "type": "text",
15
+ "text": "ABSTRACT ",
16
+ "text_level": 1,
17
+ "page_idx": 0
18
+ },
19
+ {
20
+ "type": "text",
21
+ "text": "We introduce phi-1, a new large language model for code, with significantly smaller size than competing models: phi-1 is a Transformer-based model with 1.3B parameters, trained for 4 days on 8 A100s, using a selection of “textbook quality” data from the web (6B tokens) and synthetically generated textbooks and exercises with GPT-3.5 (1B tokens). Despite this small scale, phi-1 attains pass $@ 1$ accuracy $5 0 . 6 \\%$ on HumanEval and $5 5 . 5 \\%$ on MBPP. It also displays surprising emergent properties compared to phi-1-base, our model before our finetuning stage on a coding exercises dataset, and phi-1-small, a model with 350M parameters trained with the same pipeline that still achieves $4 5 \\%$ on HumanEval. ",
22
+ "page_idx": 0
23
+ },
24
+ {
25
+ "type": "text",
26
+ "text": "1 INTRODUCTION ",
27
+ "text_level": 1,
28
+ "page_idx": 0
29
+ },
30
+ {
31
+ "type": "text",
32
+ "text": "The art of training large artificial neural networks has made extraordinary progress in the last decade, especially after the discovery of the Transformer architecture Vaswani et al. (2017), yet the science behind this success remains limited. Amidst a vast and confusing array of results, a semblance of order emerged around the same time as Transformers were introduced, namely that performance improves somewhat predictably as one scales up either the amount of compute or the size of the network Hestness et al. (2017), a phenomenon which is now referred to as scaling laws Kaplan et al. (2020). The subsequent exploration of scale in deep learning was guided by these scaling laws Brown et al. (2020), and discoveries of variants of these laws led to rapid jump in performances Hoffmann et al. (2022). In this work, following the footsteps of Eldan and Li Eldan & Li (2023), we explore the improvement that can be obtained along a different axis: the quality of the data. It has long been known that higher quality data leads to better results, e.g., data cleaning is an important part of modern dataset creation Raffel et al. (2020), and it can yield other side benefits such as somewhat smaller datasets Longpre et al. (2023); Yu et al. (2023) or allowing for more passes on the data Muennighoff et al. (2023). The recent work of Eldan and Li on TinyStories (a high quality dataset synthetically generated to teach English to neural networks) showed that in fact the effect of high quality data extends well past this: improving data quality can dramatically change the shape of the scaling laws, potentially allowing to match the performance of large-scale models with much leaner training/models. In this work we go beyond the initial foray of Eldan and Li to show that high quality data can even improve the SOTA of large language models (LLMs), while dramatically reducing the dataset size and training compute. Importantly, smaller models requiring less training can significantly reduce the environmental cost of LLMs Bender et al. (2021). ",
33
+ "page_idx": 0
34
+ },
35
+ {
36
+ "type": "text",
37
+ "text": "We focus our attention on LLMs trained for code, and specifically writing simple Python functions from their docstrings as in Chen et al. (2021). The evaluation benchmark proposed in the latter work, HumanEval, has been widely adopted for comparing LLMs’ performance on code. We demonstrate the power of high quality data in breaking existing scaling laws by training a 1.3B-parameter model, which we call phi-1, for roughly 8 passes over 7B tokens (slightly over 50B total tokens seen) followed by finetuning on less than 200M tokens. Roughly speaking we pretrain on “textbook quality” data, both synthetically generated (with GPT-3.5) and filtered from web sources, and we finetune on “textbook-exercise-like” data. Despite being several orders of magnitude smaller than competing models, both in terms of dataset and model size (see Table 1), we attain $5 0 . 6 \\%$ pass $@ 1$ accuracy on HumanEval and $5 5 . 5 \\%$ pass $@ 1$ accuracy on MBPP (Mostly Basic Python Programs), which are one of the best self-reported numbers using only one LLM generation. In Section 2, we give some details of our training process, and we discuss evidence for the importance of our data selection process in achieving this result. Moreover, despite being trained on much fewer tokens compared to existing models, phi-1 still displays emergent properties. In Section 3 we discuss these ",
38
+ "page_idx": 0
39
+ },
40
+ {
41
+ "type": "table",
42
+ "img_path": "images/b7a7f65a230ba220d9f54572f8147bcf25c0b1b1c1e055ec947827db5e10a131.jpg",
43
+ "table_caption": [],
44
+ "table_footnote": [],
45
+ "table_body": "<table><tr><td>Date</td><td>Model</td><td>Model size (Parameters)</td><td>Dataset size (Tokens)</td><td>HumanEval (Pass@1)</td><td>MBPP (Pass@1)</td></tr><tr><td>2021Jul</td><td>Codex-300M Chen et al. (2021)</td><td>300M</td><td>100B</td><td>13.2%</td><td>-</td></tr><tr><td>2021 Jul</td><td>Codex-12B Chen et al. (2021)</td><td>12B</td><td>100B</td><td>28.8%</td><td>=</td></tr><tr><td>2022Mar</td><td>CodeGen-Mono-350MNijkamp et al.(2023b)</td><td>350M</td><td>577B</td><td>12.8%</td><td>1</td></tr><tr><td>2022Mar</td><td>CodeGen-Mono-16.1B Nijkamp et al.(2023b)</td><td>16.1B</td><td>577B</td><td>29.3%</td><td>35.3%</td></tr><tr><td>2022 Apr</td><td>PaLM-Coder Chowdhery et al. (2022)</td><td>540B</td><td>780B</td><td>35.9%</td><td>47.0%</td></tr><tr><td>2022 Sep</td><td>CodeGeeX Zheng et al. (2023)</td><td>13B</td><td>850B</td><td>22.9%</td><td>24.4%</td></tr><tr><td>2022 Nov</td><td>GPT-3.5 OpenAI (2023)</td><td>175B</td><td>N.A.</td><td>47%</td><td></td></tr><tr><td>2022 Dec</td><td>SantaCoder Allal et al. (2023)</td><td>1.1B</td><td>236B</td><td>14.0%</td><td>35.0%</td></tr><tr><td>2023Mar</td><td>GPT-4 OpenAI (2023)</td><td>N.A.</td><td>N.A.</td><td>67%</td><td>1</td></tr><tr><td>2023 Apr</td><td>Replit Replit (2023)</td><td>2.7B</td><td>525B</td><td>21.9%</td><td>=</td></tr><tr><td>2023Apr</td><td>Replit-Finetuned Replit (2023)</td><td>2.7B</td><td>525B</td><td>30.5%</td><td></td></tr><tr><td>2023May</td><td>CodeGen2-1B Nijkamp et al. (2023a)</td><td>1B</td><td>N.A.</td><td>10.3%</td><td></td></tr><tr><td>2023 May</td><td>CodeGen2-7B Nijkamp et al. (2023a)</td><td>7B</td><td>N.A.</td><td>19.1%</td><td></td></tr><tr><td>2023May</td><td>StarCoder Li et al. (2023)</td><td>15.5B</td><td>1T</td><td>33.6%</td><td>52.7%</td></tr><tr><td>2023May</td><td>StarCoder-Prompted Li et al.(2023)</td><td>15.5B</td><td>1T</td><td>40.8%</td><td>49.5%</td></tr><tr><td>2023 May</td><td>PaLM 2-S Anil et al. (2023)</td><td>N.A.</td><td>N.A.</td><td>37.6%</td><td>50.0%</td></tr><tr><td>2023 May</td><td>CodeT5+ Wang et al. (2023)</td><td>2B</td><td>52B</td><td>24.2%</td><td>1</td></tr><tr><td>2023May</td><td>InstructCodeT5+ Wang et al.(2023)</td><td>16B</td><td>52B</td><td>35.0%</td><td></td></tr><tr><td>2023Jun</td><td>WizardCoder Luo et al. (2023)</td><td>16B</td><td>1T</td><td>57.3%</td><td>51.8%</td></tr><tr><td>2023Jun</td><td>phi-1</td><td>1.3B</td><td>7B</td><td>50.6%</td><td>55.5%</td></tr></table>",
46
+ "page_idx": 1
47
+ },
48
+ {
49
+ "type": "text",
50
+ "text": "Table 1: We use self-reported scores whenever available. Despite being trained at vastly smaller scale, phi-1 outperforms several competing models on HumanEval and MBPP. ",
51
+ "page_idx": 1
52
+ },
53
+ {
54
+ "type": "text",
55
+ "text": "emergent properties, and in particular we confirm the hypothesis that the number of parameters plays a key role in emergence (see e.g., Wei et al. (2022)), by comparing the outputs of phi-1 with those of phi-1-small, a model trained with the same pipeline but with only 350M parameters. The methodology used in this section is reminiscent of the Sparks of AGI paper Bubeck et al. (2023) for beyond-benchmark evaluation. Finally in Section 4 we discuss alternative benchmarks to evaluate the model and in Section 5 we study possible contamination of our training data with respect to HumanEval. We release the model for usage and evaluation by the broader community, but omit some details of the synthetic data generation, for proprietary reasons1. ",
56
+ "page_idx": 1
57
+ },
58
+ {
59
+ "type": "text",
60
+ "text": "More related works. Our work is part of the recent program of using LLMs for program synthesis, see Chen et al. (2021); Nijkamp et al. (2022) for more references on this. Our approach is also part of the emerging trend of using existing LLMs to synthesize data for the training of new generations of LLMs, Wang et al. (2022); Taori et al. (2023); Mukherjee et al. (2023); Lin et al. (2023); Jung et al. (2023). There is an ongoing debate about whether such “recursive training” might lead to narrower scope for the resulting LLM Shumailov et al. (2023); Gudibande et al. (2023), see Mukherjee et al. (2023) for a counterviewpoint. Note that in this paper we focus on a narrow task, similarly to Jung et al. (2023), where it is plausible to improve upon the teacher LLM (as is argued in the latter paper). ",
61
+ "page_idx": 1
62
+ },
63
+ {
64
+ "type": "text",
65
+ "text": "2 TRAINING DETAILS AND THE IMPORTANCE OF HIGH-QUALITY DATA ",
66
+ "text_level": 1,
67
+ "page_idx": 1
68
+ },
69
+ {
70
+ "type": "text",
71
+ "text": "As alluded to in the title of the paper, the central ingredient our model relies on textbook-quality training data. We devote this section primarily to our data curation ideas 2. ",
72
+ "page_idx": 1
73
+ },
74
+ {
75
+ "type": "text",
76
+ "text": "Previous work used standard sources of text and code data for code generation, such as The Stack Kocetkov et al. (2022) and other web-based datasets (e.g., StackOverflow). While these form large and diverse corpus covering broad range of topics and use cases, we argue that these sources are not optimal for teaching the model how to reason and plan algorithmically. Based on manual inspection we observe that many of these snippets are not very instructive for learning the basics of coding: ",
77
+ "page_idx": 1
78
+ },
79
+ {
80
+ "type": "text",
81
+ "text": "• Many samples are not self-contained, meaning that they depend on other modules or files that are external to the snippet, making them hard to understand without additional context. \n• Typical examples do not involve any meaningful computation, but rather consist of trivial or boilerplate code, such as defining constants, parameters, or configuring GUI elements. \n• Samples that do contain algorithmic logic are often buried inside complex or poorly documented functions, making them difficult to follow or learn from. \n• The examples are skewed towards certain topics or use cases, resulting in an unbalanced distribution of coding concepts and skills across the dataset. ",
82
+ "page_idx": 1
83
+ },
84
+ {
85
+ "type": "image",
86
+ "img_path": "images/6d763b34a506d5c744e84aab37a82f7a9de1f8b3bdcaf6ccdc32d1839f0a61dd.jpg",
87
+ "image_caption": [
88
+ "Figure 1: Pass $@ 1$ accuracy $( \\% )$ on HumanEval. The grouping of bar plots correspond to the usual scaling dimensions of either increasing the compute time (more passes on the data, here from 26B tokens seen to 76B) or increasing the number of parameters of the model (here from 350M to 1.3B). Each column within a group corresponds to different training datasets: (A) The first (orange) column represents the performance of models trained on the standard datasets of deduplicated Python files from The Stack and StackOverflow; (B) The second (light green) column represents the performance of models trained with our new dataset composition CodeTextbook; (C) Finally, the third (dark green) column corresponds to the respective second column models finetuned on our new CodeExercises dataset. For the 1.3B models, phi-1 and phi-1-base are checkpoints after training on 51B tokens and The Stack $^ +$ model was trained for 76B tokens. We highlight that even without any finetuning, our phi-1-base model trained on CodeTextbook dataset achieves $2 9 \\%$ HumanEval performance with a mere 1.3B parameter model. The previous smallest model that achieves close to $30 \\%$ performance on HumanEval was Replit-Finetuned at 2.7B parameters, which was trained with 100 times more training tokens than us Replit (2023). On top of this, finetuning on our CodeExercises dataset to obtain phi-1 not only gives us our top performance of $51 \\%$ on HumanEval, but also unlocks unexpected coding capabilities (see Section 3). "
89
+ ],
90
+ "image_footnote": [],
91
+ "page_idx": 2
92
+ },
93
+ {
94
+ "type": "text",
95
+ "text": "One can only imagine how frustrating and inefficient it would be for a human learner to try to acquire coding skills from these datasets, as they would have to deal with a lot of noise, ambiguity, and incompleteness in the data. We hypothesize that these issues also affect the performance of language models, as they reduce the quality and quantity of the signal that maps natural language to code. We conjecture that language models would benefit from a training set that has the same qualities as a good “textbook”: it should be clear, self-contained, instructive, and balanced. ",
96
+ "page_idx": 2
97
+ },
98
+ {
99
+ "type": "text",
100
+ "text": "In this work, we address this challenge directly and show that by intentionally selecting and generating high-quality data, we can achieve state-of-the-art results on code-generation tasks with a much smaller model and less compute than existing approaches. Our training relies on three main datasets: ",
101
+ "page_idx": 2
102
+ },
103
+ {
104
+ "type": "text",
105
+ "text": "• A filtered code-language dataset, which is a subset of The Stack and StackOverflow, obtained by using a language model-based classifier (consisting of about 6B tokens). • A synthetic textbook dataset of ${ < } 1 \\mathbf { B }$ tokens of GPT-3.5 generated Python textbooks. • A small synthetic exercises dataset of $\\mathord { \\sim } 1 8 0 \\mathbf { M }$ tokens of Python exercises and solutions. ",
106
+ "page_idx": 2
107
+ },
108
+ {
109
+ "type": "text",
110
+ "text": "We describe those datasets in more detail in the next subsections. Taken together, the above datasets contain less than 7B tokens. We refer to the combination of filtered code-language and synthetic textbook datasets as “CodeTextbook” and use it in the pretraining phase to obtain our base model phi-1-base—this model already achieves a competitive HumanEval performance of $2 9 \\%$ . Then we use the 180M token synthetic exercises dataset, referred to as “CodeExercises”, to finetune our phi1-base model to obtain phi-1. Despite the small size of the “CodeExercises” dataset, finetuning with this dataset is crucial not only for large improvements in generating simple Python function as shown in Figure 1, but more broadly to unlock many interesting emergent capabilities in our phi-1 model that are not observed in phi-1-base (see Section 3). ",
111
+ "page_idx": 2
112
+ },
113
+ {
114
+ "type": "text",
115
+ "text": "2.1 FILTERING OF EXISTING CODE DATASETS USING A TRANSFORMER-BASED CLASSIFIER ",
116
+ "text_level": 1,
117
+ "page_idx": 2
118
+ },
119
+ {
120
+ "type": "text",
121
+ "text": "We begin with publicly available Python code datasets: we use the Python subset of the deduplicated version of The Stack and the StackOverflow, which together contain over 35 million files/samples, totalling over 35B tokens. We annotate the quality of a small subset of these files (about $1 0 0 \\mathrm { k }$ samples) using GPT-4: given a code snippet, the model is prompted to “determine its educational value for a student whose goal is to learn basic coding concepts”. ",
122
+ "page_idx": 2
123
+ },
124
+ {
125
+ "type": "text",
126
+ "text": "We then use this annotated dataset to train a random forest classifier that predicts the quality of a file/sample using its output embedding from a pretrained codegen model as features. We note that unlike GPT-3.5, which we use extensively to generate synthetic content (discussed below), we use GPT-4 minimally only for annotations on the quality of a small subset of The Stack and StackOverflow samples. We thus view our usage of GPT-4 as merely a way to avoid tedious humanannotation efforts Dubois et al. (2023). ",
127
+ "page_idx": 3
128
+ },
129
+ {
130
+ "type": "image",
131
+ "img_path": "images/008198bd8bc80c39caf5939c62445e4deaee1e61fa6a2db476416e6621152e86.jpg",
132
+ "image_caption": [],
133
+ "image_footnote": [],
134
+ "page_idx": 3
135
+ },
136
+ {
137
+ "type": "text",
138
+ "text": "Our filtering boosts model performance significantly even without the synthetic datasets discussed below: for 350M parameter models trained on unfiltered Stack (deduplicated python) and StackOverflow, the HumanEval performance saturates at $1 2 . 1 9 \\%$ even after training for 96k steps (200B tokens), while training on the filtered subset achieves $1 7 . 6 8 \\%$ on HumanEval after $3 6 \\mathrm { k }$ steps. We further improve this to $2 0 . 1 2 \\%$ (reported in Figure 1) by training on a combination of the filtered dataset and the synthetic textbooks dataset discussed below. ",
139
+ "page_idx": 3
140
+ },
141
+ {
142
+ "type": "text",
143
+ "text": "2.2 CREATION OF SYNTHETIC TEXTBOOK-QUALITY DATASETS ",
144
+ "text_level": 1,
145
+ "page_idx": 3
146
+ },
147
+ {
148
+ "type": "text",
149
+ "text": "One of the main challenges in creating a high-quality dataset for code generation is ensuring that the examples are diverse and non-repetitive. By diversity, we mean that the examples should cover a wide range of coding concepts, skills, and scenarios, and that they should vary in their level of difficulty, complexity, and style. Diversity is important for several reasons: it exposes the language model to different ways of expressing and solving problems in code, it reduces the risk of overfitting or memorizing specific patterns or solutions, and it increases the generalization and robustness of the model to unseen or novel tasks. However, achieving diversity is not trivial, especially when using synthetic data generated by another language model. Simply prompting the model to produce a coding textbook or a set of exercises, even with some variation in the instructions or the parameters, will likely result in a very homogeneous and redundant dataset, where the same concepts and solutions are repeated over and over with minor changes. This is because language models tend to follow the most probable or common paths given their training data and their priors, and they lack the creativity or the incentive to explore alternative or novel ways of generating code. Therefore, one needs to find the right “trick” that will induce the language model to be more creative and diverse in its output, while still maintaining the quality and the coherence of the examples. Inspired by Eldan & Li (2023), where a diverse set of short stories were created by including a random subset of words chosen from some fixed vocabulary in the prompt and requiring that they would be somehow combined in the generated text, we look for ways to inject randomness into the prompt in a way that gives rise to the generation of a diverse dataset. ",
150
+ "page_idx": 3
151
+ },
152
+ {
153
+ "type": "text",
154
+ "text": "THE SYNTHETIC TEXTBOOK DATASET ",
155
+ "text_level": 1,
156
+ "page_idx": 4
157
+ },
158
+ {
159
+ "type": "text",
160
+ "text": "This dataset consists of less that 1B tokens of GPT-3.5 generated Python textbooks, synthesized to provide a high-quality source of natural language heavy text interleaved with relevant code snippets. We further targeted the content of these textbooks to cover topics that promote reasoning and basic algorithmic skills. Here, diversity is obtained by providing constraints on topics and target audience of the generated textbook. The following is an example text from the synthetic textbook: ",
161
+ "page_idx": 4
162
+ },
163
+ {
164
+ "type": "image",
165
+ "img_path": "images/d1219eaa38d9f315b8ae06cf33910f6a6f5e5a9dbec42db43a2c78dabfe85cba.jpg",
166
+ "image_caption": [],
167
+ "image_footnote": [],
168
+ "page_idx": 4
169
+ },
170
+ {
171
+ "type": "text",
172
+ "text": "THE CODEEXERCISES DATASET ",
173
+ "text_level": 1,
174
+ "page_idx": 4
175
+ },
176
+ {
177
+ "type": "text",
178
+ "text": "This is a small synthetic exercises dataset consisting of less than 180M tokens of Python exercises and solutions. Each exercise is a docstring of a function that needs to be completed. The goal of this dataset is to align the model to perform function completion tasks based on natural language instructions. This dataset was also generated by GPT-3.5, where the main means of eliciting diversity is by constraining the function names. For this dataset in particular, we conduct explicit decontamination and alternative evaluations in the following sections to ensure that problems similar to those from HumanEval benchmark are not seen during finetuning. Example exercise: ",
179
+ "page_idx": 4
180
+ },
181
+ {
182
+ "type": "image",
183
+ "img_path": "images/cc639997f694aed0368ec6d2c44f84e0be17de347438c4880f3e39d2a4c4b79e.jpg",
184
+ "image_caption": [],
185
+ "image_footnote": [],
186
+ "page_idx": 4
187
+ },
188
+ {
189
+ "type": "text",
190
+ "text": "3 SPIKES OF MODEL CAPABILITY AFTER FINETUNING ON CODEEXERCISES ",
191
+ "text_level": 1,
192
+ "page_idx": 4
193
+ },
194
+ {
195
+ "type": "text",
196
+ "text": "Figure 1 showed that the largest improvement in HumanEval resulted from finetuning on the small CodeExercises dataset $\\mathbf { \\chi } { < } 2 0 0 \\mathbf { M }$ tokens). CodeExercises consist exclusively of short Python tasks using only basic Python libraries. In this section, we demonstrate that, quite remarkably the model after finetuning also exhibits a substantial improvement in executing tasks that are not featured in the finetuning dataset. This includes managing intricate algorithmic tasks and using external libraries. This suggests that our finetuning process might have helped the model in reorganizing and consolidating the knowledge acquired during pretraining, even if such knowledge is not explicitly present in our CodeExercises dataset. In this section we will focus on qualitatively comparing and contrasting the capabilities of our finetuned model phi-1 and its pretrained base model phi-1-base. ",
197
+ "page_idx": 4
198
+ },
199
+ {
200
+ "type": "text",
201
+ "text": "3.1 FINETUNING IMPROVES THE MODEL’S UNDERSTANDING ",
202
+ "text_level": 1,
203
+ "page_idx": 5
204
+ },
205
+ {
206
+ "type": "text",
207
+ "text": "Using a simple Python function that we created ourselves, we observe in Figure 2 that the model shows a much higher level of understanding and compliance with instructions after finetuning. In particular, phi-1-base struggles with the logical relationships in the prompts, while phi-1 can interpret the question and generate the answer correctly. In this example, even our 350M phi-1-small model shows some level of understanding of the problem even though the final solution is wrong. ",
208
+ "page_idx": 5
209
+ },
210
+ {
211
+ "type": "image",
212
+ "img_path": "images/9762dd2e6610971bd23c8bffb6c8f188f907610286d228dbe07ce8dde9d87966.jpg",
213
+ "image_caption": [
214
+ "Figure 2: Model performance with a multi-step algorithmic prompt, comparing the effects of finetuning and scale. We see such trends consistently in our interactions, see Appendix A for another example. "
215
+ ],
216
+ "image_footnote": [],
217
+ "page_idx": 5
218
+ },
219
+ {
220
+ "type": "text",
221
+ "text": "3.2 FINETUNING IMPROVES THE MODEL’S ABILITY TO USE EXTERNAL LIBRARIES ",
222
+ "text_level": 1,
223
+ "page_idx": 5
224
+ },
225
+ {
226
+ "type": "text",
227
+ "text": "We demonstrate here that finetuning on CodeExercises unexpectedly improves the model’s ability to use external libraries such as Pygame, Tkinter, and pytorch, eventhough our exercises do not contain these libraries. This suggests that our finetuning not only improves the tasks we targeted, but also makes unrelated tasks easier to distill from pretraining. As an example, Figure 3 shows a PyGame example that asks the model to generate code to move a ball, where we see that phi-1 shows phenomenal improvement over phi-1-base model. See Appendix A for additional examples. ",
228
+ "page_idx": 5
229
+ },
230
+ {
231
+ "type": "text",
232
+ "text": "4 EVALUATION ON UNCONVENTIONAL PROBLEMS WITH LLM GRADING ",
233
+ "text_level": 1,
234
+ "page_idx": 5
235
+ },
236
+ {
237
+ "type": "text",
238
+ "text": "A potential concern with the surprisingly good performance of phi-1 on HumanEval (see Table 1 and Figure 1) is that there might be memorization stemming from contamination of the synthetic CodeExercises dataset. We study this potential contamination directly in Section 5, while this section addresses the concern with a new evaluation that is designed to be unconventional enough to be unlikely to appear in our training data. To minimize bias and leakage, the new evaluation problems were created by a dedicated team that did not access the CodeExercises dataset or the final model. They created 50 new problems in the format as HumanEval with instructions to design problems that are unlikely to appear in real-world code bases or as coding exercises. Here is an example: ",
239
+ "page_idx": 5
240
+ },
241
+ {
242
+ "type": "text",
243
+ "text": "Prompt: ",
244
+ "text_level": 1,
245
+ "page_idx": 6
246
+ },
247
+ {
248
+ "type": "text",
249
+ "text": "\"\"\" Write a PyGame. There is a ball. At every iteration, (1). The x-axis of the ball increases by a random integer between (-10, 10), (2). The y-axis of the ball increases by a random integer between (-20, 20). The x-axis of the ball should stay inside 0-400, and y-axis of the ball should stay inside 0-600. When the user press ’space’, set the $_ x$ -axis of the ball to 200 and y-axis of the ball to 400. \"\"\" ",
250
+ "page_idx": 6
251
+ },
252
+ {
253
+ "type": "text",
254
+ "text": "phi-1 ",
255
+ "text_level": 1,
256
+ "page_idx": 6
257
+ },
258
+ {
259
+ "type": "text",
260
+ "text": "phi-1-base ",
261
+ "text_level": 1,
262
+ "page_idx": 6
263
+ },
264
+ {
265
+ "type": "text",
266
+ "text": "phi-1-small ",
267
+ "text_level": 1,
268
+ "page_idx": 6
269
+ },
270
+ {
271
+ "type": "image",
272
+ "img_path": "images/b822403bc2f6f960d581b91a410bde4abfad11685edc2002f5e3f18e1b9ade10.jpg",
273
+ "image_caption": [
274
+ "Figure 3: The above code snippets show the main loop of a simple PyGame program that bounces a ball on the screen. We omit the code for initialization and boundary checking, which both models handle correctly. phi-1 correctly applies the PyGame functions as instructed by the prompt. We can see that phi-1-base shows some ability to use the appropriate API calls, but it fails to follow the logic of the task, while phi-1-small after finetuning understands the logic but does not have enough capacity to learn the correct function calls. "
275
+ ],
276
+ "image_footnote": [],
277
+ "page_idx": 6
278
+ },
279
+ {
280
+ "type": "text",
281
+ "text": "One of the challenges of evaluating language models on coding tasks is that the output of the model is often binary: either the code passes all the unit tests or it fails. However, this does not capture the nuances of the model’s performance, as it might have produced a code that is almost correct but has a minor error, or a code that is completely wrong but coincidentally passes some tests. Arguably, a more informative way of assessing the model’s coding skills is to compare its output with the correct solution and grade it based on how well it matches the expected logic. This is similar to how humans are evaluated on coding interviews, where the interviewer does not only run the code but also examines the reasoning and the quality of the solution. ",
282
+ "page_idx": 6
283
+ },
284
+ {
285
+ "type": "text",
286
+ "text": "To evaluate candidate solutions, we therefore adopt the approach of using GPT-4 to grade the solution (such as in Eldan & Li (2023)). This approach has two distinct advantages: (1) by using GPT-4 as a grader, we can leverage its knowledge and generative abilities to obtain a more fine-grained and meaningful signal of the student model’s coding capabilities, and (2) it obviates the need for tests3. Our prompt instructs the LLM to evaluate a student’s solution first in a short verbal evaluation followed by grades from 0 to 10. ",
287
+ "page_idx": 6
288
+ },
289
+ {
290
+ "type": "text",
291
+ "text": "See Table 2 for our results with phi-1 and competing models. The grades on our new unconventional problems give the same ranking as HumanEval (see Table 1). phi-1 again achieves a score significantly higher than StarCoder, as it did on HumanEval. Given that the new problems have had no chance to contaminate the training data and, furthermore, were designed to be outside the training distribution, these results greatly increase our confidence in the validity of phi-1’s performance. ",
292
+ "page_idx": 6
293
+ },
294
+ {
295
+ "type": "table",
296
+ "img_path": "images/3d7f67ad71fd52c684c071b92215ac7cac07354ba52f1db344146d66a4390a3b.jpg",
297
+ "table_caption": [
298
+ "Table 2: LLM graded Understanding scores on 50 new unconventional coding problems. "
299
+ ],
300
+ "table_footnote": [],
301
+ "table_body": "<table><tr><td>Model</td><td>Size</td><td>Train tokens</td><td>Score</td><td>HumanEval</td></tr><tr><td>CodeGen-Mono-350MNijkamp et al. (2023b)</td><td>350M</td><td>577B</td><td>19%</td><td>13%</td></tr><tr><td>CodeGen-Mono-16.1B Nijkamp et al. (2023b)</td><td>16.1B</td><td>577B</td><td>38%</td><td>29%</td></tr><tr><td>Replit Replit (2023)</td><td>2.7B</td><td>525B</td><td>37%</td><td>22%</td></tr><tr><td>StarCoder Li et al. (2023)</td><td>15.5B</td><td>1T</td><td>51%</td><td>34%</td></tr><tr><td>phi-1-base</td><td>1.3B</td><td>7B</td><td>37%</td><td>29%</td></tr><tr><td>phi-1-small</td><td>350M</td><td>7B</td><td>45%</td><td>45%</td></tr><tr><td>phi-1</td><td>1.3B</td><td>7B</td><td>52%</td><td>51%</td></tr></table>",
302
+ "page_idx": 7
303
+ },
304
+ {
305
+ "type": "text",
306
+ "text": "5 DATA PRUNING FOR UNBIASED PERFORMANCE EVALUATION ",
307
+ "text_level": 1,
308
+ "page_idx": 7
309
+ },
310
+ {
311
+ "type": "text",
312
+ "text": "In Figure 1, we see that training on CodeExercises leads to a substantial boost in the performance of the model on the HumanEval benchmark. To investigate this boost, we propose to prune the CodeExercises dataset by removing files that are “similar” to those in HumanEval. This process can be viewed as a “strong form” of data decontamination. We then retrain our model on such pruned data, and still observe strong performance on HumanEval. In particular, even after aggressively pruning more than $40 \\%$ of the CodeExercises dataset (this even prunes files that are only vaguely similar to HumanEval, see Appendix C), the retrained phi-1 still outperforms StarCoder. ",
313
+ "page_idx": 7
314
+ },
315
+ {
316
+ "type": "text",
317
+ "text": "We believe that such data pruning experiment is a fair way to evaluate performance, and is more insightful than standard “contamination” studies in the literature that are usually based on measures of overlap between training and test data (e.g., Section 4.8 of Austin et al. (2021)). For sake of completeness we start this section by conducting a standard contamination experiment, which shows that CodeExercises is not contaminated by HumanEval in this standard sense. ",
318
+ "page_idx": 7
319
+ },
320
+ {
321
+ "type": "text",
322
+ "text": "5.1 N-GRAM OVERLAP ",
323
+ "text_level": 1,
324
+ "page_idx": 7
325
+ },
326
+ {
327
+ "type": "text",
328
+ "text": "N-gram measures the similarity of text segments based on the shared n-word sequences. We calculate the n-gram overlap between the docstrings of each humaneval question and each exercise in the CodeExercises dataset that was generated. We found 4 humaneval questions with 13-gram overlap with at least one of the entries in our dataset. After further investigating, we found out that all the 4 overlap cases in the 13-gram are all false positives (see examples shown in Appendix C). ",
329
+ "page_idx": 7
330
+ },
331
+ {
332
+ "type": "text",
333
+ "text": "5.2 EMBEDDING AND SYNTAX-BASED SIMILARITY ANALYSIS ",
334
+ "text_level": 1,
335
+ "page_idx": 7
336
+ },
337
+ {
338
+ "type": "text",
339
+ "text": "As we just saw, the n-grams are not refined enough to find similar code snippets between HumanEval and CodeExercises. Instead we use a combination of embedding and syntax-based distances. For the embedding distance we compute the L2 distance between the embedding of the code snippets where the embedding is derived from a pre-trained CodeGen-Mono 350M model Nijkamp et al. (2023b). We observe that the embedding distance is successful in capturing code pairs where the overall code semantics are similar, which can be inferred via the Python Docstring, function/class names, as well as the code structure. For the syntax-based distance we calculate the (string) edit distance between the abstract syntax trees (ASTs) of two given code snippets. The AST distance successfully identifies overlapping sections between code pairs while being agnostic to non-syntax text such as variable/function naming, comments, and Python Docstrings. See Appendix C for examples of code pairs that are captured at various $\\tau$ and embedding distances. ",
340
+ "page_idx": 7
341
+ },
342
+ {
343
+ "type": "text",
344
+ "text": "For our pruning experiments on CodeExercises, we fix a threshold for the embedding distance, and we test several match rate $\\tau$ for the AST distance. We vary $\\tau$ between 0.95 and 0.8, which corresponds to $4 \\%$ to $40 \\%$ of problems in CodeExercises, respectively. Table 3 summarizes the performance of our retrained phi-1 on pruned datasets (with $\\tau = 0 . 9 5 , 0 . 9 , 0 . 8 5$ and 0.8) versus the original phi-1 trained on full CodeExercises and the $1 5 . 5 B$ -parameter StarCoder-prompted. We divide the HumanEval problems into two subsets (“similar” and “non-similar”) based on whether or not they have at least one close match (for this given $\\tau$ ) inside the original CodeExercises dataset. We then report the accuracy of the models on each subset of HumanEval separately. As one can see, even after heavily pruning our dataset, phi-1 still outperforms StarCoder-Prompted by a large margin, which validates that our performance boost is not due to dataset “contamination”, even when the latter term is understood loosely. ",
345
+ "page_idx": 7
346
+ },
347
+ {
348
+ "type": "table",
349
+ "img_path": "images/eae7a235ee0867853cc011cb5acf0953ef5eba448e943380844394697d3b0543.jpg",
350
+ "table_caption": [
351
+ "Table 3: Percentage of similar versus non-similar HumanEval problems correctly solved by different models. Similarity is determined based on whether or not the corresponding HumanEval problem has any close matches inside the CodeExercises dataset (for a given $\\tau$ ). The problem count denotes the number of HumanEval problems within each subset. Here, $\\tau$ is the threshold on AST-based match rate between codes for similarity check. "
352
+ ],
353
+ "table_footnote": [],
354
+ "table_body": "<table><tr><td>T</td><td></td><td>Problem</td><td>phi-1</td><td>phi-1 retrainaed</td><td>StarCetar. [202pted</td></tr><tr><td rowspan=\"3\">0.95</td><td>similar</td><td>71</td><td>81.7%</td><td>74.6%</td><td>57.7%</td></tr><tr><td>non-similar</td><td>93</td><td>26.9%</td><td>32.3%</td><td>29.0%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>50.6%</td><td>41.5%</td></tr><tr><td rowspan=\"3\">0.9</td><td>similar</td><td>93</td><td>63.4%</td><td>51.6%</td><td>48.4%</td></tr><tr><td>non-similar</td><td>71</td><td>33.8%</td><td>36.6%</td><td>32.4%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>45.1%</td><td>41.5%</td></tr><tr><td rowspan=\"3\">0.85</td><td>similar</td><td>106</td><td>62.3%</td><td>52.8%</td><td>47.2%</td></tr><tr><td>non-similar</td><td>58</td><td>29.3%</td><td>34.5%</td><td>31.0%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>46.3%</td><td>41.5%</td></tr><tr><td rowspan=\"3\">0.8</td><td>similar</td><td>116</td><td>59.5%</td><td>52.6%</td><td>45.7%</td></tr><tr><td>non-similar</td><td>48</td><td>29.2%</td><td>27.1%</td><td>31.2%</td></tr><tr><td>total</td><td>164</td><td>50.6%</td><td>45.1%</td><td>41.5%</td></tr></table>",
355
+ "page_idx": 8
356
+ },
357
+ {
358
+ "type": "text",
359
+ "text": "6 CONCLUSION ",
360
+ "text_level": 1,
361
+ "page_idx": 8
362
+ },
363
+ {
364
+ "type": "text",
365
+ "text": "Just as a comprehensive, well-crafted textbook can provide a student with the necessary knowledge to master a new subject, our work demonstrates the remarkable impact of high-quality data in honing a language model’s proficiency in code-generation tasks. By crafting “textbook quality” data we were able to train a model that surpasses almost all open-source models on coding benchmarks such as HumanEval and MBPP despite being $1 0 \\mathrm { x }$ smaller in model size and $1 0 0 \\mathrm { x }$ smaller in dataset size. We hypothesize that such high quality data dramatically improves the learning efficiency of language models for code as they provide clear, self-contained, instructive, and balanced examples. ",
366
+ "page_idx": 8
367
+ },
368
+ {
369
+ "type": "text",
370
+ "text": "There remains a number of limitations of our model compared to larger models for code. Firstly, phi1 is specialized in Python coding, which restricts its versatility compared to multi-language models. Secondly, phi-1 lacks the domain-specific knowledge of larger models such as programming with specific APIs or using less common packages. Lastly, due to the structured nature of the datasets and the lack of diversity in terms of language and style, phi-1 is less robust to stylistic variations or errors in the prompt (for instance, its performance substantially degrades with grammatical mistakes in the prompt). We expand on these limitations and other failure modes of phi-1 in Appendix B. ",
371
+ "page_idx": 8
372
+ },
373
+ {
374
+ "type": "text",
375
+ "text": "None of these limitations seem fundamental, and with more work our approach could be used to tackle each one of them, although it is unclear what scaling might be necessary to overcome them (both for the model size and the dataset size). We also believe that significant gains could be achieved by using GPT-4 to generate the synthetic data instead of GPT-3.5, as we noticed that GPT-3.5 data has a high error rate. It is interesting that phi-1 is able to achieve such high coding proficiency despite those errors (a similar phenomenon was observed in Allen-Zhu & Li (2023) where a language model can be trained on data with $100 \\%$ error rate and still generate correct answers at test time). ",
376
+ "page_idx": 8
377
+ },
378
+ {
379
+ "type": "text",
380
+ "text": "More generally, our work provides evidence that developing good methodology for creating highquality datasets is a central direction of research for advancing natural language processing and related fields (see also Jung et al. (2023) for further evidence). However, creating high-quality datasets is not a trivial task, and it poses several challenges that need to be addressed. One challenge is to ensure that the dataset covers all the relevant content and concepts that one wants the model to learn, and that it does so in a balanced and representative way. Another challenge is to ensure that the dataset is truly diverse and non-repetitive, so that the model does not simply overfit to the data or memorize specific patterns or solutions. This requires finding ways to inject randomness and creativity into the data generation process, while still maintaining the quality and the coherence of the examples. Moreover, even after creating such datasets, we lack a good methodology to measure and evaluate the amount of diversity and redundancy in the data. For example, if we have a dataset with coding exercises, it is hard to determine how many different variations of each exercise exist, and how they are distributed across the dataset. Finally, as language models themselves will be used to curate data for future language models, it further increases the urgency on the ethical and social implications of training such models, such as the accountability, the transparency, and the bias of the data and the models that are involved in this process. ",
381
+ "page_idx": 8
382
+ },
383
+ {
384
+ "type": "text",
385
+ "text": "REFERENCES \nLoubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, et al. Santacoder: don’t reach for the stars! arXiv preprint arXiv:2301.03988, 2023. \nZeyuan Allen-Zhu and Yuanzhi Li. Physics of language models: Part 1, context-free grammar. arXiv preprint arXiv:2305.13673, 2023. \nRohan Anil, Andrew M Dai, Orhan Firat, Melvin Johnson, Dmitry Lepikhin, Alexandre Passos, Siamak Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng Chen, et al. Palm 2 technical report. arXiv preprint arXiv:2305.10403, 2023. \nJacob Austin, Augustus Odena, Maxwell Nye, Maarten Bosma, Henryk Michalewski, David Dohan, Ellen Jiang, Carrie Cai, Michael Terry, Quoc Le, et al. Program synthesis with large language models. arXiv preprint arXiv:2108.07732, 2021. \nMohammad Bavarian, Heewoo Jun, Nikolas Tezak, John Schulman, Christine McLeavey, Jerry Tworek, and Mark Chen. Efficient training of language models to fill in the middle. arXiv preprint arXiv:2207.14255, 2022. \nEmily M Bender, Timnit Gebru, Angelina McMillan-Major, and Shmargaret Shmitchell. On the dangers of stochastic parrots: Can language models be too big? In Proceedings of the 2021 ACM Conference on Fairness, Accountability, and Transparency, pp. 610–623, 2021. \nSid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, and Samuel Weinbach. GPTNeoX-20B: An open-source autoregressive language model. In Proceedings of the ACL Workshop on Challenges & Perspectives in Creating Large Language Models, 2022. URL https: //arxiv.org/abs/2204.06745. \nTom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel Ziegler, Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. Language models are few-shot learners. In Advances in Neural Information Processing Systems, volume 33, pp. 1877–1901, 2020. \nSebastien Bubeck, Varun Chandrasekaran, Ronen Eldan, Johannes Gehrke, Eric Horvitz, Ece Ka-´ mar, Peter Lee, Yin Tat Lee, Yuanzhi Li, Scott Lundberg, et al. Sparks of artificial general intelligence: Early experiments with gpt-4. arXiv preprint arXiv:2303.12712, 2023. \nMark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, et al. Evaluating large language models trained on code. arXiv preprint arXiv:2107.03374, 2021. \nAakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311, 2022. \nTri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Re. Flashattention: Fast and memory- ´ efficient exact attention with io-awareness. Advances in Neural Information Processing Systems, 35:16344–16359, 2022. \nYann Dubois, Xuechen Li, Rohan Taori, Tianyi Zhang, Ishaan Gulrajani, Jimmy Ba, Carlos Guestrin, Percy Liang, and Tatsunori B Hashimoto. Alpacafarm: A simulation framework for methods that learn from human feedback. arXiv preprint arXiv:2305.14387, 2023. \nRonen Eldan and Yuanzhi Li. Tinystories: How small can language models be and still speak coherent english? arXiv preprint arXiv:2305.07759, 2023. \nArnav Gudibande, Eric Wallace, Charlie Snell, Xinyang Geng, Hao Liu, Pieter Abbeel, Sergey Levine, and Dawn Song. The false promise of imitating proprietary llms. arXiv preprint arXiv:2305.15717, 2023. \nJoel Hestness, Sharan Narang, Newsha Ardalani, Gregory Diamos, Heewoo Jun, Hassan Kianinejad, Md Mostofa Ali Patwary, Yang Yang, and Yanqi Zhou. Deep learning scaling is predictable, empirically. arXiv preprint arXiv:1712.00409, 2017. \nJordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, Tom Hennigan, Eric Noland, Katherine Millican, George van den Driessche, Bogdan Damoc, Aurelia Guy, Simon Osindero, Karen Simonyan, Erich Elsen, Oriol Vinyals, Jack William Rae, and Laurent Sifre. An empirical analysis of compute-optimal large language model training. In Alice H. Oh, Alekh Agarwal, Danielle Belgrave, and Kyunghyun Cho (eds.), Advances in Neural Information Processing Systems, 2022. \nJaehun Jung, Peter West, Liwei Jiang, Faeze Brahman, Ximing Lu, Jillian Fisher, Taylor Sorensen, and Yejin Choi. Impossible distillation: from low-quality model to high-quality dataset & model for summarization and paraphrasing. arXiv preprint arXiv:2305.16635, 2023. \nJared 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. arXiv preprint arXiv:2001.08361, 2020. \nDenis Kocetkov, Raymond Li, Loubna Ben Allal, Jia Li, Chenghao Mou, Carlos Munoz Ferran-˜ dis, Yacine Jernite, Margaret Mitchell, Sean Hughes, Thomas Wolf, et al. The stack: 3 tb of permissively licensed source code. arXiv preprint arXiv:2211.15533, 2022. \nAitor Lewkowycz, Anders Andreassen, David Dohan, Ethan Dyer, Henryk Michalewski, Vinay Ramasesh, Ambrose Slone, Cem Anil, Imanol Schlag, Theo Gutman-Solo, Yuhuai Wu, Behnam Neyshabur, Guy Gur-Ari, and Vedant Misra. Solving quantitative reasoning problems with language models. In S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh (eds.), Advances in Neural Information Processing Systems, volume 35, pp. 3843–3857. Curran Associates, Inc., 2022. URL https://proceedings.neurips.cc/paper_files/paper/2022/ file/18abbeef8cfe9203fdf9053c9c4fe191-Paper-Conference.pdf. \nRaymond Li, Loubna Ben Allal, Yangtian Zi, Niklas Muennighoff, Denis Kocetkov, Chenghao Mou, Marc Marone, Christopher Akiki, Jia Li, Jenny Chim, et al. Starcoder: may the source be with you! arXiv preprint arXiv:2305.06161, 2023. \nZinan Lin, Sivakanth Gopi, Janardhan Kulkarni, Harsha Nori, and Sergey Yekhanin. Differentially private synthetic data via foundation model apis 1: Images. arXiv preprint arXiv:2305.15560, 2023. \nJiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and Lingming Zhang. Is your code generated by chatgpt really correct? rigorous evaluation of large language models for code generation. arXiv preprint arXiv:2305.01210, 2023. \nShayne Longpre, Gregory Yauney, Emily Reif, Katherine Lee, Adam Roberts, Barret Zoph, Denny Zhou, Jason Wei, Kevin Robinson, David Mimno, et al. A pretrainer’s guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity. arXiv preprint arXiv:2305.13169, 2023. \nZiyang Luo, Can Xu, Pu Zhao, Qingfeng Sun, Xiubo Geng, Wenxiang Hu, Chongyang Tao, Jing Ma, Qingwei Lin, and Daxin Jiang. Wizardcoder: Empowering code large language models with evol-instruct, 2023. \nNiklas Muennighoff, Alexander M Rush, Boaz Barak, Teven Le Scao, Aleksandra Piktus, Nouamane Tazi, Sampo Pyysalo, Thomas Wolf, and Colin Raffel. Scaling data-constrained language models. arXiv preprint arXiv:2305.16264, 2023. \nSubhabrata Mukherjee, Arindam Mitra, Ganesh Jawahar, Sahaj Agarwal, Hamid Palangi, and Ahmed Awadallah. Orca: Progressive learning from complex explanation traces of gpt-4. arXiv preprint arXiv:2306.02707, 2023. \nErik 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. arXiv preprint, 2022. \nErik Nijkamp, Hiroaki Hayashi, Caiming Xiong, Silvio Savarese, and Yingbo Zhou. Codegen2: Lessons for training llms on programming and natural languages. arXiv preprint arXiv:2305.02309, 2023a. \nErik 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, 2023b. \nOpenAI. Gpt-4 technical report, 2023. arXiv preprint arXiv:2303.08774 [cs.CL]. \nColin 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. The Journal of Machine Learning Research, 21(1):5485–5551, 2020. \nReplit. Replit dev day. https://twitter.com/Replit/status/ 1651344184593506304, 2023. \nIlia Shumailov, Zakhar Shumaylov, Yiren Zhao, Yarin Gal, Nicolas Papernot, and Ross Anderson. Model dementia: Generated data makes models forget. arXiv preprint arXiv:2305.17493, 2023. \nJianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. arXiv preprint arXiv:2104.09864, 2021. \nRohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, and Tatsunori B. Hashimoto. Stanford alpaca: An instruction-following llama model. https://github.com/tatsu-lab/stanford_alpaca, 2023. \nAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Ł ukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems, volume 30, 2017. \nYizhong Wang, Yeganeh Kordi, Swaroop Mishra, Alisa Liu, Noah A Smith, Daniel Khashabi, and Hannaneh Hajishirzi. Self-instruct: Aligning language model with self generated instructions. arXiv preprint arXiv:2212.10560, 2022. \nYue Wang, Hung Le, Akhilesh Deepak Gotmare, Nghi DQ Bui, Junnan Li, and Steven CH Hoi. Codet5+: Open code large language models for code understanding and generation. arXiv preprint arXiv:2305.07922, 2023. \nJason Wei, Yi Tay, Rishi Bommasani, Colin Raffel, Barret Zoph, Sebastian Borgeaud, Dani Yogatama, Maarten Bosma, Denny Zhou, Donald Metzler, Ed H. Chi, Tatsunori Hashimoto, Oriol Vinyals, Percy Liang, Jeff Dean, and William Fedus. Emergent abilities of large language models. Transactions on Machine Learning Research, 2022. Survey Certification. \nDa Yu, Sivakanth Gopi, Janardhan Kulkarni, Zinan Lin, Saurabh Naik, Tomasz Lukasz Religa, Jian Yin, and Huishuai Zhang. Selective pre-training for private fine-tuning. arXiv preprint arXiv:2305.13865, 2023. \nQinkai Zheng, Xiao Xia, Xu Zou, Yuxiao Dong, Shan Wang, Yufei Xue, Zihan Wang, Lei Shen, Andi Wang, Yang Li, Teng Su, Zhilin Yang, and Jie Tang. Codegeex: A pre-trained model for code generation with multilingual evaluations on humaneval-x, 2023. ",
386
+ "page_idx": 9
387
+ },
388
+ {
389
+ "type": "text",
390
+ "text": "",
391
+ "page_idx": 10
392
+ },
393
+ {
394
+ "type": "text",
395
+ "text": "",
396
+ "page_idx": 11
397
+ },
398
+ {
399
+ "type": "text",
400
+ "text": "A ADDITIONAL EXAMPLES FOR SECTION 3 ",
401
+ "text_level": 1,
402
+ "page_idx": 12
403
+ },
404
+ {
405
+ "type": "text",
406
+ "text": "In Section 3, we discussed with a couple examples on how finetuned modes shows a substantial improvement over the base model in executing tasks that are not featured in the finetuning dataset. Here we provide additional examples and details to further illustrate improvements in the areas of model understanding in managing intricate algorithmic tasks and using external libraries. ",
407
+ "page_idx": 12
408
+ },
409
+ {
410
+ "type": "text",
411
+ "text": "A.1 FINETUNING IMPROVES THE MODEL’S UNDERSTANDING ABILITY ",
412
+ "text_level": 1,
413
+ "page_idx": 12
414
+ },
415
+ {
416
+ "type": "text",
417
+ "text": "The example below is challenging due to the prevalence of various logical operators such as “and” and “not” that link numerous statements. Prior to finetuning, the model is confused by the logic embedded in the statement. It struggles to differentiate between “elements” and “indices”, and is unsure about which array to use. Conversely, the finetuned model is adept at accurately identifying all relevant arrays and indices, while correctly implementing the logical operators. ",
418
+ "page_idx": 12
419
+ },
420
+ {
421
+ "type": "text",
422
+ "text": "Prompt: ",
423
+ "text_level": 1,
424
+ "page_idx": 12
425
+ },
426
+ {
427
+ "type": "text",
428
+ "text": "\"\"\" Input is an array A, an array B, an array C, an array E, a numpy matrix D. I want to find all the indices of D whose elements are in the union of B and C and whose row index is not in A and column index is in D. Loop through the elements in D. Return the list of indices. \"\"\" ",
429
+ "page_idx": 12
430
+ },
431
+ {
432
+ "type": "text",
433
+ "text": "phi-1 ",
434
+ "text_level": 1,
435
+ "page_idx": 12
436
+ },
437
+ {
438
+ "type": "text",
439
+ "text": "indices = [] \nfor i in range(D.shape[0]): for j in range(D.shape [1]): if D[i][j] in B or D [i][j] in C: if i not in A and j in D: indices. append((i,j)) \nreturn indices ",
440
+ "page_idx": 12
441
+ },
442
+ {
443
+ "type": "text",
444
+ "text": "phi-1-base ",
445
+ "text_level": 1,
446
+ "page_idx": 12
447
+ },
448
+ {
449
+ "type": "text",
450
+ "text": "phi-1-small ",
451
+ "text_level": 1,
452
+ "page_idx": 12
453
+ },
454
+ {
455
+ "type": "text",
456
+ "text": "indices = [] \nfor i in range(len(D)): for j in range(len(D[i]) ): if D[i][j] in B and D[i][j] not in A: indices.append(j ) \nreturn indices \nindices = [] \nfor i in range(D.shape[1]): if D[0][i] in B and D [0][i] not in A and D[i ][0] in C and D[i][0] not in E: indices.append(i) \nreturn indices ",
457
+ "page_idx": 12
458
+ },
459
+ {
460
+ "type": "text",
461
+ "text": "",
462
+ "page_idx": 12
463
+ },
464
+ {
465
+ "type": "text",
466
+ "text": "A.2 FINETUNING IMPROVES THE MODEL’S ABILITY TO USE EXTERNAL LIBRARIES ",
467
+ "text_level": 1,
468
+ "page_idx": 12
469
+ },
470
+ {
471
+ "type": "text",
472
+ "text": "In Section 3, we demonstrate with an example prompt using PyGame library that our finetuned phi1 model remarkably improves over phi-1-base even though our finetuning CodeExercises does not contain examples involving PyGame packages. For reference, Figure 4 shows the distribution of package imports in our CodeExercises dataset. ",
473
+ "page_idx": 12
474
+ },
475
+ {
476
+ "type": "image",
477
+ "img_path": "images/875c455fe828a359404a5503156891b6ec52c389b0eb93689ecb8708e731f563.jpg",
478
+ "image_caption": [
479
+ "Figure 4: The number of imports among 879486 exercises in the finetuning (ignored libraries imported ${ < } 1 0$ times). The plot itself is generated by phi-1 from dictionary of imports with the prompt: “I have a dictionary, first sort the dictionary using the value, from largest to smallest. Then generate a pyplot bar plot. First set font size to be 7, then rotate the x-axis label by 90 degree, the $\\mathbf { X } ^ { }$ -axis is the key, y-axis is the value of the dictionary. Use log-scale on y-axis. Moreover, set the y-axis label to be ‘Log Number of Times’ and $\\mathbf { X }$ -axis label to be ‘Imports’. Set dpi to be 1000.” "
480
+ ],
481
+ "image_footnote": [],
482
+ "page_idx": 12
483
+ },
484
+ {
485
+ "type": "text",
486
+ "text": "In the following, we provide additional examples to show how our finetuning with CodeExercises dataset unexpectedly improves the model’s ability to use external libraries such as Tkinter, pyplot, and pytorch, eventhough our exercises do not contain these libraries. ",
487
+ "page_idx": 12
488
+ },
489
+ {
490
+ "type": "text",
491
+ "text": "TKinter example. Our second example is a TKinter application where we ask the model to update a textfield accordingly when the user clicks buttons. ",
492
+ "page_idx": 13
493
+ },
494
+ {
495
+ "type": "text",
496
+ "text": "Prompt: ",
497
+ "text_level": 1,
498
+ "page_idx": 13
499
+ },
500
+ {
501
+ "type": "text",
502
+ "text": "\"\"\" Write a tkinter application, there is a textfield on top, a submit button at the button and a recover button next to it. When pressing the submit button, get the text from the textfield and save it to a global string s. If the text contains the word \"pew\" update the textfield text to \"pewpewpew?\", otherwise, add \"no pew...\" to the end. When pressing the recover button, replace the text in the textfield with s. \n\"\"\" ",
503
+ "page_idx": 13
504
+ },
505
+ {
506
+ "type": "text",
507
+ "text": "phi-1 ",
508
+ "text_level": 1,
509
+ "page_idx": 13
510
+ },
511
+ {
512
+ "type": "text",
513
+ "text": "global s \ns = \"\" \ndef submit(): global s text $=$ textfield.get() if \"pew\" in text: textfield.delete(0, tk.END) textfield.insert(0, \"pewpewpew. ) else: textfield.delete(0, tk.END) textfield.insert(0, text $^ +$ \"no pew \") s $=$ text \ndef recover(): global s textfield.delete(0, tk.END) textfield.insert(0, s) \ntextfield $=$ tk.Entry(root) \ntextfield.pack() \nsubmit_button $=$ tk.Button(root, text=\" Submit\", command=submit) \nsubmit_button.pack() \nrecover_button $=$ tk.Button(root, text=\" Recover\", command=recover) \nrecover_button.pack() \nroot.mainloop() ",
514
+ "page_idx": 13
515
+ },
516
+ {
517
+ "type": "text",
518
+ "text": "phi-1-base ",
519
+ "text_level": 1,
520
+ "page_idx": 13
521
+ },
522
+ {
523
+ "type": "text",
524
+ "text": "global s \ns $=$ s.replace(\"pew\", \"pewpewpew\") \nif \"pew\" in s: s $=$ s.replace(\"pew\", \"pewpewpew\") \nelse: s = s + \"no pew.. 1 \ntext.delete(0.0, END) \ntext.insert(0.0, s) \ndef main(): global s s $=$ \"pewpewpew\" text.delete(0.0, END) text.insert(0.0, s) text.tag_add(\"button\", \"<Button-1>\", \"< Button-3>\") text.tag_add(\"button\", \"<Button-2>\", \"< Button-4>\") # The model keeps adding buttons from here. ",
525
+ "page_idx": 13
526
+ },
527
+ {
528
+ "type": "text",
529
+ "text": "phi-1-small ",
530
+ "text_level": 1,
531
+ "page_idx": 13
532
+ },
533
+ {
534
+ "type": "text",
535
+ "text": "import tkinter as tk \nroot $=$ tk.Tk() \nglobal s \ntext = \"\" \nwhile True: event, values $=$ tk.popup() if event $= =$ \"submit\": text $+ =$ values.split()[0] + \" 1 elif event $= =$ \"textfield\": s $+ =$ values.split()[0] $^ +$ \" \" elif event $= =$ \"submit-button-text\": text $=$ values.split()[0] $^ +$ \" \" elif event $= =$ \"text-button-text\": s $=$ text if \"pew\" in text: text $=$ text.replace(\"pew\", \"pewpewpew\") if \"no pew\" in text: break \ntk.destroy() ",
536
+ "page_idx": 13
537
+ },
538
+ {
539
+ "type": "text",
540
+ "text": "The three models’ completions show a huge gap in their prompt understanding. Both phi-1-base and phi-1-small fail to use the correct Tkinter APIs and make up meaningless function calls. On the other hand, phi-1 implements the GUI and all the functions correctly (except that it did not copy “pewpewpew?” correctly). ",
541
+ "page_idx": 13
542
+ },
543
+ {
544
+ "type": "text",
545
+ "text": "Chat mode example. Finally, we show that phi-1 has a better chat capability than phi-1-base despite that chat data is exclusive in pretraining, but not in the finetuning. ",
546
+ "page_idx": 14
547
+ },
548
+ {
549
+ "type": "text",
550
+ "text": "Prompt: ",
551
+ "text_level": 1,
552
+ "page_idx": 14
553
+ },
554
+ {
555
+ "type": "text",
556
+ "text": "Student: I have a Python pyplot, and rotate it, what should I do? phi-1 ",
557
+ "page_idx": 14
558
+ },
559
+ {
560
+ "type": "text",
561
+ "text": "I want to increase its resolution TA: ",
562
+ "page_idx": 14
563
+ },
564
+ {
565
+ "type": "text",
566
+ "text": "phi-1-base ",
567
+ "text_level": 1,
568
+ "page_idx": 14
569
+ },
570
+ {
571
+ "type": "text",
572
+ "text": "1. Set the 'dpi' parameter to the desired \nresolution (e.g. 300 for 300 DPI) \n2. Use the 'rotate' function from the ' \nmatplotlib.pyplot' module to rotate the plot \nby 90 degrees clockwise \nHere's an example: \nimport matplotlib.pyplot as plt \nfig, ax $=$ plt.subplots() \nax.plot([1, 2, 3], [4, 5, 6]) \n# Set the resolution to 300 DPI \nax.set_dpi(300) \n# Rotate the plot by 90 degrees clockwise \nax.rotate(90) ",
573
+ "page_idx": 14
574
+ },
575
+ {
576
+ "type": "text",
577
+ "text": "You can use the \\`setp()\\` function to set the resolution and the \\`set_rotation()\\` function to rotate the plot. <|endoftext|> ",
578
+ "page_idx": 14
579
+ },
580
+ {
581
+ "type": "text",
582
+ "text": "phi-1-small ",
583
+ "text_level": 1,
584
+ "page_idx": 14
585
+ },
586
+ {
587
+ "type": "text",
588
+ "text": "I am a Python pyplot, and I want to increase its resolution and rotate it, what should I do? \nSECOND: \nI am a Python pyplot, and I want to increase its resolution and rotate it, what should I do? \nTHIRD:... ",
589
+ "page_idx": 14
590
+ },
591
+ {
592
+ "type": "text",
593
+ "text": "Pytorch example. In this PyTorch example, we ask the model to write a modified gradient update: ",
594
+ "page_idx": 14
595
+ },
596
+ {
597
+ "type": "text",
598
+ "text": "Prompt: ",
599
+ "text_level": 1,
600
+ "page_idx": 14
601
+ },
602
+ {
603
+ "type": "text",
604
+ "text": "\"\"\" Write a pytorch function. The input is a model, take the gradient of each parameter of the model, do an SVD of each gradient to get U, Sigma, V, take the top k singular values of Sigma as Sigmak, then do a update step to the parameter using Uk $\\star$ Sigmak $\\star \\mathrm { V k }$ times the norm of the parameter. ",
605
+ "page_idx": 14
606
+ },
607
+ {
608
+ "type": "text",
609
+ "text": "",
610
+ "page_idx": 14
611
+ },
612
+ {
613
+ "type": "text",
614
+ "text": "phi-1 ",
615
+ "text_level": 1,
616
+ "page_idx": 14
617
+ },
618
+ {
619
+ "type": "text",
620
+ "text": "phi-1-base ",
621
+ "text_level": 1,
622
+ "page_idx": 14
623
+ },
624
+ {
625
+ "type": "text",
626
+ "text": "phi-1-small ",
627
+ "text_level": 1,
628
+ "page_idx": 14
629
+ },
630
+ {
631
+ "type": "text",
632
+ "text": "for p in model.parameters(): if p.grad is not None: U, Sigma, $\\mathrm { ~ v ~ } = \\mathrm { ~ p ~ }$ .grad.svd() Sigmak $=$ Sigma[:k].diag() p.data.add_(torch.mm(U[:,: k], torch.mm(Sigmak, $\\mathbb { V } \\left[ : \\mathbb { k } , : \\right]$ ) ). $\\mathtt { \\cdot m u l \\_ m o r m } )$ ) ",
633
+ "page_idx": 14
634
+ },
635
+ {
636
+ "type": "text",
637
+ "text": "self.model $=$ model \nself.k $\\mathit { \\Theta } = \\mathit { \\Theta } \\mathrm { \\ l } \\mathit { \\Theta }$ \nself.eps $=$ eps \nself.max_iter $=$ \nmax_iter \nself.verbose $=$ \nverbose \nself.svd_u $=$ None \nself.svd_sigma $=$ None self.svd_v $=$ None \nself.svd_k $=$ None \nself.svd_u_k $=$ None self.svd_sigma_k $=$ \nNone \nself.svd_v_k $=$ None ... \ndef svd(x): u, s, v = np.linalg.svd(x) return u, s, v \ndef update_parameter(parameter, grad): u, s, $\\qquad \\lor \\quad =$ svd(grad) parameter $=$ u[:, :k] np.diag(s[:k]) v[:k, :] parameter $+ =$ np.diag(sigmoid (parameter)) return parameter ",
638
+ "page_idx": 14
639
+ },
640
+ {
641
+ "type": "text",
642
+ "text": "",
643
+ "page_idx": 14
644
+ },
645
+ {
646
+ "type": "text",
647
+ "text": "The code by phi-1-small reveals a lack of understanding of the prompt, leading to multiple significant missteps. First, it uses np.linalg.svd $\\mathbf { \\tau } ( \\mathbf { x } )$ , which is incompatible with PyTorch tensors. Second, it erroneously assigns the SVD result directly to the parameter, deviating from the prompt’s instruction to add it. On the other hand, phi-1-base is completely clueless and only produces a sequence of meaningless definitions. This indicates that improving the model’s logical reasoning ability (even only on simple functions) can greatly enhance the model’s general coding ability. ",
648
+ "page_idx": 14
649
+ },
650
+ {
651
+ "type": "text",
652
+ "text": "Pyplot example. The final API example is a Pyplot application. The model is generally good with Pyplot, so we design a challenging task to ask the model implement an animation. ",
653
+ "page_idx": 15
654
+ },
655
+ {
656
+ "type": "text",
657
+ "text": "Prompt: ",
658
+ "text_level": 1,
659
+ "page_idx": 15
660
+ },
661
+ {
662
+ "type": "text",
663
+ "text": "\"\"\"Create an x array that are integers from 1 to 20, y array that is equal to the elementwise cos of $_ \\textrm { x }$ divided by element-wise sqrt(x + 1). Write a Python code of line plot that animates the change of y according to x \\*\\*\\*step by step\\*\\*\\* with red lines. However, during the animation, when x[i] is larger than 11, change the animation line color from red to green. \n\"\"\" ",
664
+ "page_idx": 15
665
+ },
666
+ {
667
+ "type": "text",
668
+ "text": "phi-1 ",
669
+ "text_level": 1,
670
+ "page_idx": 15
671
+ },
672
+ {
673
+ "type": "text",
674
+ "text": "phi-1-base ",
675
+ "text_level": 1,
676
+ "page_idx": 15
677
+ },
678
+ {
679
+ "type": "text",
680
+ "text": "phi-1-small ",
681
+ "text_level": 1,
682
+ "page_idx": 15
683
+ },
684
+ {
685
+ "type": "text",
686
+ "text": "... ... ... \n$\\textrm { \\scriptsize x } =$ np.arange(1, 21) fig, ax $=$ plt.subplots() fig, ax $=$ plt.subplots() \ny $=$ np.cos(x) / np.sqrt( $\\mathrm { ~ ~ { ~ x ~ } ~ } + \\mathrm { ~ ~ { ~ 1 ~ } ~ }$ ) $\\textrm { \\textbf { x } } =$ np.arange(1, 21) x_array $=$ list(range(1, 21) \nfig, ax $=$ plt.subplots() $\\begin{array} { r l } { \\mathrm { y } } & { { } = } \\end{array}$ np.cos(x) / np.sqrt(x + ) \nline, $=$ ax.plot([], [], color= 1) y_array $=$ [math.cos(xi/10) 'red') line, $=$ ax.plot([], [], lw for xi in x_array] $^ { = 2 }$ ) def animate(i): \nax.set_title('Animation of def init(): ... Cosine and Cosine-Square line.set_data([], []) ax.plot(x_array, Root') return line, y_array) \ndef animate(i): def animate(i): if x_array[i] > 11: $\\mathrm { i f ~ \\ x [ \\mathrm { i } ] ~ > ~ \\mathrm { 1 1 } }$ : $\\mathrm { i f ~ \\ x [ \\mathrm { i } ] ~ > ~ \\mathrm { 1 1 } }$ : color $=$ \"red\" line.set_color('green' line.set_color(' else: ) green') color $=$ \"green\" else: else: ax.scatter(x_array[i], line.set_color('red') line.set_color('red y_array[i], color=color line.set_data(x[:i+1], y[: ') ) $\\dot { 1 } + 1 1$ ) return line, return ax return line, anim $=$ FuncAnimation(fig, ani $=$ animation. \nanim $=$ animation.FuncAnimation animate, init_func $\\mathbf { \\equiv } = \\mathbf { \\Phi } _ { \\mathrm { - } }$ init FuncAnimation(fig, (fig, animate, frames=len , frames=len(x), animate, frames=len( $( \\times )$ , interval=500, blit= interval $= 5 0$ , blit=True) x_array), interval=50, True) blit=True) \nplt.show() plt.show() ",
687
+ "page_idx": 15
688
+ },
689
+ {
690
+ "type": "text",
691
+ "text": "phi-1-small produces a very incorrect completion. From the API perspective, the model fails to understand the “line plot” requirement and only uses a scatter plot (and even that is implemented wrongly). phi-1-base gets the template correct, but misses the core function to update the line plot every iteration. ",
692
+ "page_idx": 15
693
+ },
694
+ {
695
+ "type": "text",
696
+ "text": "B LIMITATION OF PHI-1 ",
697
+ "text_level": 1,
698
+ "page_idx": 15
699
+ },
700
+ {
701
+ "type": "text",
702
+ "text": "While finetuning through simple exercises significantly enhances the model’s overall performance, there are certain constraints intrinsic to our model that cannot be overcome solely by finetuning. Firstly, our model has only 1.3B parameters trained with only 7B tokens, this restricts our model’s capacity to manage more complex tasks such as developing an intricate Flask application, in comparison to other models like Starcoder. Beyond our model’s limitations in terms of generality when contrasted with StarCoder or ChatGPT, we’ve also outlined several other weaknesses as follows: ",
703
+ "page_idx": 15
704
+ },
705
+ {
706
+ "type": "text",
707
+ "text": "Sensitivity to prompt variations. Our model is sensitive to various perturbations of prompts. First, its performance drops significantly as the length of the prompt increases, as it tends to ignore, forget or misinterpret parts of the prompt when it is too long. For example, our model fails when we increase the number of layers from 3 to 4 in the following case. We hypothesize that this issue arises because our exercises predominantly consist of short prompts. Furthermore, its generation may appear qualitatively different with a slightly modified prompt. In this case, with an additional import torch command, the model tends to succeed on the very task that it failed previously. ",
708
+ "page_idx": 15
709
+ },
710
+ {
711
+ "type": "text",
712
+ "text": "Prompt: ",
713
+ "text_level": 1,
714
+ "page_idx": 16
715
+ },
716
+ {
717
+ "type": "text",
718
+ "text": "\"\"\" Create a neural \nnetwork class in Pytorch with 3 layers. Implement a new \"rr\" method to this new function: It takes \ninput x. Apply the first layer on $_ x$ and assign the output to y, then apply \nthe second layer on $_ y$ and assign the output to $_ z$ , \nthen apply the third layer on $_ z$ and assign it to $_ w$ , then sum up $y , z , w$ and \nassign it to $Q$ . Return $Q$ . \n\"\"\" ",
719
+ "page_idx": 16
720
+ },
721
+ {
722
+ "type": "text",
723
+ "text": "Prompt: ",
724
+ "text_level": 1,
725
+ "page_idx": 16
726
+ },
727
+ {
728
+ "type": "text",
729
+ "text": "\"\"\" Create a neural network class in Pytorch with 4 layers. Implement a new \"rr\" method to this new function: It takes input x. Apply the first layer on $_ x$ and assign the output to y, then apply the second layer on $_ y$ and assign the output to $_ z$ , then apply the third layer on $_ z$ and assign it to $_ w$ , then apply the forth layer on w and assign $\\mathrm { i t } \\ t \\circ \\ p$ , then sum up $y , z , w , p$ and assign it to $Q$ . Return $Q$ . ",
730
+ "page_idx": 16
731
+ },
732
+ {
733
+ "type": "text",
734
+ "text": "\"\"\" ",
735
+ "text_level": 1,
736
+ "page_idx": 16
737
+ },
738
+ {
739
+ "type": "text",
740
+ "text": "Prompt: ",
741
+ "text_level": 1,
742
+ "page_idx": 16
743
+ },
744
+ {
745
+ "type": "text",
746
+ "text": "import torch",
747
+ "text_level": 1,
748
+ "page_idx": 16
749
+ },
750
+ {
751
+ "type": "text",
752
+ "text": "\"\"\" Create a neural network class in Pytorch with 4 layers. Implement a new \"rr\" method to this new function: It takes input x. Apply the first layer on x and assign the output to $_ y$ , then apply the second layer on $_ y$ and assign the output to $_ z$ , then apply the third layer on $_ z$ and assign it to $_ w$ , then apply the forth layer on w and assign it to p, then sum up $y , z , w , p$ and assign it to $Q$ . Return $Q$ . \"\"\" ",
753
+ "page_idx": 16
754
+ },
755
+ {
756
+ "type": "text",
757
+ "text": "class NeuralNetwork(nn. Module): def _init__(self): super( NeuralNetwork, self). _init__() self.layer1 $\\begin{array} { r l } { = } & { { } \\ \\Pi \\Pi } \\end{array}$ . Linear(2, 5) self.layer2 $\\begin{array} { r l } { = } & { { } \\ \\Pi \\Pi } \\end{array}$ . Linear(5, 3) self.layer3 $\\begin{array} { r l } { = } & { { } \\ \\Pi \\Pi } \\end{array}$ . Linear(3, 1) def rr(self, x): $\\begin{array} { r l } { \\mathrm { y } } & { { } = } \\end{array}$ self.layer1(x) $z =$ self.layer2(y) $\\begin{array} { r l } { \\mathbf { \\nabla } \\warrow } & { { } = } \\end{array}$ self.layer3(z) $\\mathrm { ~ ~ Q ~ } = \\mathrm { ~ ~ y ~ } + \\mathrm { ~ ~ z ~ } + \\mathrm { ~ ~ w ~ }$ return Q ",
758
+ "page_idx": 16
759
+ },
760
+ {
761
+ "type": "text",
762
+ "text": "class NeuralNetwork: def _init__(self): self.layers = [] def add_layer(self, layer): self.layers.append (layer) ... def rr(self, x): y $=$ self.forward(x ) z = self.forward(y ) $\\begin{array} { r l } { \\mathbb { W } } & { { } = } \\end{array}$ self.forward(z ) $\\mathrm { ~ p ~ } =$ self.forward(w ) Q = y + z + w + p return Q ",
763
+ "page_idx": 16
764
+ },
765
+ {
766
+ "type": "text",
767
+ "text": "class NeuralNetwork(torch.nn. Module): def _init__(self): super(NeuralNetwork, self).__init__() self.layer1 $=$ torch.nn. Linear(10, 20) ... def forward(self, x): $\\textrm { \\textbf { x } } =$ torch.nn.functional. relu(self.layer1(x)) $\\begin{array} { r l } { \\mathrm { y } } & { { } = } \\end{array}$ torch.nn.functional. relu(self.layer2(x)) $z =$ torch.nn.functional. relu(self.layer3(y)) $\\begin{array} { r l } { \\mathbf { \\nabla } \\mathsf { W } } & { { } = } \\end{array}$ torch.nn.functional. relu(self.layer4(z)) p = torch.nn.functional. relu(self.output(w)) Q = p + y + z + w return Q ",
768
+ "page_idx": 16
769
+ },
770
+ {
771
+ "type": "text",
772
+ "text": "Sensitivity to natural language inputs. phi-1 demonstrates less robustness in handling natural language compared to ChatGPT or StarCoder, particularly with ambiguous prompts. This may be because we filter out certain types of data from the training process to guarantee textbook-level quality. For instance, our model struggles with the term “unchanged” and has difficulties interpreting a numbered list within the prompt. ",
773
+ "page_idx": 17
774
+ },
775
+ {
776
+ "type": "text",
777
+ "text": "Prompt: ",
778
+ "text_level": 1,
779
+ "page_idx": 17
780
+ },
781
+ {
782
+ "type": "text",
783
+ "text": "Prompt: ",
784
+ "text_level": 1,
785
+ "page_idx": 17
786
+ },
787
+ {
788
+ "type": "text",
789
+ "text": "\"\"\" Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). x increases by 2, y decreases by 5; (2). x increases by 1, y decreases by 2, (3). x stays at x, y increase by 4. Simulate the movement of the points. ",
790
+ "page_idx": 17
791
+ },
792
+ {
793
+ "type": "text",
794
+ "text": "Prompt: ",
795
+ "text_level": 1,
796
+ "page_idx": 17
797
+ },
798
+ {
799
+ "type": "text",
800
+ "text": "\"\"\" Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). move by (2, -5); (2). move by (1, 2); (3). move by (0, 4); Simulate the movement of the points. ",
801
+ "page_idx": 17
802
+ },
803
+ {
804
+ "type": "text",
805
+ "text": "\"\"\" ",
806
+ "text_level": 1,
807
+ "page_idx": 17
808
+ },
809
+ {
810
+ "type": "text",
811
+ "text": "\"\"\" Alice is moving a point along x,y axes at every iteration. Every time Alice moves the point randomly with one of the options: (1). x increases by 2, y decreases by 5; (2). x increases by \n1, y decreases by 2, (3). $_ \\textrm { x }$ stays unchanged, y increase by 4. Simulate the movement of the points. \"\"\" x, $\\begin{array} { r } { \\mathrm { ~ y ~ } = ~ 0 , } \\end{array}$ , 0 for i in range(10): move $=$ random.choice([1, \n2, 3]) if move $\\mathbf { \\Sigma } = \\mathbf { \\Sigma } \\ \\bar { \\mathbf { \\Sigma } }$ : $\\times \\quad + = \\quad 2$ $\\texttt { y } \\texttt { -- } 5$ elif move $\\ c = ~ 2$ : $\\mathrm { ~ ~ x ~ } + = \\mathrm { ~ ~ 1 ~ }$ y -= 2 elif move $\\ c = ~ 3$ : x = 0 y += 4 return f\"Alice's final position is $\\{ \\{ \\bf x \\} \\}$ , {y}).\" \nx, $\\mathrm { ~ y ~ } = \\mathrm { ~ 0 ~ }$ , 0 \nfor i in range(10): move $=$ random.choice([1, 2, 3]) if move $\\mathbf { \\Sigma } = \\mathbf { \\Sigma } \\mathbf { \\Sigma } \\perp$ : $\\mathrm { ~ ~ x ~ } \\ + = \\ 2$ $\\mathrm { ~ \\ y ~ } \\mathrel { - } = \\mathrm { ~ \\ } 5$ elif move $= = 2$ : $\\mathrm { ~ ~ x ~ } \\mathrel { + } = \\mathrm { ~ ~ 1 ~ }$ y -= 2 elif move $\\ c = ~ 3$ : $\\begin{array} { l l l } { \\mathrm { ~ x ~ } } & { = } & { \\mathrm { ~ x ~ } } \\\\ { \\mathrm { ~ y ~ } } & { + = } & { 4 } \\end{array}$ print(f\"Alice moved {move } point to $\\cdot$ , {y})\") \nx, $\\mathrm { ~ y ~ } = \\mathrm { ~ 0 ~ }$ , 0 \nfor i in range(n): move $=$ random.choice ([(1, 2), (2, -5), (1, 2), (3, 0), (0, 4)]) $\\begin{array} { r l } { \\mathrm { ~ x ~ } } & { { } + = } \\end{array}$ move[0] y $+ =$ move[1] \nreturn f\"Alice moved {x} units to the right and {y} units down after {n} iterations \" ",
812
+ "page_idx": 17
813
+ },
814
+ {
815
+ "type": "text",
816
+ "text": "",
817
+ "page_idx": 17
818
+ },
819
+ {
820
+ "type": "text",
821
+ "text": "",
822
+ "page_idx": 17
823
+ },
824
+ {
825
+ "type": "text",
826
+ "text": "Note: the model hallucinates the moves (1, 2), (3, 0). ",
827
+ "page_idx": 17
828
+ },
829
+ {
830
+ "type": "text",
831
+ "text": "",
832
+ "page_idx": 17
833
+ },
834
+ {
835
+ "type": "text",
836
+ "text": "Bad at counting and spatial reasoning. A primary constraint of our model, particularly when contrasted with alternatives like StarCoder, lies in its performance on tasks involving counting and spatial reasoning. The model struggles to consistently maintain precise data regarding the quantity and positioning of elements within a scene. To illustrate, consider the following example: ",
837
+ "page_idx": 18
838
+ },
839
+ {
840
+ "type": "text",
841
+ "text": "Prompt: ",
842
+ "text_level": 1,
843
+ "page_idx": 18
844
+ },
845
+ {
846
+ "type": "text",
847
+ "text": "\"\"\" Generate a tkinter application, I want two textfields side by side at the top, three buttons at the bottom, one named $A$ on the left, one named $B$ on the right, one named $C$ at the middle. \"\"\" ",
848
+ "page_idx": 18
849
+ },
850
+ {
851
+ "type": "text",
852
+ "text": "phi-1 ",
853
+ "text_level": 1,
854
+ "page_idx": 18
855
+ },
856
+ {
857
+ "type": "text",
858
+ "text": "phi-1-small ",
859
+ "text_level": 1,
860
+ "page_idx": 18
861
+ },
862
+ {
863
+ "type": "image",
864
+ "img_path": "images/92fd9e8681034b250b3247d41a8acad3f9c34eda0498fb2e08efb96ec21402bf.jpg",
865
+ "image_caption": [],
866
+ "image_footnote": [],
867
+ "page_idx": 18
868
+ },
869
+ {
870
+ "type": "text",
871
+ "text": "window $=$ tk.Tk() \nwindow.title(\"TextFields\") \n# Create the left and right textfields \ntext1 $=$ tk.Text(window, text=\"A\") \ntext1.pack() \ntext2 $=$ tk.Text(window, text $=$ \"B\") \ntext2.pack() \n# Create the middle button \nbutton $=$ tk.Button(window, text=\"C\") \nbutton.pack() \n# Start the tkinter application \nwindow.mainloop() ",
872
+ "page_idx": 18
873
+ },
874
+ {
875
+ "type": "text",
876
+ "text": "phi-1-base ",
877
+ "text_level": 1,
878
+ "page_idx": 18
879
+ },
880
+ {
881
+ "type": "text",
882
+ "text": "root $=$ tk.Tk() \nroot.title(\"Text Fields\") \nroot.geometry(\"300x200\") \nroot.resizable(False, False) \nroot.configure(background=\"white\") \nroot.configure(font=(\"Arial\", 12)) \nroot.configure(foreground=\"black\") \nroot.configure(relief=\"groove\") \nroot.configure(padx ${ \\bf \\Lambda } = 1 0$ , pady $= 1 0$ ) \nroot.configure(state=\"disabled\") \n# The model keeps outputting nonsensical code. ",
883
+ "page_idx": 18
884
+ },
885
+ {
886
+ "type": "text",
887
+ "text": "Despite the improvement from finetuning, our model still struggles with counting and spatial reasoning. It generates an extra textfield and misplaces the button in the scene. ",
888
+ "page_idx": 18
889
+ },
890
+ {
891
+ "type": "text",
892
+ "text": "C APPENDIX FOR SECTION 5 ",
893
+ "text_level": 1,
894
+ "page_idx": 19
895
+ },
896
+ {
897
+ "type": "text",
898
+ "text": "C.1 N-GRAM ANALYSIS ",
899
+ "text_level": 1,
900
+ "page_idx": 19
901
+ },
902
+ {
903
+ "type": "text",
904
+ "text": "Our n-gram overlap analysis shows that our dataset has minimal letter-by-letter overlap with HumanEval. In particular, for our 13-gram analysis, we uncovered 4 matches to HumanEval questions, but all four of these were false positives. An example of such a false positive is given below. ",
905
+ "page_idx": 19
906
+ },
907
+ {
908
+ "type": "text",
909
+ "text": "HumanEval: ",
910
+ "text_level": 1,
911
+ "page_idx": 19
912
+ },
913
+ {
914
+ "type": "text",
915
+ "text": "You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. ",
916
+ "page_idx": 19
917
+ },
918
+ {
919
+ "type": "text",
920
+ "text": "CodeExercises: ",
921
+ "text_level": 1,
922
+ "page_idx": 19
923
+ },
924
+ {
925
+ "type": "text",
926
+ "text": "Calculates the power frequency analysis sum of a list of integers. The power frequency analysis sum is calculated by taking the sum of the squares of the frequencies of each unique integer in the list. The frequency of an integer is the number of times it appears in the list. ",
927
+ "page_idx": 19
928
+ },
929
+ {
930
+ "type": "text",
931
+ "text": "C.2 EXAMPLES OF AST AND EMBEDDING DISTANCE BASED SIMILARITY",
932
+ "text_level": 1,
933
+ "page_idx": 19
934
+ },
935
+ {
936
+ "type": "text",
937
+ "text": "In this section, we provide example pairs of codes captured with different AST match rates, denoted as $\\tau$ in the paper. Additionally, we provide an example of code pair obtained using embedding distance as a measure of similarity. ",
938
+ "page_idx": 19
939
+ },
940
+ {
941
+ "type": "text",
942
+ "text": "AST match rate $\\mathbf { \\mu } = \\mathbf { 1 . 0 }$ Here the coding problems require the same reasoning while the wording of the prompts can vary drastically. Particularly, the prompt uses a real-world event, i.e., distance between holes on a line, to implicitly teach the model the basic reasoning task of finding the closest pair of elements in an array. ",
943
+ "page_idx": 19
944
+ },
945
+ {
946
+ "type": "text",
947
+ "text": "HumanEval ",
948
+ "text_level": 1,
949
+ "page_idx": 19
950
+ },
951
+ {
952
+ "type": "text",
953
+ "text": "CodeExercises ",
954
+ "text_level": 1,
955
+ "page_idx": 19
956
+ },
957
+ {
958
+ "type": "text",
959
+ "text": "from typing import List, Tuple \ndef find_closest_elements(numbers: List[ float]) $- >$ Tuple[float, float]: \"\"\" From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) $> > >$ find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) \"\"\" numbers.sort() min_diff $=$ float('inf') closest_pair $=$ None for i in range(len(numbers) - 1): diff $=$ numbers[i+1] - numbers[i] if diff $<$ min_diff: min_diff $=$ diff closest_pair $=$ (numbers[i], numbers[i+1]) return closest_pair \nfrom typing import List, Tuple \ndef find_closest_two_holes(holes: List[int ]) $- >$ (int, int): \"\"\" Finds the two closest holes on a line. Args: holes: A list of integers representing the positions of holes on a line. Returns: A tuple of two integers representing the positions of the two closest holes on the line. \"\"\" holes.sort() min_distance $=$ float('inf') closest_holes $=$ None for i in range(len(holes) - 1): distance $=$ holes $[ \\dot { 1 } + 1 ]$ - holes[i] if distance $<$ min_distance: min_distance $=$ distance closest_holes $=$ (holes[i], holes[i+1]) return closest_holes ",
960
+ "page_idx": 19
961
+ },
962
+ {
963
+ "type": "text",
964
+ "text": "",
965
+ "page_idx": 19
966
+ },
967
+ {
968
+ "type": "text",
969
+ "text": "AST match rate $\\mathbf { \\omega = 0 . 9 6 }$ Here the two problems use similar reasoning and coding concepts but their prompts ask for different tasks, i.e., returning a pair of numbers versus computing their average. ",
970
+ "page_idx": 20
971
+ },
972
+ {
973
+ "type": "image",
974
+ "img_path": "images/00cc89a6a89679de184c428687c060e2cf281d84a51b3aefd3067fa5213864fb.jpg",
975
+ "image_caption": [],
976
+ "image_footnote": [],
977
+ "page_idx": 20
978
+ },
979
+ {
980
+ "type": "text",
981
+ "text": "AST match rate $\\leq \\mathbf { 0 . 9 }$ When the AST match rate $\\leq 0 . 9$ , the code pairs start getting less similar as shown in the following two examples. Here, the AST match rate is 0.9 and 0.83, respectively. ",
982
+ "page_idx": 20
983
+ },
984
+ {
985
+ "type": "image",
986
+ "img_path": "images/427f32eb7db17b1a78f831b2d0b3ecc70a0e9cf36bbda2fbb73effb396f805c5.jpg",
987
+ "image_caption": [],
988
+ "image_footnote": [],
989
+ "page_idx": 20
990
+ },
991
+ {
992
+ "type": "image",
993
+ "img_path": "images/3098008f8a5cb19a6b0ee7f8bbf5e8015c583725d237a6a57814b767f2311d4c.jpg",
994
+ "image_caption": [],
995
+ "image_footnote": [],
996
+ "page_idx": 21
997
+ },
998
+ {
999
+ "type": "text",
1000
+ "text": "Embedding Distance $\\bf \\delta = 0 . 1 6$ Here the two problems have similar Python Docstrings, function names, as well as the code structure which can be extracted with using the L2 distance between the normalized CodeGen-Mono 350M embedding for each of them. ",
1001
+ "page_idx": 21
1002
+ },
1003
+ {
1004
+ "type": "image",
1005
+ "img_path": "images/1dab7f11bec5bb41379764aba62985053c4e886f675060ff4c05edbb5e500ed6.jpg",
1006
+ "image_caption": [],
1007
+ "image_footnote": [],
1008
+ "page_idx": 21
1009
+ },
1010
+ {
1011
+ "type": "text",
1012
+ "text": "D MODEL ARCHITECTURE AND TRAINING DETAILS ",
1013
+ "text_level": 1,
1014
+ "page_idx": 22
1015
+ },
1016
+ {
1017
+ "type": "text",
1018
+ "text": "We use a decoder only transformer Vaswani et al. (2017) model using the FlashAttention implementation of multi-head attention (MHA) Dao et al. (2022). We also use MHA and MLP layers in parallel configuration following some recent models like CodeGen Nijkamp et al. (2022), PaLM Chowdhery et al. (2022), and GPT-NeoX Black et al. (2022). The architecture for our 1.3B parameter phi-1 model consists of 24 layers, hidden dimension of 2048, MLP-inner dimension of 8192, and 32 attention heads of dimension 64 each. The smaller 350M parameter phi-1-small model consists of 20 layers, hidden dimension of 1024, MLP-inner dimension of 4096, and 16 attention heads of dimension 64 each. We also use a rotary position embedding Su et al. (2021) with rotary dimension 32. These architectural choices were adopted from Nijkamp et al. (2022). We also use the same tokenizer as codegen-350M-mono Nijkamp et al. (2022). Aside from FlashAttention, our models do not use other techniques like Fill-In-the-Middle (FIM) Bavarian et al. (2022), or Multi-Query-Attention (MQA) Raffel et al. (2020) that could further boost efficiency Li et al. (2023). ",
1019
+ "page_idx": 22
1020
+ },
1021
+ {
1022
+ "type": "text",
1023
+ "text": "For both pretraining and finetuning, we concatenate our respective datasets into a single dimensional array with “⟨∣endoftext∣⟩” token used for separating the files. We train our models on sequence length of 2048 sliced from our dataset array with next-token prediction loss. We use fp16 training with AdamW optimizer, linear-warmup-linear-decay learning rate schedule, and attention and residual dropout of 0.1. We train on 8 Nvidia-A100 GPUs using deepspeed. Our pretrained base model phi-1-base was obtained in under 4 days of training. Finetuning to obtain phi-1 used an additional 7 hours on the same hardware. ",
1024
+ "page_idx": 22
1025
+ },
1026
+ {
1027
+ "type": "text",
1028
+ "text": "Pretraining. phi-1-base was trained on the CodeTextbook dataset (filtered code-language corpus and synthetic textbooks). We use effective batch size 1024 (including data parallelism and gradient accumulation), maximum learning rate 1e-3 with warmup over 750 steps, and weight decay 0.1, for a total of 36,000 steps. We use the checkpoint at 24,000 steps as our phi-1-base – this is equivalent to $\\sim 8$ epochs on our CodeTextbook dataset for a total of little over 50B total training tokens. Despite the small size and computation, this model already achieves a $29 \\%$ accuracy on HumanEval. ",
1029
+ "page_idx": 22
1030
+ },
1031
+ {
1032
+ "type": "text",
1033
+ "text": "Finetuning. phi-1 is obtained by finetuning phi-1-base on the CodeExercises dataset. For finetuning, we use the same setup as pretraining, but different hyperparameters: we use effective batchsize of 256, maximum learning rate 1e-4 with 50 steps of warmup, and weight decay 0.01. We train for total of 6,000 steps and pick the best checkpoint (saved every 1000 steps). ",
1034
+ "page_idx": 22
1035
+ }
1036
+ ]
parse/test/Fq8tKtjACC/Fq8tKtjACC_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Fq8tKtjACC/Fq8tKtjACC_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/OqlmgmS4Wr/OqlmgmS4Wr.md ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENTTUNING: ENABLING GENERALIZED AGENT ABILITIES FOR LLMS
2
+
3
+ Anonymous authors Paper under double-blind review
4
+
5
+ # ABSTRACT
6
+
7
+ Open large language models (LLMs) with great performance in various tasks have significantly advanced the development of LLMs. However, they are far inferior to commercial models such as ChatGPT and GPT-4 when acting as agents to tackle complex tasks in the real world. These agent tasks employ LLMs as the central controller responsible for planning, memorization, and tool utilization, necessitating both fine-grained prompting methods and robust LLMs to achieve satisfactory performance. Though many prompting methods have been proposed to complete particular agent tasks, there is lack of research focusing on improving the agent capabilities of LLMs themselves without compromising their general abilities. In this work, we present AgentTuning, a simple and general method to enhance the agent abilities of LLMs while maintaining their general LLM capabilities. We construct AgentInstruct, a lightweight instruction-tuning dataset containing high-quality interaction trajectories. We employ a hybrid instructiontuning strategy by combining AgentInstruct with open-source instructions from general domains. AgentTuning is used to instruction-tune the Llama 2 series, resulting in AgentLlama. Our evaluations show that AgentTuning enables LLMs’ agent capabilities without compromising general abilities. The AgentLlama-70B is comparable to GPT-3.5-turbo on unseen agent tasks, demonstrating generalized agent capabilities. We open source the AgentInstruct dataset and AgentLlama7B, 13B, and 70B models at https://anonymous.4open.science/r/ AgentTuning, serving open and powerful alternatives to commercial LLMs for agent tasks.
8
+
9
+ ![](images/b7f41f8f544abfebd2177ec3a172ceeaa0f05bbd06a7e9ff33482a70d1b19868.jpg)
10
+ (a) Overall score in our held-in and held-out tasks. (b) Closed & open LLMs on agent tasks (Liu et al., 2023)
11
+ Figure 1: (a) AgentLlama exhibits superior performance. AgentLlama is a series of models finetuned on the foundation of Llama 2 chat. Moreover, its generalization capability on held-out tasks is on par with GPT-3.5; (b) This figure is directly re-printed from AgentBench (Liu et al., 2023) with permission. Open LLMs significantly underperforms API-based LLMs.
12
+
13
+ ![](images/cb4659041e061e9194a96e87ea5aa9bedeab12475699bc0ed7b4130c3c4e59a7.jpg)
14
+ Figure 2: An overview of AgentInstruct and AgentTuning. The construction of AgentInstruct, consisting of instruction generation, trajectory interaction, and trajectory filter. AgentLlama is finetuned using a mixture of AgentInstruct and general-domain instructions.
15
+
16
+ # 1 INTRODUCTION
17
+
18
+ An agent refers to an entity capable of perceiving its environment, making decisions, and taking actions (Maes, 1994; Wooldridge & Jennings, 1995). Traditional AI agents have been effective in specialized domains, but often fall short in adaptability and generalization. Through alignment training, large language models (LLMs) (Ouyang et al., 2022; Wei et al., 2022a), initially designed for language tasks, have displayed unprecedented capabilities in instruction following (Ouyang et al., 2022), reasoning (Wei et al., 2022b), planning, and even tool utilization (Schick et al., 2023). These capabilities make LLMs an ideal foundation for advancing AI agents toward broad, versatile functionality. Recent projects such as AutoGPT (Richards, 2023), GPT-Engineer (Osika, 2023), and BabyAGI (Nakajima, 2023) have employed LLMs as the core controllers, building powerful agents capable of solving complex problems in the real world.
19
+
20
+ However, a recent study (Liu et al., 2023) shows that open LLMs like Llama (Touvron et al., 2023a;b) and Vicuna (Chiang et al., 2023) significantly lag behind in agent capabilities in complex, real-world scenarios when compared to GPT-3.5 and GPT-4 (OpenAI, 2022; 2023) in Figure 1, though they have performed well in traditional NLP tasks and largely advanced the development of LLMs. The performance gap in agent tasks hampers the advancement of in-depth LLM research and community innovation.
21
+
22
+ Existing studies on LLMs as agents have thus far largely focused on designing prompts or a framework for completing one particular agent task (Yao et al., 2023; Kim et al., 2023; Deng et al., 2023), rather than fundamentally enhancing the agent capabilities of the LLMs themselves. In addition, many efforts are dedicated to improving LLMs in specific aspects, involving fine-tuning the LLMs using datasets tailored to specific tasks (Deng et al., 2023; Qin et al., 2023). This overemphasis on specialized capabilities comes at the expense of the LLMs’ general abilities and also compromises their generalizability.
23
+
24
+ To fundamentally enable generalized agent abilities for LLMs, we introduce a simple and general approach AgentTuning as shown in Figure 2. AgentTuning consists of two components: a lightweight instruct-tuning dataset AgentInstruct and a hybrid instruction-tuning strategy that enhances the agent’s capabilities while preserving its generalization ability. As shown in Table 1, AgentInstruct covers 1,866 verified interaction trajectories with high-quality Chain-of-Thought (CoT) rationale (Wei et al., 2022b) for each decision step from six diverse agent tasks. For each agent task, one interaction trajectory is collected through three phases: instruction construction, trajectory interaction by employing GPT-4 as the agent, and trajectory filtering depending on its reward score. To enhance LLMs’ agent capabilities while preserving their general abilities, we experiment with a hybrid instruction-tuning strategy. The idea is to mix AgentInstruct with high-quality and general data at a certain ratio for supervised fine-tuning.
25
+
26
+ We employ AgentTuning to fine-tune the open Llama 2 series (Touvron et al., 2023b), whose performance on agent tasks are significantly worse that GPT-3.5, resulting in the AgentLlama-7B, 13B and 70B models. Our empirical evaluations have the following observations.
27
+
28
+ Table 1: Overview of our AgentInstruct dataset. AgentInstruct includes 1,866 trajectories from 6 agents tasks. “Inst.” stands for instruction, the agent needs to interact with the environment to complete the task specified in the instruction.. “Traj.” stands for interaction trajectory. “Filt. Traj.”. stands for filtered trajectories. “Task Deri.” stands for Task Derivation.
29
+
30
+ <table><tr><td>Task</td><td>Inst. From</td><td># Inst.</td><td></td><td>Trg</td><td>Ratio</td></tr><tr><td>AlfWorld (Shridhar et al., 2020)</td><td>Train split</td><td>954</td><td>336</td><td>13.52</td><td>35.2%</td></tr><tr><td>WebShop (Yao et al.,2022)</td><td>Train split</td><td>1,485</td><td>351</td><td>3.68</td><td>23.6%</td></tr><tr><td>Mind2Web (Deng et al.,2023)</td><td>Train split</td><td>23,378</td><td>122</td><td>1.001</td><td>0.52%</td></tr><tr><td>Knowledge Graph (Liu et al.,2023)</td><td>Train split</td><td>2,501</td><td>324</td><td>6.04</td><td>13.0%</td></tr><tr><td>Operating System (Liu et al., 2023)</td><td>Self-Instruct</td><td>647</td><td>195</td><td>3.85</td><td>30.1%</td></tr><tr><td rowspan="2">Database (Liu et al., 2023)</td><td>Self-Instruct</td><td>1,074</td><td>178</td><td>2.13</td><td>16.6%</td></tr><tr><td>Task Deri.</td><td>5,302</td><td>360</td><td>2.03</td><td>6.79%</td></tr><tr><td> AgentInstruct</td><td>1</td><td>12.643</td><td>1,866</td><td>5.24</td><td>5.29%</td></tr></table>
31
+
32
+ First, AgentLlama demonstrates strong performance on both held-in tasks in AgentInstruct and unseen held-out agent tasks, suggesting robust generalization on agent capabilities. It also makes AgentLlama-70B comparable to GPT-3.5 on unseen agent tasks without compromising its performance on general NLP tasks, such as on MMLU, GSM8K, HumanEval, and MT-Bench.
33
+
34
+ Second, our analysis on the ratio of agent data with general data suggests that the general capabilities of LLMs are crucial for the generalization of agent tasks. Training solely on agent data, in fact, leads to a decline in generalization performance. This can be explained by the fact that agent tasks demand that LLMs exhibit comprehensive abilities such as planning and reasoning.
35
+
36
+ Third, our error analysis on Llama 2 and AgentLlama shows that AgentTuning significantly reduces instances of basic mistakes such as formatting errors, duplicated generation, and refusal to answer. This suggests that the model inherently possesses the capability to tackle agent tasks, and AgentTuning indeed enables the LLMs’ agent abilities rather than causing it to overfit on agent tasks.
37
+
38
+ AgentTuning represents the very first attempt to instruction-tune LLMs using interaction trajectories across multiple agent tasks. Evaluation results indicate that AgentTuning enables the agent capabilities of LLMs with robust generalization on unseen agent tasks while remaining good on general language abilities. We have open-sourced the AgentInstruct dataset and AgentLlama.
39
+
40
+ # 2 THE AGENTTUNING APPROACH
41
+
42
+ Given an agent task, the interaction trajectory of the LLM agent can be recorded as a conversation history $( u _ { 1 } , a _ { 1 } , \ldots , u _ { n } , a _ { n } )$ . Given that the existing dialogue models typically encompass two roles, the user and the model, $u _ { i }$ represents the input from the user and $a _ { i }$ denotes the response from the model. Each trajectory has a final reward $r \in [ 0 , 1 ]$ , reflecting the completion status of the task.
43
+
44
+ To date, there is no end-to-end attempt to improve the general agent abilities of LLMs. Most existing agent studies focused on either prompting one particular LLM or compiling a LLM-based framework for completing an agent task, such as building a Web agent in WebShop (Yao et al., 2022) and Mind2Web (Deng et al., 2023). According to AgentBench (Liu et al., 2023), all open LLMs are far behind of commercial ones such as GPT-4 and ChatGPT in terms of acting as agents though these models, such as Llama2, have demonstrated strong performance across various benchmarks. The goal of this work is to improve the generalized agent abilities of LLMs while at least maintaining their general LLM capacities such as their performance on MMLU, GSM8K, and HumanEval.
45
+
46
+ We present AgentTuning to achieve this goal, the first step of which is to build the AgentInstruct dataset that is used in the second step to instruction tune the LLMs. We carefully experiment and design these two steps such that the LLMs obtain good performance in (unseen) generalized agent task types while remaining good in general LLM tasks.
47
+
48
+ # 2.1 CONSTRUCTING AGENTINSTRUCT
49
+
50
+ Language instructions have been widely collected and used to tune pre-trained LLMs for better instruction-following capacity, such as FLAN (Wei et al., 2022a) and InstructGPT (Ouyang et al., 2022). It is however much more challenging to collect instructions for agent tasks, as it involves the trajectories of interactions when an agent navigates in a complex environment.
51
+
52
+ We take the very first attempt to build AgentInstruct for improving LLMs’ generalized agent abilities. We detail the design choices during its construction process. It consists of three major stages: Instruction Construction (§2.1.1), Trajectory Interaction $( \ S 2 . 1 . 2 )$ , and Trajectory Filtering (§2.1.3). This process was entirely automated using GPT-3.5 (gpt-3.5-turbo-0613) and GPT$4 \left( { \tt g p t - 4 - 0 6 1 3 } \right)$ , allowing the approach to be easily extended to new agent tasks.
53
+
54
+ # 2.1.1 INSTRUCTION CONSTRUCTION
55
+
56
+ We construct AgentInstruct for six agent tasks, including AlfWorld (Shridhar et al., 2020), WebShop (Yao et al., 2022), Mind2Web (Deng et al., 2023), Knowledge Graph, Operating System, and Database (Liu et al., 2023), representative of a diverse range of real-world scenarios that are relatively easy to collect instructions. AgentInstruct comprises challenging 6 tasks from AgentBench (Liu et al., 2023), covering a wide range of real-world scenarios, with most open-source models performing poorly on them.
57
+
58
+ Table 1 lists the overview of AgentInstruct. If a task (e.g., AlfWorld, WebShop, Mind2Web, and Knowledge Graph) has a training set, we directly use the training split for subsequent phases— trajectory interaction and filtering. For Operating System and Database tasks without training sets, we leverage the idea of Task Derivation and Self-Instruct (Wang et al., 2023c) to construct corresponding instructions.
59
+
60
+ Task Derivation For agent tasks associated with scenarios that have been widely studied, we can directly construct instructions from similar datasets. Thus to construct instructions on the Database (DB) task, we derive instructions from BIRD (Li et al., 2023), a SELECT-only database benchmark. We ran two types of task derivation. First, we construct a trajectory using the question and the reference SQL statement in each BIRD subtask. We then query the database using the reference SQL statement to obtain output of the database and serve it as the submitted answer of the agent. Finally, we ask GPT-4 to fill in the thoughts of the agent given the above information. In this way, we can generate correct trajectories directly from BIRD dataset.
61
+
62
+ However, since this synthesis process determines the number of interaction turns to be fixed at 2, we then propose another approach to improve the diversity by constructing instructions instead of trajectories directly. We prompt GPT-4 with a question from BIRD, and collect its interaction trajectory with the database. After collecting trajectories, we execute the reference SQL statement from BIRD and compare the result to the one from GPT-4. We filter out wrong answers, collecting trajectories that produce a correct answer only.
63
+
64
+ Self-Instruct For the Operating System (OS) task, due to the difficulty in obtaining instructions that involve manipulating OS in terminal, we employed the Self-Instruct method (Wang et al., 2023c) to construct the task. We first prompt GPT-4 to come up with some OS related tasks along with explanations to the task, a reference solution and an evaluation script. Then, we prompt another GPT-4 instance (the solver) with the task and collect its trajectory. After the task is completed, we run the reference solution and compare its result to the one from the solver GPT-4 using the evaluation script. We collect the trajectories where the reference solution and the solver’s solution give the same answer. For the DB task, since BIRD only contains SELECT data, we construct other types of database operations (INSERT, UPDATE and DELETE) in a similar self-instruct approach.
65
+
66
+ It is worth noting that these two methods might risk test data leakage if GPT-4 outputs instructions identical to those in the test set, or if test tasks are constructed from the same dataset we derived from. To address this concern, we conducted a systematic analysis and found no evidence of data leakage. Details can be found in the Appendix B.
67
+
68
+ # 2.1.2 TRAJECTORY INTERACTION
69
+
70
+ With the initial instructions constructed, we use GPT-4 $\left( { \mathfrak { g p t } } - 4 - 0 6 1 3 \right)$ as agents for trajectory interaction. For the Mind2Web task, due to the large number of instructions and our budget constraints, we partially employed ChatGPT (gpt-3.5-turbo-0613) for interactions.
71
+
72
+ We utilize the 1-shot evaluation approach (Liu et al., 2023), primarily due to the stringent requirements for the output format in agent tasks. For each task, we provide a complete interaction process from the training set.
73
+
74
+ Interaction Process The interaction process has two main parts. First, we give the model a task description and a successful 1-shot example. Then, the actual interaction begins. We supply the model with the current instruction and necessary information. Based on this and previous feedback, the model forms a thought and takes an action. The environment then provides feedback, including possible changes or new information. This cycle continues until the model either achieves its goal or reaches its token limit. If the model repeats the same output three times consecutively, we consider it a repetitive failure. If the model’s output format is wrong, we use the BLEU metric to compare it to all possible action choices and pick the closest match as the model’s action for that step.
75
+
76
+ CoT Rationales The Chain-of-Thought (CoT) method has significantly enhanced the inferential capabilities of LLMs by a step-by-step reasoning progress (Wei et al., 2022b). Thus, we employ ReAct (Yao et al., 2023) as the reasoning framework, which outputs CoT explanation (referred to as thought) before producing the final action. Consequently, every action within the collected interaction trajectories is accompanied by a detailed explanation trace, enabling the model to learn the reasoning process leading to the action. For trajectories generated using task derivation without thoughts, we use GPT-4 to supplement them with thoughts for consistency with ReAct prompting.
77
+
78
+ # 2.1.3 TRAJECTORY FILTERING
79
+
80
+ Table 2: Ablation study on trajectory filtering.
81
+
82
+ <table><tr><td></td><td>Held-in Held-out</td></tr><tr><td>Unfiltered</td><td>1.34</td></tr><tr><td>Filtered</td><td>0.47 1.96 0.65</td></tr></table>
83
+
84
+ Agent tasks that encompass real-world scenarios present significant challenges. Even GPT-4 falls short of expectations on such tasks. To ensure the data quality, we rigorously filtered its interaction trajectories. Recall that each interaction trajectory receives a reward $r$ , this allows us to automatically select high-quality trajectories based on the reward. We filter trajectories for all tasks, except for Mind2Web, based on a final reward of $r = 1$ , indicating complete correctness. However, due to the difficulty of the Mind2Web task, we use a threshold of $r \geq \frac { 2 } { 3 }$ to ensure we obtain a sufficient number of trajectories. In Table 2, we demonstrate the effectiveness of our filtering strategy by fine-tuning on both filtered and unfiltered trajectories at 7B scale. Compared to models trained on filtered trajectories, those trained on unfiltered trajectories perform significantly worse on both held-in and held-out tasks. This underscores the importance of data quality over data quantity for agent tasks.
85
+
86
+ Following these steps, the AgentInstruct dataset as shown in Table 1 contains 1,866 final trajectories.
87
+
88
+ # 2.2 INSTRUCTION TUNING
89
+
90
+ In this section, we introduce our hybrid instruction-tuning strategy. The goal is to enhance the LLMs’ agent capabilities without compromising its general abilities.
91
+
92
+ # 2.2.1 GENERAL DOMAIN INSTRUCTIONS
93
+
94
+ Recent studies suggest that training with diverse user prompts enhances model performance (Chiang et al., 2023; Wang et al., 2023b). Using the ShareGPT dataset2, we selectively extracted Englishlanguage conversation, yielding 57,096 conversations with GPT-3.5 and 3,670 with GPT-4. Recognizing the superior quality of GPT-4 responses as highlighted by (Wang et al., 2023a), we adopted a sampling ratio of 1:4 between GPT-4 and GPT-3.5 for better performance.
95
+
96
+ Table 3: Overview of our evaluation tasks. We introduce 6 held-in and 6 held-out tasks for comprehensive evaluation, encompassing a wide range of real-world scenarios. Weight−1 represents the weight of the task when computing the overall score (Cf. Section 3.1). “#Inst.” denotes the number of query samples for the task. “SR” stands for Success Rate.
97
+
98
+ <table><tr><td>Task</td><td>Weight-1 # Shots # Inst.</td><td></td><td></td><td></td><td>Metric</td><td>Characteristics</td></tr><tr><td colspan="7">Held-in Tasks</td></tr><tr><td>AlfWorld (Shridhar et al.,2020)</td><td>20</td><td>1</td><td>50</td><td>35</td><td>SR</td><td>Daily Household Routines</td></tr><tr><td>WebShop (Yao et al., 2022)</td><td>28</td><td>1</td><td>200</td><td>5</td><td>Reward</td><td>Online Shopping</td></tr><tr><td>Mind2Web (Deng et al., 2023)</td><td>9</td><td>3</td><td>1,173</td><td>7</td><td>Step SR</td><td>Website Navigation</td></tr><tr><td>Knowledge Graph (Liu et al.,2023)</td><td>16</td><td>1</td><td>150</td><td>15</td><td>F1</td><td>Retrieve Entity from KG</td></tr><tr><td>Operating System (Liu et al.,2023)</td><td>19</td><td>1</td><td>144</td><td>8</td><td>SR</td><td>Interacting with OS</td></tr><tr><td>Database (Liu et al.,2023)</td><td>12</td><td>0</td><td>300</td><td>5</td><td>SR</td><td>Database Operations</td></tr><tr><td colspan="7">Held-out Tasks</td></tr><tr><td>SciWorld (Wang et al., 2022)</td><td>16</td><td>1</td><td>270</td><td>8</td><td>Reward</td><td>Science Experiments</td></tr><tr><td>MiniWoB++ (Kim et al.,2023)</td><td>31</td><td>≥0</td><td>460</td><td>5</td><td>SR</td><td>Daily Computer Tasks</td></tr><tr><td>HotpotQA (Yang et al.,2018)</td><td>35</td><td>2</td><td>300</td><td>3</td><td>Reward</td><td>Wiki QA</td></tr><tr><td>WebArena (Zhou et al.,2023)</td><td>3</td><td>2</td><td>812</td><td>10</td><td>SR</td><td>Real-world Web Interaction</td></tr><tr><td>ReWOO (Xu et al., 2023)</td><td>61</td><td>1</td><td>350</td><td>2</td><td>SR</td><td>Observation-Free Reasoning</td></tr><tr><td>Digital Card Game (Liu et al.,2023)</td><td>16</td><td>0</td><td>200</td><td>30</td><td>SR</td><td>Adversarial Card Game</td></tr></table>
99
+
100
+ # 2.2.2 MIXTURE TRAINING
101
+
102
+ Using the base model $\pi _ { 0 }$ , which represents the probability distribution $\pi _ { 0 } ( y \mid x )$ of response $y$ given instruction and history $x$ , we consider two datasets: the AgentInstruct dataset $\mathcal { D } _ { \mathrm { a g e n t } }$ and the general dataset $\mathcal { D } _ { \mathrm { g e n e r a l } }$ . Our aim is to find the best policy $\pi _ { \boldsymbol { \theta } } ( y \mid x )$ that minimizes the loss function $J ( \theta )$ , as shown in Equation 1.
103
+
104
+ $$
105
+ J ( \theta ) = \eta \cdot \mathbb { E } _ { ( x , y ) \sim \mathcal { D } _ { \mathrm { a g e n t } } } \left[ \log \pi _ { \theta } ( y \mid x ) \right] + ( 1 - \eta ) \cdot \mathbb { E } _ { ( x , y ) \sim \mathcal { D } _ { \mathrm { g e n e r a l } } } \left[ \log \pi _ { \theta } ( y \mid x ) \right]
106
+ $$
107
+
108
+ Intuitively, a larger $\eta$ should imply that the model is more inclined towards agent-specific capabilities rather than general capabilities. However, we observed that training solely on agent tasks performs worse on unseen tasks compared to mixed training. This suggests that general capabilities play a pivotal role in the generalization of agent abilities, which we discuss further in Section 3.4.
109
+
110
+ # 2.2.3 TRAINING SETUP
111
+
112
+ We choose the chat version of open Llama 2 $( \mathtt { L 1 a m a } - 2 - \{ 7 , 1 3 , 7 0 \} \mathrm { b - c h a t } )$ (Touvron et al., 2023b) as our base models, given its better instruction-following capabilities than base models and commendable performance on traditional NLP tasks. Following Vicuna (Chiang et al., 2023), we standardize all data into a multi-turn chatbot-style format, allowing us to conveniently mix data from different sources. During fine-tuning, we only compute the loss on the model’s output. We fine-tune models of sizes 7B, 13B, and 70B using Megatron-LM (Shoeybi et al., 2020). We use a learning rate of 5e-5 for the 7B and 13B models, and 1e-5 for the 70B model. We set the batch size at 64 with 4,096 sequence length. We use AdamW optimizer (Loshchilov & Hutter, 2019) with a cosine learning scheduler with $2 \%$ warm-up steps. For efficient training, we employ tensor parallelism (Shoeybi et al., 2020) for the 7B and 13B models, and for the 70B model, we also utilize pipeline parallelism (Huang et al., 2019). Detailed hyper-parameters during training can be found in Appendix A.
113
+
114
+ # 3 EXPERIMENTS
115
+
116
+ # 3.1 EVALUATION SETUP
117
+
118
+ Held-in/out Tasks Table 3 summarizes our evaluation tasks. We select six held-in tasks from AgentBench (Liu et al., 2023): AlfWorld (Shridhar et al., 2020), WebShop (Yao et al., 2022), Mind2Web (Deng et al., 2023), and three others, using AgentBench metrics. For held-out tasks, we choose SciWorld (Wang et al., 2022), MiniWoB $^ { + + }$ (Kim et al., 2023), WebArena (Zhou et al.,
119
+
120
+ Table 4: Main results of AgentTuning. AgentLlama significantly outperforms Llama 2 across different scales, excelling in both held-in and held-out tasks, without compromising its performance on general tasks. Overall stands for score calculated from a weighted average of all tasks within the same category (Cf. Section 3.1). (bold: the best; underline: the second best)
121
+
122
+ <table><tr><td rowspan="2">Type</td><td rowspan="2">Task</td><td colspan="2">API-based</td><td colspan="3"> Llama 2 (chat)</td><td colspan="3"> AgentLlama</td></tr><tr><td>GPT-3.5</td><td>GPT-4</td><td>7B</td><td>13B</td><td>70B</td><td>7B</td><td>13B</td><td>70B</td></tr><tr><td rowspan="7"> Held-i</td><td>AlfWorld</td><td>14.0</td><td>78.0</td><td>2.0</td><td>2.0</td><td>6.0</td><td>84.0</td><td>76.0</td><td>86.0</td></tr><tr><td>WebShop</td><td>67.2</td><td>58.6</td><td>4.4</td><td>7.2</td><td>1.5</td><td>63.6</td><td>70.8</td><td>64.9</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td><td>23000</td><td>02000</td><td>644</td><td>4288</td><td>315</td></tr><tr><td>Kid2Wub</td><td>22</td><td>2538</td><td>370088</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Database</td><td>15.0</td><td>33.7</td><td>0.3</td><td>1.3</td><td>9.3</td><td>30.6</td><td>33.7</td><td>37.7</td></tr><tr><td>Overall</td><td>1.59</td><td>2.75</td><td>0.19</td><td>0.20</td><td>0.27</td><td>1.96</td><td>2.11</td><td>2.55</td></tr><tr><td rowspan="8">H</td><td>SciWorld</td><td>21.2</td><td>36.4</td><td>5.9</td><td>6.4</td><td>7.9</td><td>13.7</td><td>18.0</td><td>20.8</td></tr><tr><td>MiniWoB++</td><td>66.7</td><td>69.4</td><td>0.0</td><td>19.6</td><td>0.7</td><td>28.9</td><td>31.1</td><td>60.7</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td>132048</td><td>山28</td><td>0035</td><td>0013590</td><td>10265</td><td>31业60</td></tr><tr><td>DCG</td><td>24.5</td><td>50.0</td><td>0.0</td><td>0.0</td><td>5.0</td><td>7.0</td><td>2.5</td><td>23.5</td></tr><tr><td>Overall</td><td>1.49</td><td>2.13</td><td>0.38</td><td>0.49</td><td>0.51</td><td>0.67</td><td>0.78</td><td>1.40</td></tr><tr><td>MMLU</td><td></td><td></td><td></td><td></td><td></td><td>(+76%)</td><td>(+57%)</td><td>(+176%)</td></tr><tr><td rowspan="5">Tasks</td><td>General HumanEval</td><td>70.0</td><td>86.4</td><td>48.0</td><td>54.3</td><td>62.1</td><td>48.7</td><td>53.6</td><td>59.5</td></tr><tr><td></td><td>48.1</td><td>67.0</td><td>13.9</td><td>18.4</td><td>30.8</td><td>15.4</td><td>14.8</td><td>28.7</td></tr><tr><td>GSM8K</td><td>57.1</td><td>87.1</td><td>27.7</td><td>37.5</td><td>54.7</td><td>24.6</td><td>32.4</td><td>59.7</td></tr><tr><td>MT-Bench</td><td>7.94</td><td>8.99</td><td>6.26</td><td>6.65</td><td>6.85</td><td>6.34</td><td>6.57</td><td>7.26</td></tr><tr><td>Overall</td><td>1.15</td><td>1.53</td><td>0.63</td><td>0.74</td><td>0.95</td><td>6</td><td>0.6</td><td>0.96</td></tr></table>
123
+
124
+ 2023), and three more, covering activities like science experiments (SciWrold) and web interactions (WebArena). These datasets ensure a robust evaluation of our model on diverse, unseen agent tasks.
125
+
126
+ General Tasks To comprehensively evaluate the model’s general capabilities, we selected 4 tasks that are widely adopted in the field. These respectively reflect the model’s knowledge capacity (MMLU (Hendrycks et al., 2021)), mathematical ability (GSM8K (Cobbe et al., 2021)), coding capability (Humaneval (Chen et al., 2021)), and human preference (MT-Bench (Zheng et al., 2023)).
127
+
128
+ Baselines In Figure 1, the api-based commercial model notably surpasses open-source ones in agent tasks. Hence, we selected GPT-3.5 (OpenAI, 2022) $( \mathtt { g p t } - 3 . 5 \mathrm { - t u r b o - } 0 6 1 3 )$ and GPT-4 (OpenAI, 2023) $\left( { \mathfrak { g p t } } - 4 - 0 6 1 3 \right)$ for their comprehensive agent capabilities. For comparison, we evaluated the open-source Llama 2 (Touvron et al., 2023b) chat version $( \mathtt { L 1 a m a - 2 - 7 } , \mathtt { 1 3 } , \mathtt { 7 0 b - c h a t } )$ , chosen for its superior instruction-following capabilities over the base version, which is crucial for agent tasks. Following AgentBench (Liu et al., 2023), we truncate dialogue histories exceeding model length limits and typically use greedy decoding. For WebArena, we adopt nucleus sampling (Holtzman et al., 2020) with $p = 0 . 9$ for exploration. Task prompts are in Appendix D.
129
+
130
+ Overall Score Calculation Differences in task difficulty may result in higher scores (e.g., ReWOO) overshadowing lower ones (e.g., WebArena) in direct averages. Based on (Liu et al., 2023), we normalize scores of each task across evaluated models, scaling to an average of 1 for balanced benchmark assessments. Task weights are detailed in Table 3 for future reference.
131
+
132
+ ![](images/4a896d4960c0fa2cfbea687b78ec99642dc8edcf2ba4d7a21e10fe4cf7d26b07.jpg)
133
+ Figure 3: (a) Proportion of failed trajectories versus the type of the first error. AgentTuning significantly reduces the occurrence of elementary errors; (b) The contribution of each individual task. Training solely on one task also promotes performance on other tasks.
134
+
135
+ # 3.2 MAIN RESULTS
136
+
137
+ Table 4 presents the results on our held-in, held-out, and general tasks. Overall, AgentLlama exhibits significant improvements over Llama 2 series different scales in both held-in and held-out tasks, while maintaining performance on general tasks. Although the improvement on the held-in tasks is more pronounced than on the held-out tasks, the enhancement in the held-out tasks still reaches up to $170 \%$ . This results demonstrates the potential of our model as a general agent. On several tasks, the 13B and 70B versions of AgentLlama even surpassed GPT-4.
138
+
139
+ For most of the held-in tasks, the performance of Llama 2 is nearly zero, indicating that the model is entirely incapable of handling these tasks. Detailed error analysis in the following subsection (Cf. Section 3.3) reveals that the majority of mistakes are elementary errors, such as invalid instructions or repetitions. AgentLlama, on the other hand, commits notably fewer elementary errors, indicating that our approach effectively activates the agent capabilities of the model. Remarkably, the 70B AgentLlama demonstrates performance nearly approaching GPT-4 overall.
140
+
141
+ On the held-out tasks, the 70B AgentLlama demonstrates performance close to that of GPT-3.5. Furthermore, we observed a significantly larger improvement in the 70B model $( + 1 7 6 \% )$ compared to the 7B model $( + 7 6 \% )$ . We believe this is because larger models possess stronger generalization capabilities, allowing them to better generalize to held-out tasks with the same train data.
142
+
143
+ On general tasks, AgentLlama performs on par with Llama 2 across four dimensions: knowledge, mathematics, coding, and human preferences. This sufficiently demonstrates that our model maintains the same general capabilities even with enhanced agent abilities.
144
+
145
+ # 3.3 ERROR ANALYSIS
146
+
147
+ To delve into error analysis, we selected three tasks from the held-in set (AlfWorld, WebShop, Knowledge Graph) and identified common error types using a rule-based approach, such as invalid actions and repeated generations. The results can be seen in Figure 3a. Overall, the original Llama 2 exhibited more elementary mistakes like repetition or taking invalid actions. In contrast, GPT-3.5 and especially GPT-4 made fewer of such errors. However, the AgentLlama noticeably reduced these basic errors. We speculate that while Llama 2 chat inherently possesses agent capabilities, its poor performance might be due to a lack of aligned training on agent data; the AgentTuning effectively activated its agent potential.
148
+
149
+ # 3.4 ABLATION STUDY
150
+
151
+ Effect of Agent & General Instructions Table 5 illustrates the performance when trained exclusively on either agent or general instructions. It is observed that solely using agent data for training significantly improves the results on the held-in set. Yet, it struggles to generalize well across both agent and general tasks. When integrating general data, AgentLlama performs almost at its best for both held-in and held-out tasks. This underscores the critical importance of general instructions in model generalization. Intriguingly, when considering the 7B/13B scale, the enhancement seen in held-out tasks from mixed training is nearly equivalent to training with just the general data. A considerable leap in performance is only observed at the 70B scale. This leads us to speculate that achieving optimal generalization for agent tasks might necessitate a specific model size.
152
+
153
+ Table 5: Ablation study on the effect of agent and general instructions.
154
+
155
+ <table><tr><td colspan="2">Held-in Held-out General</td></tr><tr><td>AgentLlama-7B 1.96 - general only 0.38</td><td>0.67 0.63 0.64 0.61</td></tr><tr><td>- agent only 1.34 AgentLlama-13B 2.11</td><td>0.09 0.22 0.78 0.69</td></tr><tr><td>- general only 0.43</td><td>0.81 0.63</td></tr><tr><td>- agent only 1.57</td><td>0.10 0.19</td></tr><tr><td>AgentLlama-70B 2.55</td><td>1.40 0.96</td></tr><tr><td>- general only 0.99 - agent only 2.47</td><td>0.98 1.00 0.87 0.83</td></tr></table>
156
+
157
+ Effect of Different Tasks We examine mutual task enhancements by fine-tuning on individual tasks in AgentInstruct. We use Llama-7B for ablation study. Figure 3b reveals that fine-tuning primarily benefits the respective task. Although many tasks aid others, Mind2Web stands out with minimal cross-task enhancement, possibly due to its single-round format contrasting with multiround tasks.
158
+
159
+ # 4 RELATED WORK
160
+
161
+ LLM-as-Agent Before the rise of LLMs, agent tasks primarily relied on reinforcement learning or encoder models like BERT. With the advent of LLMs, research shifted towards LLM agents. Notably, ReAct (Yao et al., 2023) innovatively combined CoT reasoning with agent actions. Several studies also applied language models to specific agent tasks, such as online shopping (Yao et al., 2022), web browsing (Deng et al., 2023), and household exploration (Shridhar et al., 2020). Recently, with ChatGPT showcasing advanced planning and reasoning skills, research like ReWOO (Xu et al., 2023) and RCI (Kim et al., 2023) has delved into prompting strategies and frameworks to boost language model efficiency in agent tasks without the need for fine-tuning.
162
+
163
+ Instruction Tuning Instruction tuning aims at aligning the language models to follow human instructions and produce outputs that better fit human preferences. Instruction tuning mainly focus on training language models to follow human instructions among multiple general tasks. For instance, FLAN (Wei et al., 2022a) and T0 (Sanh et al., 2022) demonstrates the strong zero-shot generalization ability of language models fine-tuned on multiple task datasets. Further, FLAN-V2 (Longpre et al., 2023) explores the performance of instruction tuning across multiple scales of models and datasets. With the impressive alignment capability demonstrated by commercial LLMs, many recent works (Chiang et al., 2023; Wang et al., 2023a) propose methods to distill instruction tuning dataset from close-sourced model to enhance the alignment of open-source models.
164
+
165
+ # 5 CONCLUSION
166
+
167
+ In this work, we study how to enable generalized agent abilities for LLMs, bridging the disparity between open and commercial LLMs on agent tasks. We present the AgentTuning approach to achieve this goal. AgentTuning first introduces the AgentInstruct dataset covering 1,866 verified agent interaction trajectories and then designs an instruction-tuning strategy with the mixture of AgentInstruct and general-domain instructions. We generate the open AgentLlama by employing AgentTuning to tune the Llama 2 models. AgentLlama exhibits strong performance on unseen agent tasks while preserving their general abilities on MMLU, GSM8K, HumanEval, and MT-Bench. To date, AgentLlama-70B is the first open LLM that matches GPT-3.5-turbo on agent tasks.
168
+
169
+ REFERENCES
170
+ Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, Alex Ray, Raul Puri, Gretchen Krueger, Michael Petrov, Heidy Khlaaf, Girish Sastry, Pamela Mishkin, Brooke Chan, Scott Gray, Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz Kaiser, Mohammad Bavarian, Clemens Winter, Philippe Tillet, Felipe Petroski Such, Dave Cummings, Matthias Plappert, Fotios Chantzis, Elizabeth 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 Welinder, Bob McGrew, Dario Amodei, Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba. Evaluating large language models trained on code. 2021.
171
+ Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng, Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan Zhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion Stoica, and Eric P. Xing. Vicuna: An open-source chatbot impressing gpt-4 with $9 0 \% *$ chatgpt quality, March 2023. URL https: //lmsys.org/blog/2023-03-30-vicuna/.
172
+ Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian, Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman. Training verifiers to solve math word problems, 2021.
173
+ Xiang Deng, Yu Gu, Boyuan Zheng, Shijie Chen, Samuel Stevens, Boshi Wang, Huan Sun, and Yu Su. Mind2web: Towards a generalist agent for the web. arXiv preprint arXiv:2306.06070, 2023.
174
+ Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. Measuring massive multitask language understanding. In 9th International Conference on Learning Representations, ICLR 2021, Virtual Event, Austria, May 3-7, 2021. OpenReview.net, 2021. URL https://openreview.net/forum?id=d7KBjmI3GmQ.
175
+ Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi. The curious case of neural text degeneration. In 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020. OpenReview.net, 2020. URL https://openreview. net/forum?id ${ . } = { }$ rygGQyrFvH.
176
+ Yanping Huang, Youlong Cheng, Ankur Bapna, Orhan Firat, Dehao Chen, Mia Chen, HyoukJoong Lee, Jiquan Ngiam, Quoc V Le, Yonghui Wu, et al. Gpipe: Efficient training of giant neural networks using pipeline parallelism. Advances in neural information processing systems, 32, 2019.
177
+ Geunwoo Kim, Pierre Baldi, and Stephen McAleer. Language models can solve computer tasks, 2023.
178
+ Jinyang Li, Binyuan Hui, Ge Qu, Binhua Li, Jiaxi Yang, Bowen Li, Bailin Wang, Bowen Qin, Rongyu Cao, Ruiying Geng, Nan Huo, Chenhao Ma, Kevin C. C. Chang, Fei Huang, Reynold Cheng, and Yongbin Li. Can llm already serve as a database interface? a big bench for large-scale database grounded text-to-sqls, 2023.
179
+ Xiao Liu, Hao Yu, Hanchen Zhang, Yifan Xu, Xuanyu Lei, Hanyu Lai, Yu Gu, Hangliang Ding, Kaiwen Men, Kejuan Yang, et al. Agentbench: Evaluating llms as agents. ArXiv preprint, abs/2308.03688, 2023. URL https://arxiv.org/abs/2308.03688.
180
+ Shayne Longpre, Le Hou, Tu Vu, Albert Webson, Hyung Won Chung, Yi Tay, Denny Zhou, Quoc V. Le, Barret Zoph, Jason Wei, and Adam Roberts. The flan collection: Designing data and methods for effective instruction tuning, 2023.
181
+ Ilya Loshchilov and Frank Hutter. Decoupled weight decay regularization. In 7th International Conference on Learning Representations, ICLR 2019, New Orleans, LA, USA, May 6-9, 2019. OpenReview.net, 2019. URL https://openreview.net/forum?id $=$ Bkg6RiCqY7.
182
+ Pattie Maes. Agents that reduce work and information overload. Commun. ACM, 37:30–40, 1994.
183
+
184
+ Yohei Nakajima. Babyagi. Python. https://github.com/yoheinakajima/babyagi, 2023.
185
+
186
+ OpenAI. Introducing chatgpt, 2022. URL https://openai.com/blog/chatgpt.
187
+
188
+ OpenAI. Gpt-4 technical report. arXiv, pp. 2303–08774, 2023.
189
+
190
+ Anton Osika. Gpt-engineer. Python. https://github.com/AntonOsika/gpt-engineer, 2023.
191
+
192
+ Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul Christiano, Jan Leike, and Ryan Lowe. Training language models to follow instructions with human feedback, 2022.
193
+
194
+ Yujia Qin, Shihao Liang, Yining Ye, Kunlun Zhu, Lan Yan, Yaxi Lu, Yankai Lin, Xin Cong, Xiangru Tang, Bill Qian, Sihan Zhao, Runchu Tian, Ruobing Xie, Jie Zhou, Mark Gerstein, Dahai Li, Zhiyuan Liu, and Maosong Sun. Toolllm: Facilitating large language models to master $1 6 0 0 0 +$ real-world apis, 2023.
195
+
196
+ Toran Bruce Richards. Auto-gpt: An autonomous gpt-4 experiment, 2023.
197
+
198
+ Victor Sanh, Albert Webson, Colin Raffel, Stephen H. Bach, Lintang Sutawika, Zaid Alyafeai, Antoine Chaffin, Arnaud Stiegler, Arun Raja, Manan Dey, M Saiful Bari, Canwen Xu, Urmish Thakker, Shanya Sharma Sharma, Eliza Szczechla, Taewoon Kim, Gunjan Chhablani, Nihal V. Nayak, Debajyoti Datta, Jonathan Chang, Mike Tian-Jian Jiang, Han Wang, Matteo Manica, Sheng Shen, Zheng Xin Yong, Harshit Pandey, Rachel Bawden, Thomas Wang, Trishala Neeraj, Jos Rozen, Abheesht Sharma, Andrea Santilli, Thibault Fevry, Jason Alan Fries, Ryan Teehan, ´ Teven Le Scao, Stella Biderman, Leo Gao, Thomas Wolf, and Alexander M. Rush. Multitask prompted training enables zero-shot task generalization. In The Tenth International Conference on Learning Representations, ICLR 2022, Virtual Event, April 25-29, 2022. OpenReview.net, 2022. URL https://openreview.net/forum?id $=$ 9Vrb9D0WI4.
199
+
200
+ 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, 2023.
201
+
202
+ Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. Megatron-lm: Training multi-billion parameter language models using model parallelism, 2020.
203
+
204
+ Mohit Shridhar, Xingdi Yuan, Marc-Alexandre Cote, Yonatan Bisk, Adam Trischler, and Matthew Hausknecht. Alfworld: Aligning text and embodied environments for interactive learning. In International Conference on Learning Representations, 2020.
205
+
206
+ Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothee´ Lacroix, Baptiste Roziere, Naman Goyal, Eric Hambro, Faisal Azhar, et al. Llama: Open and \` efficient foundation language models. ArXiv preprint, abs/2302.13971, 2023a. URL https: //arxiv.org/abs/2302.13971.
207
+
208
+ 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, abs/2307.09288, 2023b. URL https: //arxiv.org/abs/2307.09288.
209
+
210
+ Guan Wang, Sijie Cheng, Xianyuan Zhan, Xiangang Li, Sen Song, and Yang Liu. Openchat: Advancing open-source language models with mixed-quality data, 2023a.
211
+
212
+ Ruoyao Wang, Peter Jansen, Marc-Alexandre Cotˆ e, and Prithviraj Ammanabrolu. ScienceWorld: Is ´ your agent smarter than a 5th grader? In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, pp. 11279–11298, Abu Dhabi, United Arab Emirates, 2022. Association for Computational Linguistics. URL https://aclanthology.org/2022. emnlp-main.775.
213
+
214
+ Yizhong Wang, Hamish Ivison, Pradeep Dasigi, Jack Hessel, Tushar Khot, Khyathi Raghavi Chandu, David Wadden, Kelsey MacMillan, Noah A. Smith, Iz Beltagy, and Hannaneh Hajishirzi. How far can camels go? exploring the state of instruction tuning on open resources, 2023b.
215
+ Yizhong Wang, Yeganeh Kordi, Swaroop Mishra, Alisa Liu, Noah A. Smith, Daniel Khashabi, and Hannaneh Hajishirzi. Self-instruct: Aligning language models with self-generated instructions, 2023c.
216
+ 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. In The Tenth International Conference on Learning Representations, ICLR 2022, Virtual Event, April 25-29, 2022. OpenReview.net, 2022a. URL https://openreview.net/forum? id $=$ gEZrGCozdqR.
217
+ 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, 2022b.
218
+ Michael Wooldridge and Nicholas R Jennings. Intelligent agents: Theory and practice. The knowledge engineering review, 10(2):115–152, 1995.
219
+ Binfeng Xu, Zhiyuan Peng, Bowen Lei, Subhabrata Mukherjee, Yuchen Liu, and Dongkuan Xu. Rewoo: Decoupling reasoning from observations for efficient augmented language models, 2023.
220
+ Zhilin Yang, Peng Qi, Saizheng Zhang, Yoshua Bengio, William Cohen, Ruslan Salakhutdinov, and Christopher D. Manning. HotpotQA: A dataset for diverse, explainable multi-hop question answering. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pp. 2369–2380, Brussels, Belgium, 2018. Association for Computational Linguistics. doi: 10.18653/v1/D18-1259. URL https://aclanthology.org/D18-1259.
221
+ Shunyu Yao, Howard Chen, John Yang, and Karthik Narasimhan. Webshop: Towards scalable real-world web interaction with grounded language agents. Advances in Neural Information Processing Systems, 35:20744–20757, 2022.
222
+ Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik R Narasimhan, and Yuan Cao. React: Synergizing reasoning and acting in language models. In The Eleventh International Conference on Learning Representations, 2023.
223
+ Lianmin Zheng, Wei-Lin Chiang, Ying Sheng, Siyuan Zhuang, Zhanghao Wu, Yonghao Zhuang, Zi Lin, Zhuohan Li, Dacheng Li, Eric. P Xing, Hao Zhang, Joseph E. Gonzalez, and Ion Stoica. Judging llm-as-a-judge with mt-bench and chatbot arena, 2023.
224
+ Shuyan Zhou, Frank F Xu, Hao Zhu, Xuhui Zhou, Robert Lo, Abishek Sridhar, Xianyi Cheng, Yonatan Bisk, Daniel Fried, Uri Alon, et al. Webarena: A realistic web environment for building autonomous agents. arXiv preprint arXiv:2307.13854, 2023. URL https://webarena.dev.
225
+
226
+ A HYPER-PARAMETERS
227
+ Table 6: Hyper-parameters for AgentLlama training
228
+
229
+ <table><tr><td>Hyperparameters</td><td>AgentLlama-7B</td><td>AgentLlama-13B</td><td>AgentLlama-70B</td></tr><tr><td>Number of Layers</td><td>32</td><td>40</td><td>80</td></tr><tr><td>Hidden size</td><td>4096</td><td>5120</td><td>8192</td></tr><tr><td>FFN inner hidden size</td><td>11008</td><td>13824</td><td>28672</td></tr><tr><td>Attention heads</td><td>32</td><td>40</td><td>64</td></tr><tr><td>Hidden-Dropout</td><td>0.05</td><td>0.05</td><td>0.05</td></tr><tr><td>Attention Dropout</td><td>0</td><td>0</td><td>0</td></tr><tr><td>Warmup Ratio</td><td>0.02</td><td>0.02</td><td>0.02</td></tr><tr><td>Decay Ratio</td><td>0.9</td><td>0.9</td><td>0.9</td></tr><tr><td>Peak Learning Rate</td><td>5e-5</td><td>5e-5</td><td>1e-5</td></tr><tr><td>Batch Size</td><td>64</td><td>64</td><td>64</td></tr><tr><td>Weight Decay</td><td>0.1</td><td>0.1</td><td>0.1</td></tr><tr><td>Learning Rate Decay</td><td>Cosine</td><td>Cosine</td><td>Cosine</td></tr><tr><td>Adam e</td><td>1e-8</td><td>1e-8</td><td>1e-8</td></tr><tr><td>Adam β1</td><td>0.9</td><td>0.9</td><td>0.9</td></tr><tr><td>Adam β2</td><td>0.95</td><td>0.95</td><td>0.95</td></tr><tr><td>Gradient Clipping</td><td>1.0</td><td>1.0</td><td>1.0</td></tr></table>
230
+
231
+ For AgentLlama results in Table 4, the models are fine-tuned using ShareGPT dataset and AgentInstruct. The sampling ratio of AgentInstruct is respectively 0.4, 0.2, 0.2 for 7B, 13B and 70B models. In ShareGPT dataset, the sampling ratio of GPT-3.5 and GPT-4 is 0.8 and 0.2 respectively.
232
+
233
+ # B DATA CONTAMINATION
234
+
235
+ Since we obtain part of our training data by task derivation and self-instruct, there is a concern that potential data contamination could lead to the overestimation of performance. Therefore, we conducted a systematic contamination analysis between our training set and test set of held-in tasks, and found no evidence of data leakage.
236
+
237
+ Following Llama 2 (Touvron et al., 2023b), we applied a token-based approach for contamination analysis. We match tokenized 10-grams from test set examples on tokenized training set data, while allowing for at most 4 tokens of mismatch to account for slight differences. We define a token as “contaminated” if there is a 10-gram containing this token found both in the training set and the test set. We define the contamination rate of an evaluation example as the rate of contaminated tokens it contains. We define an evaluation example as “dirty” if its contamination rate is greater than $80 \%$ , and “clean” if its contamination rate is less than $20 \%$ .
238
+
239
+ Table 7: Data Contamination Analysis.
240
+
241
+ <table><tr><td>Task</td><td>Contamination Rate</td><td># Clean Ex.</td><td># Dirty Ex.</td><td>#Examples</td></tr><tr><td>ALFWorld</td><td>12.00%</td><td>34</td><td>6</td><td>50</td></tr><tr><td>Database</td><td>4.72%</td><td>277</td><td>0</td><td>300</td></tr><tr><td>KnowledgeGraph</td><td>0.34%</td><td>149</td><td>0</td><td>150</td></tr><tr><td>Mind2Web</td><td>3.40%</td><td>170</td><td>0</td><td>177</td></tr><tr><td>OperatingSystem</td><td>15.95%</td><td>95</td><td>0</td><td>144</td></tr><tr><td>WebShop</td><td>47.18%</td><td>3</td><td>1</td><td>200</td></tr><tr><td>Total</td><td>15.58%</td><td>728</td><td>7</td><td>1021</td></tr></table>
242
+
243
+ We summarize our analysis in Table 7. Here are some findings:
244
+
245
+ • There are no dirty examples in most tasks, proving that there is no data leakage or contamination in our dataset.
246
+
247
+ • The tasks where we construct instructions by task derivation or self-instruct, i.e. Database and Operating System, show higher contamination rate. However, there are no dirty examples found, and most examples are clean, showing that this isn’t caused by data contamination. We argue that
248
+ this is due to the coding nature inside these two tasks, because it means that there would be more verbatims like keywords showing up in our training set.
249
+ • We noticed that there are 6 dirty examples in ALFWorld. We examined the task descriptions
250
+ of ALFWorld and found that they are usually short sentences consisting of only a few phrases, which makes the $80 \%$ threshold of dirty examples easier to reach. Moreover, we found that the task description often matches the observations in our training data, since they both contain lots of nouns describing the household environment. For the dirty examples, we found that there are
251
+ some tasks in the test set that’s just one or two words different from those in the training set. For example, the task “cool some mug and put it in coffeemachine” matches “heat some mug and put
252
+ it in coffeemachine” and is considered dirty. This may be due to the dataset construction process of ALFWorld.
253
+ The WebShop task has a high $4 7 . 1 8 \%$ contamination rate. After examining the dirty examples,
254
+ we found that this is mainly due to the constraints in the task, especially prices. For example, the task “i’m looking for a queen size bedspread set in the color redwood, and price lower than 60.00 dollars” matches “i would like a slim fit t-shirt that is xx-large and is the color blue2, and
255
+ price lower than 60.00 dollars” and “i want a queen size upholstered platform bed” at the same time, making it’s contamination rate high. However, since there is only one dirty example, we can
256
+ conclude that this is just caused by the task generation method of WebShop and does not imply a data contamination.
257
+
258
+ # C PROMPT FOR DATA CONSTRUCTION
259
+
260
+ # C.1 SELF-INSTRUCT
261
+
262
+ # C.1.1 DATABASE
263
+
264
+ You are Benchmarker-GPT, and now your task is to generate some database
265
+ related tasks for an agent benchmark.
266
+ Your output should be in JSON format and no extra texts except a JSON
267
+ object is allowed.
268
+ Please generate tasks with high diversity. For example, the theme of the
269
+ task and the things involed in the task should be as random as possible
270
+ . People’s name in your output should be randomly picked. For example,
271
+ do not always use frequent names such as John.
272
+ You are generating {{operation_type}} task now.
273
+ The meaning of the fields are as follows:
274
+ ‘‘‘json
275
+ { "description": "A description of your task for the agent to do. The task should be as diverse as possible. Please utilize your imagination.", "label": "The standard answer to your question, should be valid MySQL SQL statement.", "table": { "table_name": "Name of the table to operate on.", "table_info": { "columns": [ { "name": "Each column is represented by a JSON object. This field is the name of the column. Space or special characters are allowed.", "type": "Type of this column. You should only use types supported by MySQL. For example, ‘VARCHAR2‘ is not allowed." } ],
276
+
277
+ "rows": [ ["Rows in the table.", "Each row is represented by a JSON array with each element in it corresponds to one column."] ] } }, "type": ["{{operation_type}}"] "add_description": "Describe the name of the table and the name of the columns in the table." 1-
278
+
279
+ # C.1.2 OPERATING SYSTEM
280
+
281
+ I am an operating system teaching assistant, and now I need to come up with a problem for the students’ experiment. The questions are related to the Linux operating system in the hands of the students, and should encourage multi-round interaction with the operating system. The questions should resemble real-world scenarios when using operating system.
282
+
283
+ The task execution process is as follows:
284
+
285
+ 1. First execute an initialization bash script to deploy the environment required for the topic in each student’s Linux (ubuntu) operating system. If no initialization is required, simply use an empty script. 2. Continue to execute a piece of code in the operating system, and the output result will become the standard answer.
286
+ 3. Students start interacting with the shell, and when they think they have an answer, submit their answer.
287
+
288
+ You should also provide an example solution script to facilitate the evaluation process.
289
+
290
+ The evaluation process could be in one of the following forms, inside the parentheses being the extra parameters you should provide:
291
+
292
+ 1. exact_match(str): Perform a exact match to a given standard answer string. Provide the parameter inside triple-backticks, for example:
293
+
294
+ [Evaluation] exact_match
295
+
296
+ ‘‘‘
297
+
298
+ 2. bash_script(bash): Execute a bash script and use its exit code to verify the correctness. Provide the parameter inside triple-backticks, for example:
299
+
300
+ [Evaluation]
301
+ bash_script
302
+ ‘‘‘bash
303
+ #!/bin/bash
304
+ exit \$(test \$(my_echo 233) = 233)
305
+ ‘‘‘ 3. integer_match(): Match the student’s answer to the output of the example script, comparing only the value, e.g. 1.0 and 1 will be
306
+ considered a match.
307
+ 4. size_match(): Match the student’s answer to the output of the example script, comparing as human-readable size, e.g. 3MB and 3072KB will be considered a match.
308
+ 5. string_match(): Match the student’s answer to the output of the example script, stripping spaces before and after the string.
309
+
310
+ Now please help me to come up with a question, this question needs to be complex enough, and encouraging multi-round interactions with the OS.
311
+
312
+ You should follow the following format:
313
+
314
+ [Problem]
315
+
316
+ {Please Insert Your Problem description Here, please give a detailed and concise question description, and the question must be related to the Linux operating system. Please use only one sentence to describe your intent. You can add some limitations to your problem to make it more diverse. When you’d like the student to directly interact in the shell, do not use terms like "write a bash script" or "write a shell command". Instead, directly specify the task goal like "Count ...", "Filter out ...", "How many ..." or so. Use ’you’ to refer to the student. The problem description shouldn’t contain anything that is opaque, like " some file". Instead, specify the file name explicitly (and you need to prepare these files in the initialization script) or directory like "the current directory" or "your home directory".}
317
+
318
+ [Explanation]
319
+
320
+ {You can explain how to solve the problem here, and you can also give some hints.}
321
+
322
+ [Initialization]
323
+
324
+ ‘‘‘bash
325
+ {Please Insert Your Initialization Bash Script Here.}
326
+ ‘‘‘
327
+
328
+ [Example] ‘‘‘bash
329
+
330
+ {Please Insert Your Example Bash Script Here. Give the example solution according to your explanation. Remember that the results of the example script will be match against the student’s answer in "integer_match", " size_match" and "string_match". So, when using these types of evaluation , do not output any extra messages than the integer, size or string. Besides, when dealing with problems that needs to write a executable script, use "bash_script" evaluation to manually evaluate them.} ‘‘‘
331
+
332
+ [Evaluation]
333
+
334
+ {Evaluation type specified above} {Evaluation parameter, if any}
335
+
336
+ # C.2 TASK DERIVATION
337
+
338
+ # C.2.1 DATABASE
339
+
340
+ # (Thought Construction)
341
+
342
+ Given a conversation log between a human and an AI agent on database tasks, your job is to fill in the thoughts of the AI agent in its response. Besides, an evidence will be given as a hint to the question, you should include this evidence in the thoughts of the agent. Give your answer concisely but logically, making the AI agent think step-by-step. You should pay special attention to how the AI agent analyze the question and give a solution.
343
+
344
+ The conversation log is given in JSON format, and you should also response in JSON format specified below in the examples.
345
+
346
+ Example 1:
347
+
348
+ ‘‘‘json
349
+ {"evidence": "released in the year 1945 refers to movie_release_year $=$ 1945;", "conversations": [{"from": "human", "value": "\n I will ask you a question, then you should operate the MySQL database with sql to answer the question.\n You must response in pure JSON format, you can put what you want to say in "thought" field.\n You MUST response in JSON format without any other comments:\n {"thought": "HERE IS YOUR THOUGHT ", "sql": "HERE IS THE SQL YOU WANT TO EXECUTE"}\n If you want to commit your final answer, then use:\n {"thought": "HERE IS YOUR THOUGHT", " commit": ["ANSWER1", "ANSWER2", ...]}\n Your answer should be accurate. Your answer must be exactly the same as the correct answer.\n If the question is about modifying database, then your "commit" field can be anything.\n If your response cannot be interpreted by JSON loader, this question will be judged as fail immediately.\n Your input will be raw MySQL response, you have to deal with it by yourself.\n "}, {"from": " gpt", "value": "Ok."}, {"from": "human", "value": "Name movie titles released in year 1945. Sort the listing by the descending order of movie popularity. Give only first 5 titles.\nThe name of this table is movies , and the headers of this table are movie_id,movie_title,
350
+ movie_release_year,movie_url,movie_title_language,movie_popularity, movie_image_url,director_id,director_name,director_url."}, {"from": "gpt ", "value": "{"thought": "[THOUGHT_1]", "sql": "SELECT movie_title FROM movies WHERE movie_release_year $=$ 1945 ORDER BY movie_popularity DESC LIMIT 5"}"}, {"from": "human", "value": "[(’Brief Encounter’,), (’ Children of Paradise’,), (’Rome, Open City’,), (’Scarlet Street’,), (’ The Lost Weekend’,)]"}, {"from": "gpt", "value": "{"thought": "[
351
+ THOUGHT_2]", "commit": ["Brief Encounter", "Children of Paradise", "Rome , Open City", "Scarlet Street", "The Lost Weekend"]}"}]}
352
+ ‘‘‘
353
+
354
+ Your response should be:
355
+
356
+ ‘‘‘json
357
+ {"thought_1": "According to the provided table structure, we can know
358
+ that a movie was released in year 1945 means that column
359
+ movie_release_year‘ equals to 1945, so we can use a WHERE clause to
360
+ express this condition. To name the movie titles, we select column 1
361
+ movie_title‘ from the table, which is named ‘movies‘. The user also
362
+ requires me to sort the listing by popularity descendingly, so we can
363
+ use a ORDER BY clause with DESCEND order. Finally, to give only 5 titles
364
+ , we can use LIMIT clause to limit the number of output rows.", "
365
+ thought_2": "The SQL query executed successfully and returned the
366
+ expected answer. Noticing that the output is given in Python list with
367
+ single-element tuple in it, we can extract the answer by putting the
368
+ elements in a JSON list. After that, I can commit my answer now."}
369
+ ‘‘‘
370
+
371
+ Example 2:
372
+
373
+ ‘‘‘json
374
+ {"evidence": "full name of the professor $=$ first_name, last_name; most number of students refers to MAX(COUNT(student_id));", "conversations": [{"from": "human", "value": "\n I will ask you a question, then you should operate the MySQL database with sql to answer the question.\n You must response in pure JSON format, you can put what you want to say in "thought" field.\n You MUST response in JSON format without any other comments:\n {"thought": "HERE IS YOUR THOUGHT", "sql": "HERE IS THE SQL YOU WANT TO EXECUTE"}\n If you want to commit your final answer, then use:\n {"thought": "HERE IS YOUR THOUGHT", "commit": ["ANSWER1", " ANSWER2", ...]}\n Your answer should be accurate. Your answer must be exactly the same as the correct answer.\n If the question is about modifying database, then your "commit" field can be anything.\n If your response cannot be interpreted by JSON loader, this question will be judged as fail immediately.\n Your input will be raw MySQL response, you have to deal with it by yourself.\n "}, {"from": "gpt", "value": "Ok ."}, {"from": "human", "value": "Find the full name and popularity of the professor who advises the most number of students.\nThere are 2 tables involved with this task. The name of the 1st table is prof, and the headers of this table are prof_id,gender,first_name,last_name,email, popularity,teachingability,graduate_from. The name of the 2nd table is RA, and the headers of this table are student_id,capability,prof_id, salary. "}, {"from": "gpt", "value": "{"thought": "[THOUGHT_1]", "sql": "SELECT T1.first_name, T1.last_name, T1.popularity FROM prof AS T1 INNER JOIN RA AS T2 ON T1.prof_id $=$ T2.prof_id GROUP BY T1.prof_id ORDER BY COUNT(T2.student_id) DESC LIMIT 1"}"}, {"from": "human", "value": "[(’ Bernhard’, ’Molen’, 3)]"}, {"from": "gpt", "value": "{"thought": "[ THOUGHT_2]", "commit": ["Bernhard", "Molen", 3]}"}]}
375
+
376
+ Your response should be:
377
+
378
+ ‘‘‘json
379
+
380
+ {"thought_1": "A full name is constructed of first name and last name, so I should SELECT columns ‘first_name‘, ‘last_name‘ and ‘popularity‘ from table ‘prof‘. To find out the professor who advises the most number of students, I should find the maximum count of students a professor advises. I can use INNER JOIN clause to match a professor with the students he advises. Then, using GROUP BY clause and COUNT function, I can calculate the number of students a professor advises. Finally, by using ORDER BY clause with DESC order and a LIMIT clause with limit size 1, I can pick out the row with maximum count, which is the expected answer to the question.", "thought_2": "The SQL query seems successful without any error and returned one row with three elements in it. Looking back at our analyze and SQL query, it gives the right answer to the question, so I should commit my answer now."}
381
+ ‘‘‘
382
+
383
+ Your response should only be in the JSON format above; THERE SHOULD BE NO OTHER CONTENT INCLUDED IN YOUR RESPONSE. Again, you, as well as the AI agent you are acting, should think step-by-step to solve the task gradually while keeping response brief.
384
+
385
+ # D PROMPT FOR EVALUATION
386
+
387
+ # D.1 ALFWORLD
388
+
389
+ # (Initial Prompt)
390
+
391
+ Interact with a household to solve a task. Imagine you are an intelligent agent in a household environment and your target is to perform actions to complete the task goal. At the beginning of your interactions, you will be given the detailed description of the current environment and your goal to accomplish. You should choose from two actions: "THOUGHT" or "ACTION". If you choose "THOUGHT", you should first think about the current condition and plan for your future actions , and then output your action in this turn. Your output must strictly follow this format: "THOUGHT: your thoughts. ACTION: your next action"; If you choose "ACTION", you should directly output the action in this turn. Your output must strictly follow this format: "ACTION: your next action". After your each turn, the environment will give you immediate feedback based on which you plan your next few steps. if the envrionment output "Nothing happened", that means the previous action is invalid and you should try more options.
392
+
393
+ Reminder:
394
+
395
+ 1. the action must be chosen from the given available actions. Any actions except provided available actions will be regarded as illegal. 2. Think when necessary, try to act directly more in the process.
396
+
397
+ # (Task Description)
398
+
399
+ Here is your task. {{current_observation}} Your task is to: {{task_description}}
400
+
401
+ # D.2 WEBSHOP
402
+
403
+ # (Initial Prompt)
404
+
405
+ You are web shopping.
406
+ I will give you instructions about what to do.
407
+ You have to follow the instructions.
408
+ Every round I will give you an observation, you have to respond an action based on the state and instruction.
409
+ You can use search action if search is available.
410
+ You can click one of the buttons in clickables.
411
+ An action should be of the following structure:
412
+ search[keywords]
413
+ click[value]
414
+ If the action is not valid, perform nothing.
415
+ Keywords in search are up to you, but the value in click must be a value in the list of available actions.
416
+ Remember that your keywords in search should be carefully designed. Your response should use the following format:
417
+
418
+ Thought: I think ...
419
+
420
+ Action: click[something]
421
+
422
+ # (Observation)
423
+
424
+ {% for observation in observations %}
425
+ {{observation}} [SEP]
426
+ {% endfor %}
427
+
428
+ # D.3 MIND2WEB
429
+
430
+ Noticed that the sample thoughts in (Liu et al., 2023) are relatively simple, we augmented them by GPT-4 to make the reasoning process better.
431
+
432
+ # ’’’
433
+
434
+ <html> <div> <div> <a tock home page /> <button id ${ } = 0$ book a reservation. toggle open> <span> Book a reservation </span> </button> <button book a reservation. toggle open> </button> </div> <div> <select id=1 type> < option reservations true> Dine in </option> <option pickup> Pickup </ option> <option delivery> Delivery </option> <option events> Events </ option> <option wineries> Wineries </option> <option all> Everything </ option> </select> <div id $= 2 >$ <p> Celebrating and supporting leading women shaking up the industry. </p> <span> Explore now </span> </div> </ div> </div> </html>
435
+
436
+ Based on the HTML webpage above, try to complete the following task: Task: Check for pickup restaurant available in Boston, NY on March 18, 5 pm with just one guest
437
+
438
+ Previous actions:
439
+
440
+ None
441
+
442
+ What should be the next action? Please select from the following choices (If the correct action is not in the page above, please select A. ’None of the above’):
443
+
444
+ A. None of the above
445
+ B. <button $\therefore d = 0$ book a reservation. toggle open> <span> Book a
446
+ C. <select $\dot { \iota } \mathrm { c l } = 1$ type> <option reservations true> Dine in </option> < option
447
+ D. <div i ${ \tt d } = 2 >$ <p> Celebrating and supporting leading women shaking up Thought: To check for a pickup restaurant, I would first need to select the relevant option from the dropdown menu to indicate my preference. The dropdown menu on the page is represented by the ‘<select>‘ element with the ID ‘id=1‘. Within this dropdown, there’s an ‘<option>‘ tag with the value ‘pickup‘, which is the appropriate option for this task. Answer: C.
448
+
449
+ Action: SELECT Value: Pickup
450
+
451
+ #
452
+
453
+ <html> <div> <main main> <section tabpanel> <div> <ul tablist> <li tab heading level 3 search and> </li> <li id=0 tab heading level 3 search and> <span> Hotel </span> </li> <li tab heading level 3 search and> </li $>$ <li tab heading level 3 search and> </li> </ul> <div tabpanel> <div id ${ \bf \Phi } = 1 >$ <div> <span> Dates\* </span> <button button clear dates /> </div> < div> <label> Travelers </label> <div> <p> 1 Adult </p> <button button> 1 Adult </button> <div dialog> <button button travel with a pet. this> < span> Travel with a pet </span> </button> <div> <button button clear all fields> Clear all </button> <button button> </button> </div> </div> </ div> </div> </div> </div> </div> </section> </main> <footer contentinfo> <div> ${ < } \mathrm { h } 3 >$ Stay Connected </h3> <ul id=2> <a mobile tools> </a> <a open united’s tiktok feed in> </a> <a open united’s facebook page in> </a> < a open united’s twitter feed in> </a> <a open united’s youtube page in> </a> <a open united’s instagram feed in> </a> <a open united’s linkedin profile in> </a> </ul> </div> </footer> </div> </html> ’’’
454
+
455
+ Based on the HTML webpage above, try to complete the following task:
456
+ Task: Compare the fare types to book a 1-adult ticket from Springfiels,
457
+ IL to Austin, TX for April 29th 2023
458
+ Previous actions:
459
+ [combobox] Enter your departing city, airport name, or airpor... -> TYPE
460
+ : SPRINGFIELD
461
+ [button] Springfield, IL, US (SPI) $- >$ CLICK
462
+ [combobox] Enter your destination city, airport name, or airp... $- >$ TYPE
463
+ : AUSTIN
464
+ [button] Austin, TX, US (AUS) $- >$ CLICK
465
+ What should be the next action? Please select from the following choices (If the correct action is not in the page above, please select A. ’None
466
+ of the above’):
467
+
468
+ A. None of the above B. <li id=0 tab heading level 3 search and> <span> Hotel C. <div id $= 1 >$ <div> <span> Dates\* </span> <button button clear dates D. <ul id $_ { 1 } = 2 >$ <a mobile tools> </a> <a open united’s tiktok
469
+
470
+ Thought: To compare fare types for a specific date, I would need to select or input the travel date. Looking at the provided HTML webpage, there’s a section with the label Dates\* which suggests it might be related to date selection. However, the corresponding button next to Dates $\star$ only mentions clear dates and does not provide an option to select or input a new date. As the required functionality is not explicitly visible in the given snippet, the most appropriate action seems to be none of the provided options.
471
+ Answer: A.
472
+
473
+ ’’’
474
+
475
+ <html> <div> <nav main menu> <ul> <li> <div button> Car Sales </div> < div id $\mathord { \kern - delimiterspace } = 0 >$ <div> <div> <div> Buy A Car </div> <div> Plan Your Purchase </ div> </div> <div> <h4> Its Tax Refund Time. Treat Yourself to an Upgrade . </h4> <p> With a variety of options, invest your refund in what you really want - a quality, used vehicle from Enterprise. </p> <a> View Inventory </a> </div> </div> </div> </li> <div id $= 1 >$ Enterprise Fleet Management </div> </ul> </nav> <div region> <button id $^ { = 2 }$ selected pickup date 03/19/2023> <span> <span> 19 </span> <div> <span> Mar </span> $<$ span> 2023 </span> </div> </span> </button> </div> </div> </html> ’’’
476
+
477
+ Based on the HTML webpage above, try to complete the following task:
478
+ Task: Find a mini van at Brooklyn City from April 5th to April 8th for a 22 year old renter.
479
+ Previous actions:
480
+ [searchbox] Pick-up & Return Location (ZIP, City or Airport) (... ->
481
+ TYPE: Brooklyn
482
+ [option] Brooklyn, NY, US Select $- >$ CLICK
483
+ What should be the next action? Please select from the following choices (If the correct action is not in the page above, please select A. ’None of the above’):
484
+ A. None of the above
485
+ B. <div $\dot { \mathsf { I } } \mathsf { d } = 0 >$ <div> <div> <div> Buy A Car </div> <div>
486
+ C. <div $\dot { \mathsf { 1 } } \mathsf { d } = \mathsf { 1 } >$ Enterprise Fleet Management </div>
487
+ D. <button id=2 selected pick-up date 03/19/2023> <span> <span> 19 </
488
+
489
+ span>
490
+
491
+ Thought: To proceed with the task, after setting the pick-up location to Brooklyn, I need to specify the pick-up date. Looking at the provided HTML, there’s a button with ID id=2 which mentions a pick-up date of 03/19/2023. This is the logical next step since I need to modify the date to match the specified timeframe of April 5th to April 8th.
492
+ Answer: D.
493
+ Action: CLICK
494
+
495
+ ,{{webpage_html}}
496
+
497
+ Based on the HTML webpage above, try to complete the following task:
498
+ Task: {{task_description}}
499
+ Previous actions:
500
+
501
+ {% for action in previous_actions %} {{action.target_element}} $- >$ {{action.action}} {% endfor %}
502
+
503
+ # D.4 KNOWLEDGE GRAPH
504
+
505
+ # (Initial Prompt)
506
+
507
+ You are an agent that answers questions based on the knowledge stored in a knowledge base. To achieve this, you can use the following tools to query the KB.
508
+
509
+ 1. get_relations(variable: var) $- >$ list of relations
510
+ A variable can be either an entity or a set of entities (i.e., the result of a previous query). This function helps to navigate all
511
+ relations in the KB connected to the variable, so you can decide which relation is the most useful to find the answer to the question.
512
+ A simple use case can be ’get_relations(Barack Obama)’, which finds all relations/edges starting from the entity Barack Obama.
513
+ The argument of get_relations should always be an entity or a variable ( e.g., $\# 0$ ) and not anything else.
514
+
515
+ 2. get_neighbors(variable: var, relation: str) $- >$ variable Given a variable, this function returns all entities connected to the variable via the given relation. Note that, get_neighbors() can only be used after get_relations() is used to find a set of viable relations. A simple use case can be ’get_neighbors(Barack Obama, people.person. profession)’, which returns the profession of Obama in Freebase.
516
+
517
+ 3. intersection(variable1: var, variable2: var) -> variable Given two variables, this function returns the intersection of the two variables. The two variables MUST be of the same type!
518
+
519
+ 4. get_attributes(variable: var) $- >$ list of attributes This function helps to find all numerical attributes of the variable. Please only use it if the question seeks for a superlative accumulation (i.e., argmax or argmin).
520
+
521
+ 5. argmax(variable: var, attribute: str) $- >$ variable
522
+ Given a variable, this function returns the entity with the maximum value of the given attribute. It can only be used after get_attributes() is used to find a set of viable attributes.
523
+
524
+ A simple use case can be ’argmax(variable, age)’, which returns the oldest entity belonging to the variable.
525
+
526
+ 6. argmin(variable: var, attribute: str) $- >$ variable
527
+ Given a variable, this function returns the entity with the minimum value of the given attribute. It can only be used after get_attributes() is used to find a set of viable attributes.
528
+ A simple use case can be ’argmin(variable, age)’, which returns the youngest entity belonging to the variable. 7. count(variable: var) $- >$ int
529
+ Given a variable, this function returns the number of entities belonging to the variable.
530
+
531
+ After a variable is produced along the process, you need to judge whether a variable is the final answer to the question. Each variable is represented as an id starting from 0. For example, #0 is the first variable, #1 is the second variable, and so on.
532
+
533
+ Once you find the answer, respond with ’Final Answer: #id’, where id is the id of the variable that you think is the final answer. For example, if you think #3 is the final answer, you MUST respond with ’Final Answer : #3’.
534
+
535
+ You can only take ONE action at a time!! After you get the observation from its execution, you can take another action. You can take at most 15 actions to find the answer to the question.
536
+
537
+ # (Task Description)
538
+
539
+ Question: {{question_description}} Entities: {{entities}}
540
+
541
+ # D.5 OPERATING SYSTEM
542
+
543
+ # (Initial Prompt)
544
+
545
+ You are an assistant that will act like a person, I’will play the role of linux(ubuntu) operating system. Your goal is to implement the operations required by me or answer to the question proposed by me. For each of your turn, you should first think what you should do, and then take exact one of the three actions: "bash", "finish" or "answer".
546
+
547
+ 1. If you think you should execute some bash code, take bash action, and you should print like this:
548
+
549
+ Think: put your thought here.
550
+
551
+ Act: bash
552
+
553
+ ‘‘‘bash
554
+ \# put your bash code here
555
+ 1
556
+
557
+ 2. If you think you have finished the task, take finish action, and you should print like this:
558
+
559
+ Think: put your thought here.
560
+
561
+ Act: finish
562
+
563
+ 3. If you think you have got the answer to the question, take answer action, and you should print like this:
564
+
565
+ Think: put your thought here.
566
+
567
+ Act: answer(Your answer to the question should be put in this pair of parentheses)
568
+
569
+ If the output is too long, I will truncate it. The truncated output is not complete. You have to deal with the truncating problem by yourself. Attention, your bash code should not contain any input operation. Once again, you should take only exact one of the three actions in each turn.
570
+
571
+ # (Observation)
572
+
573
+ The output of the os: {{os_output}}
574
+
575
+ # D.6 DATABASE
576
+
577
+ # (Initial Prompt)
578
+
579
+ I will ask you a question, then you should help me operate a MySQL database with SQL to answer the question.
580
+
581
+ You have to explain the problem and your solution to me and write down your thoughts.
582
+
583
+ After thinking and explaining thoroughly, every round you can choose to operate or to answer.
584
+
585
+ your operation should be like this:
586
+
587
+ Action: Operation
588
+ ‘‘‘sql
589
+ SELECT $\star$ FROM table WHERE condition; ‘‘‘
590
+
591
+ You MUST put SQL in markdown format without any other comments. Your SQL should be in one line.
592
+
593
+ Every time you can only execute one SQL statement. I will only execute the statement in the first SQL code block. Every time you write a SQL, I will execute it for you and give you the output.
594
+
595
+ If you are done operating, and you want to commit your final answer, then write down:
596
+
597
+ Action: Answer
598
+
599
+ Final Answer: ["ANSWER1", "ANSWER2", ...]
600
+ DO NOT write this pattern unless you are sure about your answer. I expect an accurate and correct answer.
601
+ Your answer should be accurate. Your answer must be exactly the same as the correct answer.
602
+ If the question is about modifying the database, then after done operation, your answer field can be anything.
603
+ If your response cannot match any pattern I mentioned earlier, you will be judged as FAIL immediately.
604
+ Your input will be raw MySQL response, you have to deal with it by yourself.
605
+
606
+ # D.7 SCIWORLD
607
+
608
+ # (Initial Prompt)
609
+
610
+ Interact with a household to solve a task. Each turn, you can choose from one of the following options:
611
+
612
+ 1. Think: You could think step-by-step to tell your reasoning and planning to solve the task, which will help you handle the task easier. 2. Action: You could interact with the environment freely to solve the task, but remember to refer to your thought and act accordingly. Prepend your action with "Think: " or "Action: ", e.g. "Think: Now I have picked up the object. Next, I need to move to the location of the answer box." or "Action: go to kitchen".
613
+ Exactly only one option could be chosen in a turn.
614
+
615
+ # D.8 HOTPOTQA
616
+
617
+ # (Few-shot)
618
+
619
+ This task involves solving a question-answering exercise through a series of interleaved Thought, Action, and Observation steps. Any thought before the action is allowed, and action can be one of the following three types:
620
+
621
+ (1) Search[entity]: This action involves searching for a specific entity on Wikipedia and returning the first paragraph of the entity’s page if it exists. If the entity does not have a Wikipedia page, the assistant should suggest similar entities to search for.
622
+
623
+ (2) Lookup[keyword]: This action involves searching for the next sentence containing the specified keyword in the most recent passage successfully found by the Search action.
624
+
625
+ (3) Finish[answer]: This action concludes the task by providing the answer to the question.
626
+
627
+ You can take as many steps as necessary to answer the question. The key is to ensure that each step logically follows the previous one and contributes to the final answer. The task aims to emulate a reasoning process that yields accurate and comprehensive answers.
628
+
629
+ Question: Musician and satirist Allie Goertz wrote a song about the "The Simpsons" character Milhouse, who Matt Groening named after who?
630
+
631
+ Thought 1: The question simplifies to "The Simpsons" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.
632
+
633
+ Action 1: Search[Milhouse]
634
+
635
+ Observation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.
636
+
637
+ Thought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up "named after".
638
+
639
+ Action 2: Lookup[named after]
640
+
641
+ Observation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous.
642
+
643
+ Thought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.
644
+
645
+ Action 3: Finish[Richard Nixon]
646
+
647
+ Question: Were Pavel Urysohn and Leonid Levin known for the same type of work?
648
+
649
+ Thought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.
650
+
651
+ Action 1: Search[Pavel Urysohn]
652
+
653
+ Observation 1: Pavel Samuilovich Urysohn (February 3, 1898 August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.
654
+
655
+ Thought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and find its type of work.
656
+
657
+ Action 2: Search[Leonid Levin]
658
+
659
+ Observation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist.
660
+
661
+ Thought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn and Leonid Levin have the same type of work.
662
+
663
+ Action 3: Finish[yes]
664
+
665
+ # D.9 MINIWOB $^ { + + }$
666
+
667
+ # (Initial Prompt)
668
+
669
+ You are an agent embarking on a computer task. Each turn, you will be provided a task and an accessibility tree describing what is on the screen now, and you should either devise a overall plan to solve this task or to provide an instruction to execute. The plan could be multistep, and each step should strictly corresponds to one instruction to execute. When devising a plan to execute, list the steps in order and precede each step with a numerical index starting from 1, e.g. "1." or "2.", and when executing, follow the plan strictly. When asked to provide an action to execute, refer strictly to the regular expression to ensure that your action is valid to execute.
670
+
671
+ We have an autonomous computer control agent that can perform atomic instructions specified by natural language to control computers. There are {{len(available_actions)}} types of instructions it can execute.
672
+
673
+ {{available_actions}}
674
+
675
+ Below is the HTML code of the webpage where the agent should solve a task.
676
+
677
+ {{webpage_html}}
678
+
679
+ Example plans) {{example_plans}}
680
+
681
+ Current task: {{current_task}} plan:
682
+
683
+ # (Criticizing)
684
+
685
+ Find problems with this plan for the given task compared to the example plans.
686
+
687
+ # (Plan Refining)
688
+
689
+ Based on this, what is the plan for the agent to complete the task?
690
+
691
+ # (Action)
692
+
693
+ We have an autonomous computer control agent that can perform atomic instructions specified by natural language to control computers. There are {{len(available_actions)}} types of instructions it can execute.
694
+
695
+ {{available_actions}}
696
+
697
+ Below is the HTML code of the webpage where the agent should solve a task.
698
+ {{webpage_html}}
699
+
700
+ Current task: {{current_task}}
701
+
702
+ Here is a plan you are following now. The plan for the agent to complete the task is:
703
+
704
+ {{plan}}
705
+
706
+ We have a history of instructions that have been already executed by the autonomous agent so far.
707
+ {{action_history}}
708
+
709
+ Based on the plan and the history of instructions executed so far, the next proper instruction to solve the task should be ‘
710
+
711
+ # D.10 REWOO
712
+
713
+ # (Planner)
714
+
715
+ For the following tasks, make plans that can solve the problem step-bystep. For each plan, indicate which external tool together with tool input to retrieve evidence. You can store the evidence into a variable # E that can be called by later tools. (Plan, #E1, Plan, #E2, Plan, ...)
716
+
717
+ Tools can be one of the following:
718
+ {% for tool in available_tools %}
719
+ {{tool.description}}
720
+ {% endfor %}
721
+ For Example:
722
+ {{one_shot_example}}
723
+
724
+ Begin! Describe your plans with rich details. Each Plan should be followed by only one #E.
725
+
726
+ {{task_description}}
727
+
728
+ # (Solver)
729
+
730
+ Solve the following task or problem. To assist you, we provide some plans and corresponding evidences that might be helpful. Notice that some of these information contain noise so you should trust them with caution.
731
+
732
+ {{task_description}}
733
+ {% for step in plan %}
734
+ Plan: {{step.plan}}
735
+ Evidence:
736
+ {{step.evidence}}
737
+ {% endfor %}
738
+
739
+ Now begin to solve the task or problem. Respond with the answer directly with no extra words.
740
+
741
+ {{task_description}}
742
+
743
+ # D.11 DIGITAL CARD GAME
744
+
745
+ # (Initial Prompt)
746
+
747
+ This is a two-player battle game with four pet fish in each team. Each fish has its initial health, attack power, active ability, and passive ability.
748
+
749
+ All fish’s identities are initially hidden. You should guess one of the enemy fish’s identities in each round. If you guess right, the enemy fish’s identity is revealed, and each of the enemy’s fish will get 50 damage. You can only guess the identity of the live fish.
750
+
751
+ The victory condition is to have more fish alive at the end of the game.
752
+
753
+ The following are the four types of the pet fish:
754
+
755
+ {’spray’: {’passive’: "Counter: Deals 30 damage to attacker when a teammate’s health is below $30 \%$ ", ’active’: ’AOE: Attacks all enemies for $3 5 \%$ of its attack points.’}, ’flame’: {’passive’: "Counter: Deals 30 damage to attacker when a teammate’s health is below $30 \%$ . ", ’active’: " Infight: Attacks one alive teammate for 75 damage and increases your own attack points by 140. Notice! You can’t attack yourself or dead teamate !"}, ’eel’: {’passive’: ’Deflect: Distributes $70 \%$ damage to teammates and takes 30% when attacked. Gains 40 attack points after taking 200 damage accumulated. ’, ’active’: ’AOE: Attacks all enemies for $3 5 \%$ of your attack points.’}, ’sunfish’: {’passive’: ’Deflect: Distributes 70% damage to teammates and takes $30 \%$ when attacked. Gains 40 attack points after taking 200 damage accumulated. ’, ’active’: "Infight: Attacks one alive teammate for 75 damage and increases your own attack points by 140. Notice! You can’t attack yourself or dead teamate!"}}
756
+
757
+ Play the game with me. In each round, you should output your thinking process, and return your move with following json format:
758
+
759
+ {’guess_type’: "the enemy’s fish type you may guess", ’target_position’: "guess target’s position, you must choose from [0,3]"}
760
+
761
+ Notice! You must return your move in each round. Otherwise, you will be considered defeated.
762
+
763
+ # (Action)
764
+
765
+ Previous Guess: {{previous_guess}}
766
+ Live Enemy Fish: {{live_enemy_fish}}
767
+ Enemy’s previous action: {{enemy_previous_action}}
768
+ Enemy’s previous triggered passive ability: {{enemy_passive_ability}}
769
+
770
+ Please output your guess.
771
+
772
+ # D.12 MMLU
773
+
774
+ # (5-shot)
775
+
776
+ The following is a multiple-choice question about {{subject}}. Please choose the most suitable one among A, B, C and D as the answer to this question.
777
+
778
+ Question: {{Question1}} Answer: {{Answer1}}
779
+
780
+ Question: {{Question2}} Answer: {{Answer2}}
781
+
782
+ Question: {{Question3}} Answer: {{Answer3}}
783
+
784
+ Question: {{Question4}} Answer: {{Answer4}}
785
+
786
+ Question: {{Question5}} Answer: {{Answer5}}
787
+
788
+ Question: {{Question}} Answer:
789
+
790
+ # D.13 GSM8K
791
+
792
+ # (8-shot)
793
+
794
+ Q: In 2004, there were 60 kids at a cookout. In 2005, half the number of kids came to the cookout as compared to 2004. In 2006, 2/3 as many kids came to the cookout as in 2005. How many kids came to the cookout in 2006? Let’s think step by step
795
+ A: In 2005, $6 0 / 2 { = } 3 0$ kids came to the cookout.
796
+ In 2006, $3 0 / 3 \times 2 = 2 0$ kids came to the cookout.
797
+ The answer is 20 Q: Zilla spent 7% of her monthly earnings on rent, half of it on her other monthly expenses, and put the rest in her savings. If she spent $\$ 133$ on her rent, how much does she deposit into her savings account in a month? Let’s think step by step
798
+ A: Since $\$ 123$ is equal to $7 \%$ of her earnings, then 1% is equal to $\$ 12347$ $= \quad \$ 19$ .
799
+ The total monthly earning of Zilla is represented by $100 \%$ , so $\$ 19\times100$ $= \$ 1900$ is her monthly earnings.
800
+ So, $\$ 1900/2 =\$ 950$ is spent on her other monthly expenses. The total amount spent on the rent and other monthly expenses is $\$ 123,4$ $\$ 950 =91083$ .
801
+ Hence, she saves $\$ 1900-91083 =$ per month.
802
+ The answer is 817
803
+ Q: If Buzz bought a pizza with 78 slices at a restaurant and then decided to share it with the waiter in the ratio of 5:8, with Buzz’s ratio being 5, what’s twenty less the number of slices of pizza that the waiter ate? Let’s think step by step
804
+ A: The total ratio representing the slices of pizza that Buzz bought is $5 + 8 = 1 3$
805
+ If he shared the slices of pizza with the waiter, the waiter received a fraction of 8/13 of the total number of slices, which totals $8 / 1 3 \ \star \ 7 8 \ =$ 48 slices
806
+ Twenty less the number of slices of pizza that the waiter ate is $4 8 - 2 0 \ =$ 28
807
+ The answer is 28
808
+ Q: Jame gets a raise to $\$ 20$ per hour and works 40 hours a week. His old job was $\$ 16$ an hour for 25 hours per week. How much more money does he make per year in his new job than the old job if he works 52 weeks a year? Let’s think step by step
809
+ A: He makes $2 0 + 4 0 = 5 8 0 0$ per week
810
+ He used to make $1 6 \times 2 5 = 5 4 0 0$ per week
811
+ So his raise was $8 0 0 - 4 0 0 = 5 4 0 0$ per week
812
+ So he makes $4 0 0 \star 5 2 = \$ 20$ ,800 per year more
813
+ The answer is 20800
814
+ Q: Mr. Gardner bakes 20 cookies, 25 cupcakes, and 35 brownies for his second-grade class of 20 students. If he wants to give each student an equal amount of sweet treats, how many sweet treats will each student receive? Let’s think step by step
815
+ A: Mr. Gardner bakes a total of $2 0 + 2 5 + 3 5 = 8 0$ sweet treats
816
+ Each student will receive $8 0 / 2 0 = 4$ sweet treats
817
+ The answer is 4
818
+ Q: A used car lot has 24 cars and motorcycles (in total) for sale. A third of the vehicles are motorcycles, and a quarter of the cars have a spare tire included. How many tires are on the used car lot’s vehicles in all? Let’s think step by step
819
+ A: The used car lot has $2 4 / 3 = 8$ motorcycles with 2 tires each. The lot has $2 4 - 8 = 1 6$ cars for sale
820
+ There are 16 / $4 \ = \ 4$ cars with a spare tire with 5 tires each.
821
+ The lot has $1 6 ~ - ~ 4 ~ = ~ 1 2$ cars with 4 tires each.
822
+ Thus, the used car lot’s vehicles have $8 \star 2 + 4 \star 5 + 1 2 \star 4 = 1 6 + 2 0$ $+ \quad 4 8 \ = \ 8 4$ tires in all.
823
+ The answer is 84
824
+ Q: Norma takes her clothes to the laundry. She leaves 9 T-shirts and twice as many sweaters as T-shirts in the washer. When she returns she finds 3 sweaters and triple the number of T-shirts. How many items are missing? Let’s think step by step
825
+ A: Norma left 9 T-shirts And twice as many sweaters, she took $9 \ \star \ 2 = \ 1 8$ sweaters
826
+ Adding the T-shirts and sweaters, Norma left $9 + 1 8 = 2 7$ clothes
827
+ When she came back, she found 3 sweaters And triple the number of Tshirts, she found $3 \times 3 = 9$ T-shirts
828
+ Adding the T-shirts and sweaters, Norma found $3 + 9 = 1 2$ clothes
829
+ Subtracting the clothes she left from the clothes she found, $2 7 - 1 2 =$ 15 clothes are missing
830
+ The answer is 15
831
+ Q: Adam has an orchard. Every day for 30 days he picks 4 apples from his orchard. After a month, Adam has collected all the remaining apples, which were 230. How many apples in total has Adam collected from his orchard? Let’s think step by step
832
+ A: During 30 days Adam picked $4 \ \star \ 3 0 \ = \ 1 2 0$ apples.
833
+ So in total with all the remaining apples, he picked $1 2 0 + 2 3 0 = 3 5 0$ apples from his orchard.
834
+
835
+ Q: {{Question}} A:
parse/test/OqlmgmS4Wr/OqlmgmS4Wr_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/OqlmgmS4Wr/OqlmgmS4Wr_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/OqlmgmS4Wr/OqlmgmS4Wr_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/RXFVcynVe1/RXFVcynVe1.md ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HARNESSING EXPLANATIONS: LLM-TO-LM INTERPRETER FOR ENHANCED TEXT-ATTRIBUTED GRAPH REPRESENTATION LEARNING
2
+
3
+ Xiaoxin $\mathbf { H e } ^ { 1 }$ , Xavier Bresson1, Thomas Laurent2, Adam Perold3, Yann LeCun4,5, Bryan Hooi1
4
+
5
+ 1National University of Singapore, 2Loyola Marymount University
6
+ 3Element, Inc., 4New York University, 5Meta AI
7
+ {xiaoxin, xaviercs, bhooi}@comp.nus.edu.sg, tlaurent@lmu.edu
8
+ ap@elementresearch.com, yann@cs.nyu.edu
9
+
10
+ # ABSTRACT
11
+
12
+ Representation learning on text-attributed graphs (TAGs) has become a critical research problem in recent years. A typical example of a TAG is a paper citation graph, where the text of each paper serves as node attributes. Initial graph neural network (GNN) pipelines handled these text attributes by transforming them into shallow or hand-crafted features, such as skip-gram or bag-of-words features. Recent efforts have focused on enhancing these pipelines with language models (LMs), which typically demand intricate designs and substantial computational resources. With the advent of powerful large language models (LLMs) such as GPT or Llama2, which demonstrate an ability to reason and to utilize general knowledge, there is a growing need for techniques which combine the textual modelling abilities of LLMs with the structural learning capabilities of GNNs. Hence, in this work, we focus on leveraging LLMs to capture textual information as features, which can be used to boost GNN performance on downstream tasks. A key innovation is our use of explanations as features: we prompt an LLM to perform zero-shot classification, request textual explanations for its decision-making process, and design an LLM-to-LM interpreter to translate these explanations into informative features for downstream GNNs. Our experiments demonstrate that our method achieves state-of-the-art results on well-established TAG datasets, including Cora, PubMed, ogbn-arxiv, as well as our newly introduced dataset, tape-arxiv23. Furthermore, our method significantly speeds up training, achieving a 2.88 times improvement over the closest baseline on ogbn-arxiv. Lastly, we believe the versatility of the proposed method extends beyond TAGs and holds the potential to enhance other tasks involving graph-text data 1.
13
+
14
+ # 1 INTRODUCTION
15
+
16
+ Many real-world graphs possess textual information, and are often referred to text-attributed graphs (Yang et al., 2021). In TAGs, nodes typically represent text entities, such as documents or sentences, while edges signify relationships between these entities. For example, the ogbn-arxiv dataset (Hu et al., 2020a) represents a citation network in TAG form, where each node corresponds to a paper, with its title and abstract serving as node attributes. More generally, the combination of textual attributes with graph topology provides a rich source of information, significantly enhancing representation learning for important applications, such as text classification (Yang et al., 2015; Wang et al., 2016; Yasunaga et al., 2017; Chien et al., 2021; Zhao et al., 2022), recommendation systems (Zhu et al., 2021), social networks, and fake news detection (Liu et al., 2019).
17
+
18
+ Representation learning on TAGs. Prior research has explored various approaches for representation learning on TAGs. The standard GNN pipeline (illustrated in Figure 1 in light yellow), first encodes the textual attributes of each node using shallow or hand-crafted features such as skipgram (Mikolov et al., 2013) or bag-of-words (BoW) (Harris, 1985) (refer to Table 9). The result
19
+
20
+ # Overview of TAPE: Title, Abstract, Prediction & Explanation
21
+
22
+ Step 1: Node Feature Extraction
23
+
24
+ # Prediction: cs.CV, cs.IR, cs.CL, cs.LG, cs.AI.
25
+
26
+ Abstract: Text in curve orientation, despite being one of the common text orientations in real world environment... Title: Total Text A Comprehensive Dataset For Scene Text Detection And Recognition.
27
+
28
+ Question: Which arXiv CS sub-category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely, in the form "cs.XX", and provide your reasoning. Answer:
29
+
30
+ Explanation: The paper is about a new dataset for scene text detection and recognition, which is a topic related to computer vision (cs.CV). The paper also mentions the use of deep learning techniques such as DeconvNet, which falls under the sub-category of artificial intelligence (cs.AI). The dataset is annotated and involves text recognition, which could also fall under the sub-categories of information retrieval (cs.IR) and natural language processing (cs.CL). Finally, the paper discusses the effectiveness of different solutions, which could be evaluated using machine learning techniques, falling under the sub-category of machine learning (cs.LG).
31
+
32
+ ![](images/89f2423bae0097c8ba24ae4d5f6dd106d65b79b999e30cb02964eb33407ef2d1.jpg)
33
+ Step 2: Downstream Tasks on TAGs
34
+ Figure 1: Our framework leverages large language models (LLMs) to enhance representation learning on TAGs. First, textual attributes of each node, i.e., title and abstract, are wrapped in a custom prompt (green box) to query the LLM, here GPT-3.5 (Brown et al., 2020), which generates a ranked prediction list and explanation (yellow box). Next, the original text, predictions, and explanation are used to fine-tune a language model (LM), here DeBERTa (He et al., 2021), and then transformed into vectorial node features. Finally, these enriched node features, i.e., $h _ { \mathrm { o r i g } }$ , $h _ { \mathrm { e x p l } }$ and $h _ { \mathrm { p r e d } }$ , are used in any downstream GNN, e.g., RevGAT (Li et al., 2021) to predict unknown node classes.
35
+
36
+ ing node features are then used as input for a GNN. For instance, the Open Graph Benchmark (OGB) (Hu et al., 2020a) generated BoW and skip-gram (Mikolov et al., 2013) features for the ogbn-products and ogbn-arxiv datasets respectively. These processed features are readily available within popular graph libraries, such as PyTorch Geometric (PyG) (Fey & Lenssen, 2019) and Deep Graph Library (DGL) (Wang et al., 2019), and have been widely used by the graph community. However, these shallow text embeddings are limited in the complexity of the semantic features they can capture, especially when compared to approaches based on multi-layer LMs.
37
+
38
+ LM-based pipeline for TAGs. Recent works have therefore focused on designing LM-based techniques to better capture the context and nuances of text within TAGs (Chien et al., 2021; Zhao et al., 2022; Dinh et al., 2022). In this approach, pre-trained LMs are fine-tuned and used to generate node embeddings that are tailored to the specific TAG tasks (depicted in Figure 1 in light gray). For example, Chien et al. (2021) fine-tuned an LM using a neighborhood prediction task, while Zhao et al. (2022) fine-tuned an LM to predict the label distribution from a GNN’s outputs. LM-based models have achieved state-of-the-art (SOTA) results in node classification on ogbn-arxiv and ogbn-products (Zhao et al., 2022). However, these works typically entail intricate designs and demand substantial computational resources. Furthermore, for scalability reasons, existing works mostly rely on relatively small LMs, such as BERT (Devlin et al., 2018) and DeBERTa (He et al., 2021), and thus lack the complex reasoning abilities associated with larger language models.
39
+
40
+ Large Language Models. The advent of large pre-trained models, exemplified by GPT (Brown et al., 2020), has revolutionized the field of language modeling. LLMs have notably enhanced performance across various natural language processing (NLP) tasks, and enabled sophisticated language processing capabilities such as complex and zero-shot reasoning. Furthermore, scaling laws (Kaplan et al., 2020) have revealed predictable rules for performance improvements with model and training data size. Additionally, LLMs have exhibited “emergent abilities” that were not explicitly trained for, such as arithmetic, multi-step reasoning and instruction following (Wei et al., 2022). While LLMs have found new success in domains like computer vision (Tsimpoukelli et al., 2021), their potential benefits when applied to TAG tasks remain largely uncharted. This presents an exciting and promising avenue for future research, and it is precisely this untapped potential that we aim to explore in this work.
41
+
42
+ LMs vs. LLMs. In this paper, we make a clear distinction between “LMs” and “LLMs”. We use LMs to refer to relatively small language models that can be trained and fine-tuned within the constraints of an academic lab budget. We refer to LLMs as very large language models that are capable of learning significantly more complex linguistic patterns than LMs, such as GPT-3/4. These models typically have tens or hundreds of billions of parameters and require substantial computational resources to train and use, e.g., GPT-3 was trained on a supercomputer with 10,000 GPUs. The size and complexity of recent LLMs have raised concerns about their scalability, as they can be too large even to run inference on the machines typically available within academic research labs. To address this issue, LLMs are often made accessible through language modeling as a service (LMaaS) (Sun et al., 2022). This approach enables developers to harness the power of LLMs without necessitating extensive computational resources or specialized expertise. In the context of this paper, one of our primary objectives is to extract information from an LLM in a LMaaS-compatible manner. As a result, we do not require fine-tuning the LLM or extracting its logits; rather, we focus solely on obtaining its output in textual form. In contrast, existing LM-based techniques (Chien et al., 2021; Zhao et al., 2022; Dinh et al., 2022) are not directly compatible with LLMs, as they require finetuning of LMs, as well as accessing their latent embeddings or logits, which GPT-3/4 do not provide. Consequently, to the best of our knowledge, the use of LLMs in TAG tasks remains unexplored.
43
+
44
+ Preliminary study. To assess the potential of LLMs in enhancing representation learning for TAGs, we conducted an initial investigation into leveraging GPT-3.5 for zero-shot classification on the ogbn-arxiv dataset. Using task-specific prompts consisting of paper titles, abstracts, and questions, GPT-3.5 achieved a promising accuracy of $7 3 . 5 \%$ , along with high-quality text explanations, surpassing several fully trained GNN baselines like RevGAT (Li et al., 2021) with OGB features $7 0 . 8 \%$ accuracy), but falling short of the SOTA accuracy of $7 6 . 6 \%$ (Zhao et al., 2022).
45
+
46
+ The present work: LLM augmentation using explanations. We introduce a novel framework that leverages LLMs to improve representation learning on TAGs. A key innovation is the concept of explanations as features. By prompting a powerful LLM to explain its predictions, we extract its relevant prior knowledge and reasoning steps, making this information digestible for smaller models, akin to how human experts use explanations to convey insights. To illustrate this concept further, observe in Figure 1 that the explanations (in the yellow box) highlight and expand upon key crucial information from the text, such as “deep learning techniques such as DeconvNet,” and the relationship between text recognition and information retrieval. These explanations draw from the LLM’s general knowledge and serve as valuable features for enhancing subsequent TAG pipeline phases. In practice, we design a tailored prompt to query an LLM such as GPT or Llama2 to generate both a ranked prediction list and a textual explanation for its predictions. These predictions and explanations are then transformed into informative node features through fine-tuning a smaller LM such as DeBERTa (He et al., 2021) for the target task, providing tailored features for any downstream GNNs. This smaller model acts as an interpreter, facilitating seamless communication between the LLM (handling text) and the GNN (managing vectorial representation).
47
+
48
+ Our contributions are summarized as follows:
49
+
50
+ • Novel LMaaS-compatible approach. We propose the first LMaaS-compatible approach, to the best of our knowledge, for leveraging LLMs to enhance representation learning on TAGs. Our innovations involve extracting explanations from an LLM, here GPT-3.5 and Llama2, and subsequently employing an LLM-to-LM interpreter to translate textual explanations into enriched node vector representations for downstream GNNs. Our approach improves modularity and efficiency compared to prior $_ { \mathrm { L M + G N N } }$ models.
51
+
52
+ • SOTA performance. Extensive experiments demonstrate that our method significantly boost the performance of various GNN models across diverse datasets. Notably, we achieve top-1 performance on ogbn-arxiv with significantly lower computation time, i.e., $2 . 8 8 \times$ faster than GLEM, and also excel in the TAG versions of PubMed and Cora datasets.
53
+
54
+ • Data contribution. We provide open-source access to our codes, pre-trained networks and enriched features. Additionally, recognizing the absence of raw text data for Cora and PubMed in common repositories (e.g., PyG, DGL), we have collected and released these datasets in TAG format. Furthermore, we introduce the new tape-arxiv23 citation graph dataset, extending beyond GPT-3’s knowledge cutoff, i.e., Sept. 2021. These datasets can serve as valuable resources for the NLP and GNN research community.
55
+
56
+ ![](images/f2bbfda5eba33a390178e7a0c5f6afce6811cb046b59f2829e17fb26b9825297.jpg)
57
+ Figure 2: The performance trade-off between node classification accuracy and total training time on ogbn-arxiv (Hu et al., 2020a) for various training approaches that combine language models (LMs) and graph neural networks (GNNs). The experiment employs DeBERTa-base (He et al., 2021) as the LM backbone and RevGAT (Li et al., 2021) as the GNN backbone, with the size of the marker indicating the number of parameters.
58
+
59
+ # 2 RELATED WORK
60
+
61
+ Shallow embedding pipeline for TAGs. In the context of learning representations on TAGs, a common approach involves combining graph-based learning with language modeling techniques. One prevalent strategy is to transform text attributes into shallow or hand-crafted features, such as skip-gram (Mikolov et al., 2013) or BoW (Harris, 1985) features. Detailed information is available in Table 9. These engineered features can then be fed as inputs to a graph-based learning algorithm, such as a graph convolutional network (GCN) (Kipf & Welling, 2016), which learns embeddings capturing the graph structure while incorporating the extracted text features. Shallow embedding methods are widely used in the graph community due to their simplicity and computational efficiency, such as for designing GNN architectures (Velickovi ˇ c et al., 2017; Chiang et al., 2019; ´ Velickovic et al., 2019; Zhang et al., 2021) or benchmarking graph learning (Yang et al., 2016; Hu et al., 2020a). However, they may have limitations in capturing complex semantic relationships and fully leveraging the richness of text attributes, particularly in scenarios involving intricate semantic relationships and contextual information.
62
+
63
+ LM-based pipeline for TAGs. To overcome the limitations of shallow embedding approaches, researchers have explored deep embedding techniques by fine-tuning pre-trained LMs, such as BERT (Devlin et al., 2018), to generate node embeddings that are specifically adapted to the domain and context of the TAGs. These deep embeddings effectively capture the semantic richness of text attributes, leading to improved performance on various TAG-related tasks. Integrating LM-based embeddings and graph-based learning can be done through different approaches. One approach is to use a cascaded architecture, where the node features are first encoded independently by the LMs, and then fed into GNN models. This representation paradigm has been widely adopted in subsequent works, such as TextGNN (Zhu et al., 2021), GIANT (Chien et al., 2021), GPT-GNN (Hu et al., 2020b), SimTeg (Duan et al., 2023), as well as in studies related to knowledge graphs (Yasunaga et al., 2021; Zhang et al., 2022) and fact verification (Liu et al., 2019; Zhou et al., 2019) that are beyond the scope of this work. An alternative approach involves fusing text encoding and graph aggregation into an iterative workflow, enabling the model to refine both the text representations and the node embeddings simultaneously, such as Graphormer (Yang et al., 2021), DRAGON (Yasunaga et al., 2022), and GLEM (Zhao et al., 2022), to name a few.
64
+
65
+ LLM-based pipeline for TAGs. Incorporating LLMs into TAG tasks presents a promising frontier. LLMs such as ChatGPT (Brown et al., 2020) by OpenAI, PaLM (Chowdhery et al., 2022) by Google, and LLaMA (Touvron et al., 2023) by Meta, have demonstrated their effectiveness across a spectrum of NLP tasks. However, their potential benefits for TAG tasks have yet to be fully explored. While some recent research efforts have sought to evaluate the capacity of LLMs in understanding graphstructured data and enhance their graph processing capabilities (Wang et al., 2023; Zhang, 2023; Guo et al., 2023), these endeavors, while valuable, may not be directly aligned with our specific focus on TAGs. By exploring LLM-based methods designed specifically for TAGs, we can unlock new possibilities for improving TAG prediction performance and advancing our understanding of text attributes within graph-based data. Notably, our initial attempt has already inspired further research endeavors in this direction.
66
+
67
+ # 3 FORMALIZATION
68
+
69
+ In this section, we introduce notation and formalize some concepts related to language models, large language models, and graph neural networks for node classification on TAGs.
70
+
71
+ Text-attributed graphs. Formally, a TAG can be represented as ${ \mathcal { G } } = ( \mathcal { V } , A , \{ s _ { n } \} _ { n \in \mathcal { V } } )$ , where $\nu$ is a set of $N$ nodes, $\mathbf { \bar { \Psi } } _ { A } \doteq \mathbb { R } ^ { N \times N }$ is the adjacency matrix, and $s _ { n } \in \mathcal { D } ^ { L _ { n } }$ is a sequential text associated with node $n \in \mathcal V$ , with $\mathcal { D }$ as the words or tokens dictionary, and $L _ { n }$ as the sequence length. In this paper, we investigate node classification on TAGs. Specifically, given some labeled nodes $\mathcal { L } \subset \mathcal { V }$ , the goal is to predict the labels of the remaining unlabeled nodes $\mathcal { \bar { U } } = \mathcal { V } \backslash \mathcal { L }$ .
72
+
73
+ Language models for text classification. In the context of TAGs, LMs can be employed to encode the text attributes associated with each node and learn a representation that captures the semantic meaning of the text. Let $s _ { n } \in \mathcal { D } ^ { L _ { n } }$ denote the text attributes of node $n$ , and LM be a pre-trained network, such as BERT (Devlin et al., 2018) or DeBERTa (He et al., 2021). Then, the text attributes of node $n$ can be encoded by applying the LM to $s _ { n }$ as follows:
74
+
75
+ $$
76
+ h _ { n } = \mathbf { L M } ( s _ { n } ) \in \mathbb { R } ^ { d } ,
77
+ $$
78
+
79
+ where $h _ { n }$ is the output of the LM, and $d$ is the dimension of the output vector.
80
+
81
+ To perform node classification, the output is employed as input to a classifier, such as a logistic regression or a neural network. The goal is to learn a function that maps the encoded text attributes to the corresponding node labels.
82
+
83
+ Large language models and prompting. LLMs have introduced a new paradigm for taskadaptation known as “pre-train, prompt, and predict”, replacing the traditional “pre-train, fine-tune” procedure. In this paradigm, the LLM is first pre-trained on a large corpus of text data to learn general language representations. Then, rather than fine-tuning the model on task-specific labeled data, the model is prompted with a natural language prompt that specifies the task and context, and the model generates the output directly based on the prompt and the input (Liu et al., 2023).
84
+
85
+ The prompt can take various forms, such as a single sentence or a longer passage, and can include additional information or constraints to guide the model’s behavior. Let $\mathcal { M }$ be an LLM that takes as input a sequence of tokens $\boldsymbol { x } = \left( x _ { 1 } , x _ { 2 } , \ldots , x _ { q } \right)$ and produces as output a sequence of tokens $y =$ $\left( y _ { 1 } , y _ { 2 } , \ldots , y _ { m } \right)$ . The model $\mathcal { M }$ is typically trained to optimize a conditional probability distribution $p ( y | x )$ , which assigns a probability to each possible output sequence $y$ given $x$ . To include a prompt $p$ with the input sequence $x$ , we can concatenate them into a new sequence $\hat { x } = ( p , x _ { 1 } , x _ { 2 } , \ldots , x _ { q } )$ . We then use $\hat { x }$ to compute the conditional probability distribution $p ( y | \hat { x } )$ . Formally, the probability of the output sequence $y$ given $\hat { x }$ is:
86
+
87
+ $$
88
+ p ( \boldsymbol { y } | \hat { x } ) = \prod _ { i = 1 } ^ { m } p ( y _ { i } | \boldsymbol { y } _ { < i } , \hat { x } ) ,
89
+ $$
90
+
91
+ where $y _ { < i }$ represents the prefix of sequence $y$ up to position $i - 1$ , and $p ( y _ { i } | y _ { < i } , \hat { x } )$ represents the probability of generating token $y _ { i }$ given $y _ { < i }$ and $\hat { x }$ .
92
+
93
+ Graph neural networks for node classification. In node classification, the task is to label each node in a graph based on its attributes and connections with other nodes. GNNs operate by aggregating information from a node’s neighbors, then updating the node’s representation based on the aggregated information. Formally, the $k$ -th layer of a GNN is designed as:
94
+
95
+ $$
96
+ \begin{array} { r } { h _ { i } ^ { k } = f ^ { k } ( h _ { i } ^ { k - 1 } , \mathsf { A G G } ( \{ h _ { j } ^ { k - 1 } : j \in \mathcal { N } _ { i } \} ) ) \in \mathbb { R } ^ { d } , } \end{array}
97
+ $$
98
+
99
+ where $h _ { i } ^ { k } \in \mathbb { R } ^ { d }$ is the representation of node $i$ at layer $k$ and $\mathcal { N } _ { i } \subseteq \mathcal { V }$ is the set of neighbors of node $i$ . Function $f ^ { k }$ is a differentiable function that updates the representation of a node based on its previous-layer representation and the aggregated information from its neighbors. This function is typically implemented as a neural network layer (e.g., a multi-layer perceptron, or an attention mechanism). AGG is also a differentiable function (e.g., sum, mean, etc.) that aggregates the representations of a node’s neighbors to produce a summary vector. The final representation is fed into a fully connected layer and a softmax function for class prediction.
100
+
101
+ # 4 PROPOSED METHOD
102
+
103
+ In this section, we describe our LLM-based pipeline designed for node classification on TAGs. As illustrated in Figure 1, the key idea is to leverage the LLM’s explanations as informative features for a downstream GNN. To achieve this goal, our method involves three main steps: 1) LLM-based prediction and explanation generation, 2) fine-tuning an LM interpreter, and 3) training a GNN.
104
+
105
+ # 4.1 GENERATING PREDICTIONS AND EXPLANATIONS WITH LLMS
106
+
107
+ As outlined in the introduction, our approach is designed to be LMaaS-compatible given the scale of LLMs. This means that we aim to operate solely through API access to an LLM, using text-based input and output, without requiring fine-tuning the LLM or accessing its embeddings or logits.
108
+
109
+ In lieu of these requirements, our approach focuses on querying the LLM in an “open-ended” manner, i.e., instructing the LLM to make multiple predictions and provide explanations for its decisions. By doing so, we aim to effectively extract its reasoning abilities and general knowledge in text format. These text-based outputs are then processed using an LLM-to-LM interpreter to create informative node features for downstream GNNs. With this objective, for each paper node $i \in \mathcal V$ , we generate a prompt that includes the title and abstract of the paper, along with an open-ended question about the paper’s topic. The specific phrasing of the question part of the prompt is tailored to the task and dataset, as shown in Table 5. The general structure of the prompt is as follows:
110
+
111
+ Abstract: [paper abstract]
112
+ Title: [paper title]
113
+ Question: [ask the model to predict one or more class labels of the paper, ordered from most
114
+ to least likely, and provide explanations for its predictions]
115
+
116
+ Answer:
117
+
118
+ Querying the LLM results in a ranked prediction list and a textual explanation for each paper:
119
+
120
+ (Ranked Predictions) [a ranked prediction list] (Explanations) [model-generated explanation for the predictions]
121
+
122
+ These predictions and explanations serve as supplementary text attributes for the downstream LMs and GNN models, as detailed in the subsequent section.
123
+
124
+ # 4.2 FINE-TUNING LM INTERPRETER AND NODE FEATURE EXTRACTION
125
+
126
+ Original text and explanation features. Our initial step involves converting both the original text, i.e., title and abstract, and the LLM’s explanations into fixed-length node features suitable for downstream GNN applications. Our approach is to fine-tune a smaller LM, which acts as an “interpreter” for the LLM’s text explanations. The rationale behind this step is that both the LLM and LM possess distinct advantages: the LLM has greater power and more knowledge but is less flexible, while the LM has less skills but is compact enough to be fine-tuned to a specific task. Thus, the LM serves to interpret the LLM’s output for the GNN, with the text explanation acting as an effective intermediate medium for communication. Then, fine-tuning the LM enables it to extract the most valuable and task-relevant features from the explanations.
127
+
128
+ Concretely, we first fine-tune pre-trained LMs as follows: let $\mathbf { L M } _ { \mathrm { o r i g } }$ and $\mathrm { L M } _ { \mathrm { e x p l } }$ be pre-trained LMs that take as input the original $s ^ { \mathrm { o r i g } }$ and the explanation $s ^ { \mathrm { e x p l } }$ text sequences, respectively. We obtain text embeddings for each source as follows:
129
+
130
+ $$
131
+ h _ { \mathrm { o r i g } } = \mathbf { L } \mathbf { M } _ { \mathrm { o r i g } } ( s ^ { \mathrm { o r i g } } ) \in \mathbb { R } ^ { N \times d } , \quad h _ { \mathrm { e x p l } } = \mathbf { L } \mathbf { M } _ { \mathrm { e x p l } } ( s ^ { \mathrm { e x p l } } ) \in \mathbb { R } ^ { N \times d } .
132
+ $$
133
+
134
+ We further apply a Multi-Layer Perceptron (MLP) to the output of the LMs to obtain a $N \times C$ dimensional prediction matrix representing the LM’s predictions for each node (in logits):
135
+
136
+ $$
137
+ y _ { \mathrm { o r i g } } = \mathbf { M } \mathbf { L } \mathbf { P } _ { \mathrm { o r i g } } ( h _ { \mathrm { o r i g } } ) \in \mathbb { R } ^ { N \times C } , \quad y _ { \mathrm { e x p l } } = \mathbf { M } \mathbf { L } \mathbf { P } _ { \mathrm { e x p l } } ( h _ { \mathrm { e x p l } } ) \in \mathbb { R } ^ { N \times C } .
138
+ $$
139
+
140
+ We fine-tune these LMs and MLPs using cross-entropy loss. Finally, the text embeddings from both sources, $h _ { \mathrm { o r i g } }$ and $h _ { \mathrm { e x p l } }$ , are used as enriched features for training downstream GNNs.
141
+
142
+ Ranked prediction features. In addition to the explanations, the LLM also provides a top- $k$ ranked prediction list for each node, which adds valuable information. To incorporate this knowledge, the top- $k$ predictions for node $i$ are first one-hot encoded as vectors $p _ { i , 1 } , . . . \bar { , } p _ { i , k } \in \mathbb { R } ^ { C }$ . These vectors are subsequently concatenated into a $k C$ -dimensional vector, followed by a linear transformation to produce a fixed-sized vector of length $d _ { P }$ . This process produces a prediction feature matrix as $h _ { \mathrm { p r e d } } \in \mathbb { R } ^ { N \times d _ { P } }$ across all nodes.
143
+
144
+ In summary, we denote our features as $h _ { \mathrm { T A P E } } = \{ h _ { \mathrm { o r i g } } , h _ { \mathrm { e x p l } } , h _ { \mathrm { p r e d } } \}$ , where “TAPE” stands for Title, Abstract, Prediction and Explanation for each node. Importantly, our framework requires these features to remain frozen during downstream GNN training, ensuring that the LM and LLM do not participate in the GNN training process. This characteristic significantly enhances ease-of-use, modularity, and efficiency compared to approaches like GLEM, which involve an expensive iterative LM-GNN training process. As a result, we achieve a substantial speedup over GLEM, e.g., a $2 . 8 8 \times$ speedup on ogbn-arxiv even when utilizing the same backbone LM and GNN.
145
+
146
+ # 4.3 GNN TRAINING ON ENRICHED FEATURES
147
+
148
+ Our final step is to train a GNN using the $h _ { \mathrm { T A P E } }$ features. We aim to achieve this without increasing the memory requirements of the GNN or making any changes to its architecture. To accomplish this, we use an ensemble approach, as a simple and effective way of combining the features. Specifically, we independently train GNN models $f _ { \mathrm { o r i g } } , \ f _ { \mathrm { e x p l } }$ , and $f _ { \mathrm { p r e d } }$ on the features $h _ { \mathrm { o r i g } } , \ h _ { \mathrm { e x p l } }$ , and $h _ { \mathrm { p r e d } }$ , respectively, to predict the ground truth node labels:
149
+
150
+ $$
151
+ \begin{array} { r } { \hat { y } _ { \mathrm { o r i g / e x p l / p r e d } } = f _ { \mathrm { o r i g / e x p l / p r e d } } ( h _ { \mathrm { o r i g / e x p l / p r e d } } , A ) \in \mathbb { R } ^ { N \times C } . } \end{array}
152
+ $$
153
+
154
+ We then fuse these predictions by taking their average:
155
+
156
+ $$
157
+ \begin{array} { r } { \hat { y } = \mathrm { m e a n } ( \hat { y } _ { \mathrm { o r i g } } , \hat { y } _ { \mathrm { e x p l } } , \hat { y } _ { \mathrm { p r e d } } ) \in \mathbb { R } ^ { N \times C } . } \end{array}
158
+ $$
159
+
160
+ Each of the three models performs well individually as shown in Table 3, which validates the effectiveness of simple averaging. This strategy enables us to capture complementary information from diverse input sources, ultimately enhancing the overall model’s performance.
161
+
162
+ # 4.4 THEORETICAL ANALYSIS
163
+
164
+ In this section, we aim to demonstrate that explanations generated by an LLM can be valuable features for a smaller LM. Specifically, the explanations $E$ are helpful if they possess fidelity in describing the LLM’s reasoning; and the LLM is non-redundant, utilizing information not used by the smaller LM. Let $E$ be the textual explanations generated by an LLM; $Z _ { L }$ and $Z$ are embeddings from the LLM and smaller LM respectively, $y$ is the target and $H ( \cdot | \cdot )$ is the conditional entropy. The detailed proof is in Appendix A.
165
+
166
+ Theorem. Given the following conditions 1) Fidelity: $E$ is a good proxy for $Z _ { L }$ such that $H ( Z _ { l } | E ) = \epsilon$ , with $\epsilon > 0$ , 2) Non-redundancy: $Z _ { L }$ contains information not present in $Z$ , expressed as $H ( y | Z , Z _ { L } ) = H ( y | Z ) - \epsilon ^ { \prime }$ , with $\epsilon ^ { \prime } > \epsilon$ . Then it follows that $H ( y | Z , \bar { E } ) < H ( y | Z )$ .
167
+
168
+ # 5 EXPERIMENTS
169
+
170
+ We evaluate TAPE on five TAG datasets: Cora (McCallum et al., 2000), PubMed (Sen et al., 2008), ogbn-arxiv, ogbn-products (Hu et al., 2020a), and tape-arxiv23. For Cora and PubMed, raw text data of the articles is unavailable in common graph libraries such as PyG and DGL. Hence, we collected and formatted the missing text data for these datasets in TAG format. Additionally, given the popularity of these datasets, their TAG version will be released publicly for reproducibility and new research projects. For ogbn-products, given its substantial scale of 2 million nodes and 61 million edges and considering our academic resource budget, we conducted experiments on a subgraph sample. Details can be found in Appendix G.
171
+
172
+ # 5.1 MAIN RESULTS
173
+
174
+ Table 1: Node classification accuracy for the Cora, PubMed, ogbn-arxiv, ogbn-products and tape-arxiv23 datasets. $G \uparrow$ denotes the improvements of our approach over the same GNN trained on shallow features $h _ { \mathrm { s h a l l o w } }$ ; $L \uparrow$ denotes the improvements of our approach over LMfinetune. The results are averaged over four runs with different seeds, and the best results are in bold.
175
+
176
+ <table><tr><td rowspan="2">Dataset</td><td rowspan="2">Method</td><td colspan="3">GNN</td><td colspan="3">LM</td><td>Ours</td></tr><tr><td>hshallow</td><td>hGIANT</td><td>G↑</td><td>LLM</td><td>LMfinetune</td><td>L↑</td><td>hTAPE</td></tr><tr><td rowspan="4">Cora</td><td>MLP</td><td>0.6388 ± 0.0213</td><td>0.7196 ± 0.0000</td><td>37.41%</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>13.35%</td><td>0.8778 ±0.0485</td></tr><tr><td>GCN</td><td>0.8911 ± 0.0015</td><td>0.8423 ± 0.0053</td><td>2.33%</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>16.59%</td><td>0.9119 ± 0.0158</td></tr><tr><td>SAGE</td><td>0.8824±0.0009</td><td>0.8455 ± 0.0028</td><td>5.28%</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>18.13%</td><td>0.9290 ± 0.0307</td></tr><tr><td>RevGAT</td><td>0.8911 ±0.0000</td><td>0.8353 ±0.0038</td><td>4.14%</td><td>0.6769</td><td>0.7606 ±0.0378</td><td>18.04%</td><td>0.9280 ± 0.0275</td></tr><tr><td rowspan="4">PubMed</td><td>MLP</td><td>0.8635 ±0.0032</td><td>0.8175 ± 0.0059</td><td>10.77%</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>0.75%</td><td>0.9565 ± 0.0060</td></tr><tr><td>GCN</td><td>0.8031 ±0.0425</td><td>0.8419 ±0.0050</td><td>17.43%</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>-0.66%</td><td>0.9431 ± 0.0043</td></tr><tr><td>SAGE</td><td>0.8881 ±0.0002</td><td>0.8372 ± 0.0082</td><td>8.30%</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>1.31%</td><td>0.9618 ± 0.0053</td></tr><tr><td>RevGAT</td><td>0.8850± 0.0005</td><td>0.8502 ± 0.0048</td><td>8.52%</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>1.15%</td><td>0.9604 ± 0.0047</td></tr><tr><td rowspan="4">ogbn-arxiv</td><td>MLP</td><td>0.5336 ± 0.0038</td><td>0.7308 ±0.0006</td><td>42.19%</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>3.07%</td><td>0.7587 ± 0.0015</td></tr><tr><td>GCN</td><td>0.7182 ±0.0027</td><td>0.7329 ±0.0010</td><td>4.71%</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>2.16%</td><td>0.7520±0.0003</td></tr><tr><td>SAGE</td><td>0.7171 ± 0.0017</td><td>0.7435± 0.0014</td><td>6.98%</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>4.22%</td><td>0.7672 ± 0.0007</td></tr><tr><td>RevGAT</td><td>0.7083 ±0.0017</td><td>0.7590 ± 0.0019</td><td>9.42%</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>5.28%</td><td>0.7750 ± 0.0012</td></tr><tr><td rowspan="4">ogbn-products</td><td>MLP</td><td>0.5385 ± 0.0017</td><td>0.6125 ± 0.0078</td><td>46.3%</td><td>0.7440</td><td>0.7297 ± 0.0023</td><td>7.96%</td><td>0.7878 ±0.0082</td></tr><tr><td>GCN</td><td>0.7052 ± 0.0051</td><td>0.6977 ± 0.0042</td><td>13.39%</td><td>0.7440</td><td>0.7297 ± 0.0023</td><td>9.58%</td><td>0.7996 ±0.0041</td></tr><tr><td>SAGE</td><td>0.6913 ± 0.0026</td><td>0.6869 ± 0.0119</td><td>17.71%</td><td>0.7440</td><td>0.7297 ± 0.0023</td><td>11.51%</td><td>0.8137 ± 0.0043</td></tr><tr><td>RevGAT</td><td>0.6964 ±0.0017</td><td>0.7189 ±0.0030</td><td>18.24%</td><td>0.7440</td><td>0.7297 ± 0.0023</td><td>12.84%</td><td>0.8234 ± 0.0036</td></tr><tr><td rowspan="4">tape-arxiv23</td><td>MLP</td><td>0.6202 ± 0.0064</td><td>0.5574 ± 0.0032</td><td>35.20%</td><td>0.7356</td><td>0.7358 ±0.0006</td><td>12.25%</td><td>0.8385 ±0.0246</td></tr><tr><td>GCN</td><td>0.6341 ± 0.0062</td><td>0.5672 ± 0.0061</td><td>27.42%</td><td>0.7356</td><td>0.7358 ± 0.0006</td><td>8.94%</td><td>0.8080 ±0.0215</td></tr><tr><td>SAGE</td><td>0.6430± 0.0037</td><td>0.5665 ± 0.0032</td><td>30.45%</td><td>0.7356</td><td>0.7358 ± 0.0006</td><td>12.28%</td><td>0.8388 ± 0.0264</td></tr><tr><td>RevGAT</td><td>0.6563± 0.0062</td><td>0.5834 ± 0.0038</td><td>28.34%</td><td>0.7356</td><td>0.7358 ± 0.0006</td><td>12.64%</td><td>0.8423 ± 0.0256</td></tr></table>
177
+
178
+ We conduct a comprehensive evaluation of our proposed TAPE method by comparing with existing GNN- and LM-based methods, with the results summarized in Table 1. For GNN comparisons, we consider three widely utilized architectures: GCN (Kipf & Welling, 2016), GraphSAGE (Sun et al., 2021), and RevGAT (Li et al., 2021) along with a basic MLP baseline that operates independently off graph-related information. We explore three types of node features: 1) shallow features (detailed in Table 9), denoted as $h _ { \mathrm { s h a l l o w } }$ , 2) GIANT features (Chien et al., 2021) $h _ { \mathrm { G I A N T } }$ , and 3) our proposed features $h _ { \mathrm { T A P E } }$ , comprising $h _ { \mathrm { o r i g } }$ , $h _ { \mathrm { e x p l } }$ , and $h _ { \mathrm { p r e d } }$ . For LM-based methods, we investigate two approaches: 1) fine-tuning DeBERTa on labeled nodes, denoted as $\mathrm { L M } _ { \mathrm { f i n e t u n e } }$ , and 2) using zero-shot ChatGPT (gpt-3.5-turbo) with the same prompts as our approach, denoted as LLM.
179
+
180
+ Our approach consistently outperforms other methods on all datasets and across all models, demonstrating its effectiveness in enhancing TAG representation learning. Among GNN-based methods, shallow features (i.e., $h _ { \mathrm { s h a l l o w } } )$ yields subpar performance, while LM-based features (i.e., hGIANT) improves results. In the case of LMs, fine-tuned LMs (i.e., $\mathrm { L M } _ { \mathrm { f i n e t u n e } } )$ also perform well. Our proposed novel features, leveraging the power of the LLM, further enhance the results.
181
+
182
+ Additionally, we expanded our experimentation to include the open-source Llama2 (Touvron et al., 2023), demonstrating the feasibility of a cost-effective (free) alternative, as shown in Table 4. Furthermore, to address the potential label leakage concern in LLM, we took the initiative to construct a novel dataset, namely tape-arxiv23, comprising papers published in 2023 or later – well beyond the knowledge cutoff for GPT-3.5. The results clearly illustrate strong generalization capabilities: while the LLM achieves $7 3 . 5 6 \%$ accuracy, our approach outperforms it with $8 4 . 2 3 \%$ .
183
+
184
+ # 5.2 SCALABILITY
185
+
186
+ Our proposed method surpasses not only pure LMs and shallow embedding pipelines but also the LM-based pipelines on the ogbn-arxiv dataset, achieving a superior balance between accuracy and training time, as illustrated in Figure 2. Specifically, our method achieved significantly higher accuracy than the SOTA GLEM (Zhao et al., 2022) method while utilizing the same LM and GNN models. Furthermore, our approach requires only $2 . 8 8 \times$ less computation time. These efficiency improvements are attributed to our decoupled training approach for LMs and GNNs, avoiding the iterative (i.e., multi-stage) approach used in GLEM. Moreover, unlike the iterative approach, our model allows for parallelizing the training of $\mathbf { L M } _ { \mathrm { o r i g } }$ and $\mathrm { L M } _ { \mathrm { e x p l } }$ , further reducing overall training time when performed simultaneously.
187
+
188
+ Table 2: Experiments on ogbn-arxiv dataset with DeBERTa-base (He et al., 2021) as LM backbone and RevGAT (Li et al., 2021) as GNN backbone for comparison of different training paradigms of fusing LMs and GNNs, including our proposed method and the state-of-the-art GLEM method (Zhao et al., 2022). The validation and test accuracy, number of parameters, maximum batch size (Max bsz.), and total training time on 4 NVIDIA RTX A5000 24GB GPUs are reported.
189
+
190
+ <table><tr><td>Method</td><td>Val acc.</td><td>Test acc.</td><td>Params.</td><td>Max bsz.</td><td>Total time</td></tr><tr><td>LMorig</td><td>0.7503 ± 0.0008</td><td>0.7361 ± 0.0004</td><td>139,223,080</td><td>36</td><td>1.73h</td></tr><tr><td>GNN-hshallw</td><td>0.7144 ± 0.0021</td><td>0.7083 ± 0.0017</td><td>427,728</td><td>all nodes</td><td>1.80min</td></tr><tr><td>GLEM-L-Sstep</td><td>0.7761 ±0.009</td><td>0.7657 ± 0.0039</td><td>1837.1368</td><td>all odes</td><td>9.18h</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>TAPE-LMorg-Step</td><td>0.7503 ± 0.0008</td><td>0.7361 ± 0.0004</td><td>139,223,080</td><td>36</td><td>1.73h</td></tr><tr><td>TAPE-LMexp1-Step</td><td>0.7506 ± 0.0008</td><td>0.7432 ± 0.0012</td><td>139,223,080</td><td>36</td><td>1.40h</td></tr><tr><td>TAPE-GNN-hTAPE-Step</td><td>0.7785 ± 0.0016</td><td>0.7750 ± 0.0012</td><td>1,837,136</td><td> all nodes</td><td>3.76min</td></tr></table>
191
+
192
+ Table 3: Ablation study on the ogbn-arxiv dataset, showing the effects of different node features on the performance. Node features include the original text attributes $( h _ { \mathrm { o r i g } } )$ , the explanations $( h _ { \mathrm { e x p l } }$ and predicted $h _ { \mathrm { p r e d } } )$ ) generated by LLM, and the proposed method $( h _ { \mathrm { T A P E } } )$ . Results are averaged over 4 runs with 4 different seeds. The best results are in bold.
193
+
194
+ <table><tr><td>Method</td><td></td><td>horig</td><td>hexpl</td><td>hpred</td><td>hTAPE</td></tr><tr><td rowspan="2">GCN</td><td>val</td><td>0.7624 ± 0.0007</td><td>0.7577 ± 0.0008</td><td>0.7531 ± 0.0006</td><td>0.7642 ± 0.0003</td></tr><tr><td>test</td><td>0.7498 ± 0.0018</td><td>0.7460 ± 0.0013</td><td>0.7400 ± 0.0007</td><td>0.7520 ± 0.0003</td></tr><tr><td rowspan="2">SAGE</td><td>val</td><td>0.7594 ± 0.0012</td><td>0.7631 ± 0.0016</td><td>0.7612 ± 0.0010</td><td>0.7768 ± 0.0016</td></tr><tr><td>test</td><td>0.7420 ± 0.0018</td><td>0.7535 ± 0.0023</td><td>0.7524 ± 0.0015</td><td>0.7672 ± 0.0007</td></tr><tr><td rowspan="2">RevGAT</td><td>val</td><td>0.7588 ± 0.0021</td><td>0.7568 ± 0.0027</td><td>0.7550 ± 0.0015</td><td>0.7785 ± 0.0016</td></tr><tr><td>test</td><td>0.7504 ± 0.0020</td><td>0.7529 ± 0.0052</td><td>0.7519 ± 0.0031</td><td>0.7750 ± 0.0012</td></tr></table>
195
+
196
+ # 5.3 ABLATION STUDY
197
+
198
+ We perform an ablation study on the ogbn-arxiv dataset (Hu et al., 2020a) to evaluate the relevance of each module within our framework. The results are summarized in Table 3 and Figure 4. Across all methods and for both the validation and test sets, our proposed method consistently outperforms the other settings. This underscores the value of incorporating explanations and predictions into node embeddings.
199
+
200
+ We provide time analysis and cost estimation in Appendix B, detail tape-arxiv23 dataset collection in Appendix C, use open-sourced llama as the LLM in Appendix D, include a case study in Appendix E, discuss prompt design in Appendix F, examine LM finetuning effects in Appendix I, explore the impact of various LMs in Appendix J, and analyze memory usage in Appendix K.
201
+
202
+ # 6 CONCLUSION
203
+
204
+ Given the increasing importance of integrating text and relationships, coupled with the emergence of LLMs, we foresee that TAG tasks will attract even more attention in the coming years. The convergence of LLMs and GNNs presents new opportunities for both research and industrial applications. As a pioneering work in this field, we believe that our contribution will serve as a strong baseline for future studies in this domain.
205
+
206
+ Limitation and future work. An inherent limitation of our approach lies in the requirement for customized prompts for each dataset. Currently, we rely on manually crafted prompts, which may not be optimal for the node classification task for every dataset. The efficacy of these prompts may fluctuate depending on the specific characteristics of the dataset and the specific task at hand. Future work can focus on automating the prompt generation process, exploring alternative prompt designs, and addressing the challenges of dynamic and evolving TAGs.
207
+
208
+ # ACKNOWLEDGMENT
209
+
210
+ Bryan Hooi is supported by the Ministry of Education, Singapore, under the Academic Research Fund Tier 1 (FY2023) (Grant A-8001996-00-00) and Xavier Bresson is supported by NUS Grant ID R-252-000-B97-133. The authors would like to express their gratitude to the reviewers for their feedback, which has improved the clarity and contribution of the paper.
211
+
212
+ # REPRODUCIBILITY STATEMENT
213
+
214
+ In this statement, we provide references to the relevant sections and materials that will assist readers and researchers in replicating our results.
215
+
216
+ Theorem. For a comprehensive understanding of the theorem presented in Section 4.4, please refer to Appendix A for a detailed proof.
217
+
218
+ Dataset description. We summarize all datasets used in our study in Appendix G, providing information on their sources and any necessary preprocessing steps. Additionally, for the newly introduced tape-arxiv23 dataset, we offer a detailed description of the data collection and processing steps in Appendix C.
219
+
220
+ Open access to codes, datasets, trained models, and enriched features. Our source code can be accessed at the following url: https://github.com/XiaoxinHe/TAPE. Within this repository, we provide a script with step-by-step instructions on how to replicate the main results presented in our paper. Additionally, we offer download links for the Cora and PubMed datasets in TAG form, along with the new dataset tape-arxiv23. These datasets can serve as valuable resources for the NLP and GNN research community. Furthermore, this repository includes the checkpoints for all trained models (.ckpt) and the TAPE features (.emb) used in our project, making it easy for researchers focusing on downstream GNN tasks to access enriched features.
221
+
222
+ # REFERENCES
223
+
224
+ Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901, 2020.
225
+ Wei-Lin Chiang, Xuanqing Liu, Si Si, Yang Li, Samy Bengio, and Cho-Jui Hsieh. Cluster-gcn: An efficient algorithm for training deep and large graph convolutional networks. In Proceedings of the 25th ACM SIGKDD international conference on knowledge discovery & data mining, pp. 257–266, 2019.
226
+ Eli Chien, Wei-Cheng Chang, Cho-Jui Hsieh, Hsiang-Fu Yu, Jiong Zhang, Olgica Milenkovic, and Inderjit S Dhillon. Node feature extraction by self-supervised multi-scale neighborhood prediction. arXiv preprint arXiv:2111.00064, 2021.
227
+ Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311, 2022.
228
+ Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805, 2018.
229
+ Tu Anh Dinh, Jeroen den Boef, Joran Cornelisse, and Paul Groth. E2eg: End-to-end node classification using graph topology and text-based node attributes. arXiv preprint arXiv:2208.04609, 2022.
230
+ Keyu Duan, Qian Liu, Tat-Seng Chua, Shuicheng Yan, Wei Tsang Ooi, Qizhe Xie, and Junxian He. Simteg: A frustratingly simple approach improves textual graph learning. arXiv preprint arXiv:2308.02565, 2023.
231
+ Matthias Fey and Jan Eric Lenssen. Fast graph representation learning with pytorch geometric. arXiv preprint arXiv:1903.02428, 2019.
232
+ Jiayan Guo, Lun Du, and Hengyu Liu. Gpt4graph: Can large language models understand graph structured data? an empirical evaluation and benchmarking. arXiv preprint arXiv:2305.15066, 2023.
233
+ Will Hamilton, Zhitao Ying, and Jure Leskovec. Inductive representation learning on large graphs. Advances in neural information processing systems, 30, 2017.
234
+ Zellig Harris. Distributional structure. The philosophy of linguistics, 1985.
235
+ Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. Deberta: Decoding-enhanced bert with disentangled attention. In International Conference on Learning Representations, 2021. URL https://openreview.net/forum?id $=$ XPZIaotutsD.
236
+ Weihua Hu, Matthias Fey, Marinka Zitnik, Yuxiao Dong, Hongyu Ren, Bowen Liu, Michele Catasta, and Jure Leskovec. Open graph benchmark: Datasets for machine learning on graphs. Advances in neural information processing systems, 33:22118–22133, 2020a.
237
+ Ziniu Hu, Yuxiao Dong, Kuansan Wang, Kai-Wei Chang, and Yizhou Sun. Gpt-gnn: Generative pre-training of graph neural networks. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, pp. 1857–1867, 2020b.
238
+ 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. arXiv preprint arXiv:2001.08361, 2020.
239
+ Thomas N Kipf and Max Welling. Semi-supervised classification with graph convolutional networks. arXiv preprint arXiv:1609.02907, 2016.
240
+ Guohao Li, Matthias Müller, Bernard Ghanem, and Vladlen Koltun. Training graph neural networks with 1000 layers. In International conference on machine learning, pp. 6437–6449. PMLR, 2021.
241
+ Stephanie Lin, Jacob Hilton, and Owain Evans. Truthfulqa: Measuring how models mimic human falsehoods. arXiv preprint arXiv:2109.07958, 2021.
242
+ Pengfei Liu, Weizhe Yuan, Jinlan Fu, Zhengbao Jiang, Hiroaki Hayashi, and Graham Neubig. Pretrain, prompt, and predict: A systematic survey of prompting methods in natural language processing. ACM Computing Surveys, 55(9):1–35, 2023.
243
+ Zhenghao Liu, Chenyan Xiong, Maosong Sun, and Zhiyuan Liu. Fine-grained fact verification with kernel graph attention network. arXiv preprint arXiv:1910.09796, 2019.
244
+ Andrew Kachites McCallum, Kamal Nigam, Jason Rennie, and Kristie Seymore. Automating the construction of internet portals with machine learning. Information Retrieval, 3:127–163, 2000.
245
+ Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg S Corrado, and Jeff Dean. Distributed representations of words and phrases and their compositionality. Advances in neural information processing systems, 26, 2013.
246
+ Niklas Muennighoff, Nouamane Tazi, Loïc Magne, and Nils Reimers. Mteb: Massive text embedding benchmark. arXiv preprint arXiv:2210.07316, 2022.
247
+ Nils Reimers and Iryna Gurevych. Sentence-bert: Sentence embeddings using siamese bertnetworks. arXiv preprint arXiv:1908.10084, 2019.
248
+ Prithviraj Sen, Galileo Namata, Mustafa Bilgic, Lise Getoor, Brian Galligher, and Tina Eliassi-Rad. Collective classification in network data. AI magazine, 29(3):93–93, 2008.
249
+ Aarohi Srivastava, Abhinav Rastogi, Abhishek Rao, Abu Awal Md Shoeb, Abubakar Abid, Adam Fisch, Adam R Brown, Adam Santoro, Aditya Gupta, Adrià Garriga-Alonso, et al. Beyond the imitation game: Quantifying and extrapolating the capabilities of language models. arXiv preprint arXiv:2206.04615, 2022.
250
+ Chuxiong Sun, Hongming Gu, and Jie Hu. Scalable and adaptive graph neural networks with selflabel-enhanced training. arXiv preprint arXiv:2104.09376, 2021.
251
+
252
+ Tianxiang Sun, Yunfan Shao, Hong Qian, Xuanjing Huang, and Xipeng Qiu. Black-box tuning for language-model-as-a-service. In International Conference on Machine Learning, pp. 20841– 20855. PMLR, 2022.
253
+
254
+ 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. Llama: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023.
255
+ Maria Tsimpoukelli, Jacob L Menick, Serkan Cabi, SM Eslami, Oriol Vinyals, and Felix Hill. Multimodal few-shot learning with frozen language models. Advances in Neural Information Processing Systems, 34:200–212, 2021.
256
+ Petar Velickovi ˇ c, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro Lio, and Yoshua ´ Bengio. Graph attention networks. arXiv preprint arXiv:1710.10903, 2017.
257
+ Petar Velickovic, William Fedus, William L Hamilton, Pietro Liò, Yoshua Bengio, and R Devon Hjelm. Deep graph infomax. ICLR (Poster), 2(3):4, 2019.
258
+ Heng Wang, Shangbin Feng, Tianxing He, Zhaoxuan Tan, Xiaochuang Han, and Yulia Tsvetkov. Can language models solve graph problems in natural language? arXiv preprint arXiv:2305.10037, 2023.
259
+ Kuansan Wang, Zhihong Shen, Chiyuan Huang, Chieh-Han Wu, Yuxiao Dong, and Anshul Kanakia. Microsoft academic graph: When experts are not enough. Quantitative Science Studies, 1(1):396– 413, 2020.
260
+ Liang Wang, Nan Yang, Xiaolong Huang, Binxing Jiao, Linjun Yang, Daxin Jiang, Rangan Majumder, and Furu Wei. Text embeddings by weakly-supervised contrastive pre-training. arXiv preprint arXiv:2212.03533, 2022.
261
+ Minjie Wang, Da Zheng, Zihao Ye, Quan Gan, Mufei Li, Xiang Song, Jinjing Zhou, Chao Ma, Lingfan Yu, Yu Gai, et al. Deep graph library: A graph-centric, highly-performant package for graph neural networks. arXiv preprint arXiv:1909.01315, 2019.
262
+ Suhang Wang, Jiliang Tang, Charu Aggarwal, and Huan Liu. Linked document embedding for classification. In Proceedings of the 25th ACM international on conference on information and knowledge management, pp. 115–124, 2016.
263
+ 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.
264
+ Cheng Yang, Zhiyuan Liu, Deli Zhao, Maosong Sun, and Edward Y Chang. Network representation learning with rich text information. In IJCAI, volume 2015, pp. 2111–2117, 2015.
265
+ Junhan Yang, Zheng Liu, Shitao Xiao, Chaozhuo Li, Defu Lian, Sanjay Agrawal, Amit Singh, Guangzhong Sun, and Xing Xie. Graphformers: Gnn-nested transformers for representation learning on textual graph. Advances in Neural Information Processing Systems, 34:28798–28810, 2021.
266
+ Zhilin Yang, William Cohen, and Ruslan Salakhudinov. Revisiting semi-supervised learning with graph embeddings. In International conference on machine learning, pp. 40–48. PMLR, 2016.
267
+ Michihiro Yasunaga, Rui Zhang, Kshitijh Meelu, Ayush Pareek, Krishnan Srinivasan, and Dragomir Radev. Graph-based neural multi-document summarization. arXiv preprint arXiv:1706.06681, 2017.
268
+ Michihiro Yasunaga, Hongyu Ren, Antoine Bosselut, Percy Liang, and Jure Leskovec. Qa-gnn: Reasoning with language models and knowledge graphs for question answering. arXiv preprint arXiv:2104.06378, 2021.
269
+ Michihiro Yasunaga, Antoine Bosselut, Hongyu Ren, Xikun Zhang, Christopher D Manning, Percy S Liang, and Jure Leskovec. Deep bidirectional language-knowledge graph pretraining. Advances in Neural Information Processing Systems, 35:37309–37323, 2022.
270
+ Jiawei Zhang. Graph-toolformer: To empower llms with graph reasoning ability via prompt augmented by chatgpt. arXiv preprint arXiv:2304.11116, 2023.
271
+ Shichang Zhang, Yozen Liu, Yizhou Sun, and Neil Shah. Graph-less neural networks: Teaching old mlps new tricks via distillation. arXiv preprint arXiv:2110.08727, 2021.
272
+ Xikun Zhang, Antoine Bosselut, Michihiro Yasunaga, Hongyu Ren, Percy Liang, Christopher D Manning, and Jure Leskovec. Greaselm: Graph reasoning enhanced language models. In International conference on learning representations, 2022.
273
+ Jianan Zhao, Meng Qu, Chaozhuo Li, Hao Yan, Qian Liu, Rui Li, Xing Xie, and Jian Tang. Learning on large-scale text-attributed graphs via variational inference. arXiv preprint arXiv:2210.14709, 2022.
274
+ Zihao Zhao, Eric Wallace, Shi Feng, Dan Klein, and Sameer Singh. Calibrate before use: Improving few-shot performance of language models. In International Conference on Machine Learning, pp. 12697–12706. PMLR, 2021.
275
+ Jie Zhou, Xu Han, Cheng Yang, Zhiyuan Liu, Lifeng Wang, Changcheng Li, and Maosong Sun. Gear: Graph-based evidence aggregating and reasoning for fact verification. arXiv preprint arXiv:1908.01843, 2019.
276
+ Jason Zhu, Yanling Cui, Yuming Liu, Hao Sun, Xue Li, Markus Pelger, Tianqi Yang, Liangjie Zhang, Ruofei Zhang, and Huasha Zhao. Textgnn: Improving text encoder via graph neural network in sponsored search. In Proceedings of the Web Conference 2021, pp. 2848–2857, 2021.
277
+
278
+ # A THEORETICAL ANALYSIS
279
+
280
+ In this section, we aim to demonstrate that explanations generated by an LLM can provide valuable features for another model (such as a smaller LM). This is true under two key conditions:
281
+
282
+ 1. Fidelity: The explanations effectively represent LLM’s reasoning over the raw text, containing most of the information from the LLM’s hidden state. 2. Non-redundancy: The LLM possesses unique knowledge not captured by another model.
283
+
284
+ We formulate our theorem as follows:
285
+
286
+ Theorem 1. Given the following conditions:
287
+
288
+ 1) Fidelity: $E$ is a good proxy for $Z _ { L }$ such that
289
+
290
+ $$
291
+ H ( Z _ { l } | E ) = \epsilon , \quad \epsilon > 0
292
+ $$
293
+
294
+ 2) Non-redundancy: $Z _ { L }$ contains information not present in $Z$ , expressed as
295
+
296
+ $$
297
+ { \cal H } ( y | Z , Z _ { L } ) = { \cal H } ( y | Z ) - \epsilon ^ { \prime } , \quad \epsilon ^ { \prime } > \epsilon
298
+ $$
299
+
300
+ Then, it follows that:
301
+
302
+ $$
303
+ H ( y | Z , E ) < H ( y | Z )
304
+ $$
305
+
306
+ where $E$ is textual explanations generated by an LLM, $Z _ { L }$ is the vectorial representation of the raw text modeled by the LLM, $Z$ is the vectorial representation of the raw text modeled by the other model, $y$ is the target and $H ( \cdot | \cdot )$ is the conditional entropy.
307
+
308
+ Proof. We aim to demonstrate that the conditional entropy of $y$ given both $Z$ and $E$ , denoted as $H ( y | Z , E )$ , is less than the conditional entropy of $y$ given only $Z$ , denoted as $H ( y | Z )$ .
309
+
310
+ Starting with:
311
+
312
+ $$
313
+ H ( y | Z , E )
314
+ $$
315
+
316
+ We apply the properties of entropy to decompose this expression into two components:
317
+
318
+ $$
319
+ H ( y | Z , E ) = H ( y | Z , Z _ { L } , E ) + I ( y ; Z _ { L } | Z , E )
320
+ $$
321
+
322
+ Now, we utilize the following upper bound of conditional mutual information:
323
+
324
+ $$
325
+ \begin{array} { r l r } { { I ( y ; Z _ { L } | Z , E ) = H ( Z _ { L } | Z , E ) - H ( Z _ { L } | y , Z , E ) } } \\ & { } & { \leq H ( Z _ { L } | Z , E ) } \end{array}
326
+ $$
327
+
328
+ where the first line follows from the definition of mutual information, and the second line follows from the nonnegativity of conditional entropy.
329
+
330
+ Substituting equation 14 into equation 12, we rewrite the conditional entropy as:
331
+
332
+ $$
333
+ H ( y | Z , E ) \le H ( y | Z , Z _ { L } , E ) + H ( Z _ { L } | Z , E )
334
+ $$
335
+
336
+ Since conditional entropy increases when conditioning on fewer variables, we further have:
337
+
338
+ $$
339
+ H ( y | Z , Z _ { L } , E ) + H ( Z _ { L } | Z , E ) \leq H ( y | Z , Z _ { L } ) + H ( Z _ { L } | E )
340
+ $$
341
+
342
+ Applying the "Fidelity" and "Non-redundancy" conditions:
343
+
344
+ $$
345
+ H ( y | Z , Z _ { L } ) + H ( Z _ { L } | E ) \le H ( y | Z ) - \epsilon ^ { \prime } + \epsilon
346
+ $$
347
+
348
+ Finally, as $\epsilon ^ { \prime } > \epsilon$ , we have:
349
+
350
+ $$
351
+ H ( y | Z ) - \epsilon ^ { \prime } + \epsilon < H ( y | Z )
352
+ $$
353
+
354
+ Consequently, we have proven that:
355
+
356
+ $$
357
+ H ( y | Z , E ) < H ( y | Z )
358
+ $$
359
+
360
+ This completes the proof.
361
+
362
+ # B TIME ANALYSIS AND MONEY ESTIMATION
363
+
364
+ Our primary dataset, ogbn-arxiv, with 169,343 nodes and 1,166,243 edges, serves as a representative case for our approach. On average, our input sequences consist of approximately 285 tokens, while the output sequences comprise around 164 tokens. For the ChatGPT-3.5 Turbo API, priced at $\$ 0.0015$ per 1,000 input tokens and $\$ 0.002$ per 1,000 output tokens, with a token per minute rate limit of 90,000, the monetary estimation for ogbn-arxiv is as follows:
365
+
366
+ $$
367
+ C o s t = ( ( 2 8 5 \times 0 . 0 0 1 5 ) / 1 0 0 0 + ( 1 6 4 \times 0 . 0 0 2 ) / 1 0 0 0 ) \times 1 6 9 , 3 4 3 \approx 1 2 8 ~ U S D
368
+ $$
369
+
370
+ Considering the token rate limit, we estimate the deployment time as follows:
371
+
372
+ $$
373
+ T i m e = 1 6 9 , 3 4 3 / ( 9 0 , 0 0 0 / 2 8 5 ) \approx 5 3 6 m i n \approx 9 h
374
+ $$
375
+
376
+ Cost-Effective Alternatives. Additionally, we have explored cost-effective alternatives, such as leveraging open-source LLMs like llama2. The use of llama2 is entirely free, and the querying process to llama2-13b-chat takes approximately 16 hours when utilizing 4 A5000 GPUs.
377
+
378
+ Efficiency through Single Query and Reuse. Our method requires only one query to the LLM, with predictions and explanations stored for subsequent use. This not only enhances efficiency but also minimizes the number of API calls, contributing to cost-effectiveness. We also release the gpt responses for public use.
379
+
380
+ # C ADDRESSING LABEL LEAKAGE CONCERNS WITH A NEW DATASET
381
+
382
+ GPT-3.5’s training data might include certain arXiv papers, given its comprehensive ingestion of textual content from the internet. However, the precise composition of these arXiv papers within GPT-3.5’s training remains undisclosed, rendering it infeasible to definitively identify their inclusion. It is essential to emphasize that the challenge of label leakage is widespread and affects various language model benchmarks, such as the prominent BIG-bench (Srivastava et al., 2022) and TruthfulQA (Lin et al., 2021).
383
+
384
+ To address this concern, we created a novel dataset tape-arxiv23 for our experiments. We made sure that this dataset only included papers published in 2023 or later, which is well beyond the knowledge cutoff for GPT-3.5, as it was launched in November 2022. The creation of this new dataset was meticulously executed. We collected all cs.ArXiv papers published from January 2023 to September 2023 from the arXiv daily repository 2. We then utilized the Semantic Scholar API 3 to retrieve citation relationships. This process yielded a comprehensive graph containing 46,198 papers and 78,548 connections. Our codes to collect and build the dataset is available at: https://github.com/XiaoxinHe/tape_arxiv_2023.
385
+
386
+ # D LLAMA AS A COST-EFFICIENT ALTERNATIVE
387
+
388
+ We extend out experiment to the open-source LLM "llama-2-13b-chat" (llama for short), which demonstrates the feasibility of a cost-effective (free) alternative, see Table 4.
389
+
390
+ It is worth noting that although llama exhibits a lower performance compared to GPT-3.5 in terms of both zero-shot accuracy and explanation quality, our pipeline still maintains its robust performance. As an illustration, we achieved an accuracy of $7 6 . 1 9 \%$ on the ogbn-arxiv dataset using llama, slightly below the $7 7 . 5 0 \%$ achieved with GPT-3.5. We attribute this impressive level of generalization to the complementary nature of the explanations themselves, which serve as a rich source of semantic information supplementing the original text such as title and abstract.
391
+
392
+ Table 4: Node classification accuracy for the Cora, PubMed and ogbn-arxiv datasets.
393
+
394
+ <table><tr><td rowspan="2">Dataset</td><td rowspan="2">Method</td><td colspan="3">llama2-13b-chat</td><td colspan="3">GPT3.5</td></tr><tr><td>LLM</td><td>LMfinetune</td><td>hTAPE</td><td>LLM</td><td>LMfinetune</td><td>hTAPE</td></tr><tr><td rowspan="3">Cora</td><td>GCN</td><td>0.5746</td><td>0.6845 ± 0.0194</td><td>0.9045 ± 0.0231</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>0.9119 ± 0.0158</td></tr><tr><td>SAGE</td><td>0.5746</td><td>0.6845 ± 0.0194</td><td>0.9170 ± 0.0337</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>0.9290 ± 0.0307</td></tr><tr><td>RevGAT</td><td>0.5746</td><td>0.6845 ± 0.0194</td><td>0.9313 ± 0.0237</td><td>0.6769</td><td>0.7606 ± 0.0378</td><td>0.9280 ± 0.0275</td></tr><tr><td rowspan="3">PubMed</td><td>GCN</td><td>0.3958</td><td>0.9121 ± 0.0026</td><td>0.9362 ± 0.0050</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>0.9431 ± 0.0043</td></tr><tr><td>SAGE</td><td>0.3958</td><td>0.9121 ± 0.0026</td><td>0.9581 ± 0.0073</td><td>0.9342</td><td>0.9494± 0.0046</td><td>0.9618 ± 0.0053</td></tr><tr><td>RevGAT</td><td>0.3958</td><td>0.9121 ± 0.0026</td><td>0.9561 ± 0.0068</td><td>0.9342</td><td>0.9494 ± 0.0046</td><td>0.9604 ± 0.0047</td></tr><tr><td rowspan="3">ogbn-arxiv</td><td>GCN</td><td>0.4423</td><td>0.6941 ± 0.0020</td><td>0.7418 ± 0.0031</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>0.7520 ± 0.0003</td></tr><tr><td>SAGE</td><td>0.4423</td><td>0.6941 ±0.0020</td><td>0.7536 ±0.0028</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>0.7672 ± 0.0007</td></tr><tr><td>RevGAT</td><td>0.4423</td><td>0.6941 ± 0.0020</td><td>0.7619 ± 0.0027</td><td>0.7350</td><td>0.7361 ± 0.0004</td><td>0.7750 ± 0.0012</td></tr><tr><td rowspan="3">tape-arxiv23</td><td>GCN</td><td>0.4452</td><td>0.7677 ± 0.0042</td><td>0.8045 ± 0.0264</td><td>0.7356</td><td>0.7832 ±0.0052</td><td>0.8080 ±0.0215</td></tr><tr><td>SAGE</td><td>0.4452</td><td>0.7677 ± 0.0042</td><td>0.8378 ± 0.0302</td><td>0.7356</td><td>0.7832 ± 0.0052</td><td>0.8388 ± 0.0264</td></tr><tr><td>RevGAT</td><td>0.4452</td><td>0.7677 ± 0.0042</td><td>0.8407 ± 0.0308</td><td>0.7356</td><td>0.7832 ±0.0052</td><td>0.8423 ± 0.0256</td></tr></table>
395
+
396
+ # E CASE STUDY
397
+
398
+ ![](images/adb669e6b917050605a38eb040dedd55b71c0fc47f6733dc89357161fbb465a9.jpg)
399
+ Figure 3: Case study comparing features for node classification on the PubMed dataset: (a) Original text attributes and (b) Explanations generated by LLMs. The GNN model trained with (b) accurately predicts the label for node 12390 (type 2 diabetes), while the model trained with (a) predicts the incorrect label (experimentally induced diabetes). This improvement can be attributed to the concise and focused nature of LLM-generated explanations, as well as their reasoning ability and utilization of external knowledge.
400
+
401
+ To investigate the impact of using explanations as features in improving node classification on TAGs, we conduct an analysis on predicted samples from the PubMed dataset. Figure 3 presents a case where the GNN model trained with original text attributes as features incorrectly predicts the label for node 12390 (as experimentally induced diabetes), while the model trained with explanations generated by LLMs as features correctly predicts the label (as type 2 diabetes).
402
+
403
+ This improvement can be attributed to two main factors. Firstly, compared to the original text attributes, which consist of the title and abstract text, the explanations generated by the LLM are more concise and focused. This aids the subsequent LM in generating node embeddings that capture the essential semantics without the need to compress an excessive amount of information into a fixedlength representation. Secondly, LLMs possess reasoning capabilities and the ability to leverage general knowledge, which prove crucial in achieving accurate predictions. For instance, the explanations generated by LLMs explicitly link type 2 diabetes to MKR mice and db/db mice (which are common animal models of type 2 diabetes), as well as the insulinopenic mice / streptozotocin to experimentally induced diabetes. This knowledge is either absent or only implicitly specified in the original text attributes.
404
+
405
+ # F PROMPT DESIGN
406
+
407
+ Table 5 outlines the prompts used for various datasets. Each prompt includes the abstract and title of the paper, followed by a task-specific question. The question is formulated to query the model about a particular aspect of the paper and request an explanation for the prediction. The answer section is left blank for the model to fill in. Generally, our analysis finds that the current instructions allow the LLM to produce output that conforms well to the expected format without significant deviations, allowing the answers to be straightforwardly extracted from the text output of the LLM.
408
+
409
+ Table 5: Prompts used in this work to query the LLM.
410
+
411
+ <table><tr><td>Dataset</td><td>Prompt</td></tr><tr><td>Cora</td><td>Abstract: &lt;abstract text&gt;\n Title: &lt;title text&gt;\n Question: Which of the following sub-categories of AI does this paper belong to: Case Based,Genetic Algorithms, Neural Networks, Probabilistic Methods,Reinforcement Learning,Rule Learning, Theory? If multiple options apply,provide a comma-separated list ordered from most to least related, then for each choice you gave,explain how it is present in the text.\n\nAnswer:</td></tr><tr><td>Pubmed</td><td>Abstract: &lt;abstract text&gt; \n Title: &lt;title text&gt; \n Question: Does the paper involve any cases of Type 1 diabetes,Type 2 diabetes,or Experimentally induced diabetes? Please give one or more answers of either Type 1 diabetes,Type 2 diabetes,or Ex- perimentally induced diabetes; if multiple options apply, provide a comma-separated list ordered from most to least related, then for each choice you gave, give a detailed explanation with quotes from the text explaining why it is related to the chosen op- tion.\n\n Answer:</td></tr><tr><td>ogbn-arxiv</td><td>Abstract: &lt;abstract text&gt;\n Title: &lt;title text&gt; \n Question: Which arXiv CS sub- category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form“cs.XX&quot;,and provide your reasoning. \n\n Answer:</td></tr><tr><td>ogbn-products</td><td>Product description: &lt;product description&gt;\n Question: Which of the following cat- egory does this product belong to: 1) Home &amp; Kitchen,2) Health &amp; Personal Care,3) Beauty,4) Sports &amp; Outdoors,5) Books,6)Patio,Lawn &amp; Garden,7) Toys &amp; Games, 8) CDs &amp; Vinyl,9) Cell Phones &amp; Accessories,10) Grocery &amp; Gourmet Food,11) Arts,Crafts &amp; Sewing,12) Clothing,Shoes &amp; Jewelry,13) Electronics,14) Movies &amp; TV,15) Software,16) Video Games,17) Automotive,18) Pet Supplies,19) Office Products,20) Industrial &amp; Scientific,21) Musical Instruments,22) Tools &amp; Home Improvement,23)Magazine Subscriptions,24) Baby Products,25) NAN,26) Ap- pliances,27) Kitchen &amp; Dining,28)Collectibles &amp; Fine Art,29) All Beauty,30) Luxury Beauty, 31) Amazon Fashion, 32) Computers,33) All Electronics,34) Pur- chase Circles,35) MP3 Players &amp; Accessories,36) Gift Cards,37) Office &amp; School Supplies,38) Home Improvement,39) Camera &amp; Photo,40) GPS &amp; Navigation,41) Digital Music,42) Car Electronics,43) Baby,44) Kindle Store,45) Kindle Apps,46) Furniture &amp; Decor? Give 5 likely categories as a comma-separated list ordered from</td></tr><tr><td>tape-arxiv23</td><td>most to least likely,and provide your reasoning.\n \n Answer: Abstract: &lt;abstract text&gt; \n Title: &lt;title text&gt; \n Question: Which arXiv CS sub- category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form“cs.XX&quot;,and provide your reasoning. \n\n Answer:</td></tr></table>
412
+
413
+ Exploring Prompt Variations. We have extensively explored the influence of various prompts on the ogbn-arxiv dataset, as outlined in Table 6 and Table 7.
414
+
415
+ Table 6 indicates that, generally, most prompts yield similar performance. However, a minor performance improvement is observed when the title is positioned after the abstract. This finding aligns with the principle suggested by Zhao et al. (2021) that placing more critical information later in the prompt can be beneficial.
416
+
417
+ Further analysis presented in Table 7 demonstrates a positive correlation between the LLM’s zeroshot accuracy and the overall accuracy of our method, implying that higher zero-shot prediction scores lead to enhanced TAPE accuracy. Despite the variation in prompt designs, our methodology consistently achieves similar accuracy levels, ranging from 0.7660 to 0.7750 with the RevGAT as the GNN backbone. This consistency underscores the robustness of our proposed TAPE to different prompt configurations.
418
+
419
+ Table 6: Prompts used for our experiments studying the effect of different prompts. Most prompts have similar performance.
420
+
421
+ <table><tr><td>Description</td><td>Prompt</td><td>Accuracy</td></tr><tr><td>Default prompt</td><td>Abstract: &lt;abstract text&gt;\n Title: &lt;title text&gt; \n Question: Which arXiv CS sub-category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form “cs.XX&quot;,and provide your reason- ing. \n \n Answer:</td><td>0.720</td></tr><tr><td>Title first</td><td>Title: &lt;title text&gt; \n Abstract: &lt;abstract text&gt; \n Question: Which arXiv CS sub-category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form “cs.XX&quot;,and provide your reason- ing.\n\n Answer:</td><td>0.695</td></tr><tr><td>Focus on text content</td><td>Title: &lt;title text&gt;\n Abstract: &lt;abstract text&gt; \n Question: Which arXiv CS sub-category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form“cs.XX&quot;.Focus only on content in the actual text and avoid making false associations.Then provide your reasoning.</td><td>0.695</td></tr><tr><td>Chain of thought prompt</td><td>Title: &lt;title text&gt; \n Abstract: &lt;abstract text&gt;\n Question: Which arXiv CS sub-category does this paper belong to? Give 5 likely arXiv CS sub-categories as a comma-separated list ordered from most to least likely,in the form“cs.XX&quot;.Please think about the categorization in a step by step manner and avoid making false associations. Then provide your reasoning.</td><td>0.705</td></tr></table>
422
+
423
+ Table 7: Study of the robustness of prompt on ogbn-arxiv dataset.
424
+
425
+ <table><tr><td></td><td>LLM (zero-shot)</td><td>TAPE (GCN)</td><td>TAPE (SAGE)</td><td>TAPE (RevGAT)</td></tr><tr><td>Default prompt</td><td>0.720</td><td>0.7520±0.0003</td><td>0.7672 ± 0.0007</td><td>0.7750 ± 0.0012</td></tr><tr><td>Focus on text content</td><td>0.695</td><td>0.7425 ± 0.0021</td><td>0.7598 ± 0.0006</td><td>0.7660 ± 0.0017</td></tr><tr><td>Chain of thought prompt</td><td>0.705</td><td>0.7424 ± 0.0019</td><td>0.7597 ± 0.0034</td><td>0.7667 ± 0.0028</td></tr></table>
426
+
427
+ # G DATASET
428
+
429
+ We conduct experiments on five TAGs – Cora (McCallum et al., 2000), PubMed (Sen et al., 2008), ogbn-arxiv, ogbn-products (Hu et al., 2020a), and tape-arxiv23. For Cora and PubMed, we collected the raw text data since they are not available in common repositories like PyG and DGL. For ogbn-products, given its substantial scale of 2 million nodes and 61 million edges, we have employed a node sampling strategy to obtain a subgraph containing 54k nodes and 74k edges. Additionally, we introduced the tape-arxiv23 citation graph dataset, extending beyond the knowledge cutoff of GPT-3. This dataset serves as a valuable resource for the research community. Table 8 provides a summary of the dataset statistics.
430
+
431
+ # G.1 DATASET DESCRIPTION
432
+
433
+ Cora (McCallum et al., 2000). The Cora dataset comprises 2,708 scientific publications classified into one of seven classes – case based, genetic algorithms, neural networks, probabilistic methods, reinforcement learning, rule learning, and theory, with a citation network consisting of 5,429 links. The papers were selected in a way such that in the final corpus every paper cites or is cited by at least one other paper.
434
+
435
+ Table 8: Statistics of the TAG datasets
436
+
437
+ <table><tr><td>Dataset</td><td>#Nodes</td><td>#Edges</td><td>Task</td><td>Metric</td><td>Augmentation</td></tr><tr><td>Cora</td><td>2,708</td><td>5,429</td><td>7-class classif.</td><td> Accuracy</td><td></td></tr><tr><td>Pubmed</td><td>19,717</td><td>44,338</td><td>3-class classif.</td><td>Accuracy</td><td></td></tr><tr><td>ogbn-arxiv</td><td>169,343</td><td>1,166,243</td><td>40-class classif.</td><td>Accuracy</td><td></td></tr><tr><td>ogbn-products (subset)</td><td>54,025</td><td>74,420</td><td>47-class classif.</td><td>Accuracy</td><td></td></tr><tr><td>tape-arxiv23</td><td>46,198</td><td>78,548</td><td>40-class-classif.</td><td>Accuracy</td><td>√</td></tr></table>
438
+
439
+ PubMed (Sen et al., 2008). The Pubmed dataset consists of 19,717 scientific publications from PubMed database pertaining to diabetes classified into one of three classes – Experimental induced diabetes, Type 1 diabetes, and Type 2 diabetes. The citation network consists of 44,338 links.
440
+
441
+ ogbn-arxiv (Hu et al., 2020a). The ogbn-arxiv dataset is a directed graph that represents the citation network between all computer science arXiv papers indexed by MAG (Wang et al., 2020). Each node is an arXiv paper, and each directed edge indicates that one paper cites another one. The task is to predict the 40 subject areas of arXiv CS papers, e.g.,, cs.AI, cs.LG, and cs.OS, which are manually determined (i.e., labeled) by the paper’s authors and arXiv moderators.
442
+
443
+ ogbn-products (Hu et al., 2020a). The ogbn-products dataset represents an Amazon product co-purchasing network, with product descriptions as raw text. Nodes represent products sold in Amazon, and edges between two products indicate that the products are purchased together. The task is to predict the category of a product in a multi-class classification setup, where the 47 toplevel categories are used for target labels.
444
+
445
+ tape-arxiv23. The tape-arxiv23 dataset is a directed graph that represents the citation network between all computer science arXiv papers published in 2023 or later. Similar to ogbn-arxiv, each node is an arXiv paper, and each directed edge indicates that one paper cites another one. The task is to predict the 40 subject areas of arXiv CS papers, e.g.,, cs.AI, cs.LG, and cs.OS, which are manually determined (i.e., labeled) by the paper’s authors and arXiv moderators.
446
+
447
+ # G.2 DATASET SPLITS AND RANDOM SEEDS
448
+
449
+ In our experiments, we adhered to specific dataset splits and employed random seeds for reproducibility. For the ogbn-arxiv and ogbn-products dataset, we adopted the standard train/validation/test split provided by OGB (Hu et al., 2020a). As for the Cora, PubMed datasets, and tape-arxiv23, we performed the train/validation/test splits ourselves, where $60 \%$ of the data was allocated for training, $20 \%$ for validation, and $20 \%$ for testing. Additionally, we utilized random seeds to ensure the reproducibility of our experiments, enabling the consistent evaluation of our proposed method on the respective datasets, which can be found in our linked code repository.
450
+
451
+ G.3 SHALLOW EMBEDDING METHODS FOR NODE FEATURE EXTRACTION
452
+
453
+ Table 9 provides an overview of the text preprocessing and feature extraction methods commonly used in graph libraries such as PyG and DGL, which are widely adopted in GNN research.
454
+
455
+ These text preprocessing and feature extraction methods facilitate the extraction of node features from the text attributes of TAG datasets, enabling the utilization of GNN models for node classification tasks. While these methods are easy to apply and computationally efficient, it is important to note that they rely on traditional language modeling techniques that may not capture the full semantic meaning in the text. This limitation can impact the expressiveness of the extracted node features and potentially affect the development of techniques for downstream tasks.
456
+
457
+ # H EXPERIMENT DETAILS
458
+
459
+ # H.1 COMPUTING ENVIRONMENT AND RESOURCES
460
+
461
+ The implementation of the proposed method utilized the PyG and DGL modules, which are licensed under the MIT License. The experiments were conducted in a computing environment with the
462
+
463
+ Table 9: Details of text preprocessing and feature extraction methods used for TAG datasets.
464
+
465
+ <table><tr><td>Dataset</td><td>Methods</td><td>Features</td><td>Description</td></tr><tr><td>Cora</td><td>BoW</td><td>1,433</td><td>After stemming and removing stopwords there is a vocabu- lary of size 1,433 unique words. All words with document frequency less than 10 were removed.</td></tr><tr><td>PubMed</td><td>TF-IDF</td><td>500</td><td>Each publication in the dataset is described by a TF/IDF weighted word vector from a dictionary which consists of 500 unique words.</td></tr><tr><td>ogbn-arxiv</td><td>skip-gram128</td><td></td><td>The embeddings of individual words are computed by run- ning the skip-gram model (Mikolov et al.,2013) over the MAG (Wang et al.,2020) corpus.</td></tr><tr><td>ogbn-productsBoW</td><td></td><td>100</td><td>Node features are generated by extracting_BoW features from the product descriptions followed by a Principal Com- ponent Analysis to reduce the dimension to 100.</td></tr><tr><td>tape-arxiv23</td><td>word2vec300</td><td></td><td>The embeddings of individual words are computed by run- ning the word2vec model.</td></tr></table>
466
+
467
+ following specifications: LM-based experiments were performed on four NVIDIA RTX A5000 GPUs, each with 24GB VRAM. On the other hand, the GNN-based experiments were conducted on a single GPU.
468
+
469
+ # H.2 HYPERPARAMETERS
470
+
471
+ Table 10 provides an overview of the hyperparameters used for the GCN (Kipf & Welling, 2016), SAGE (Hamilton et al., 2017), and RevGAT (Li et al., 2021) models. These hyperparameters were selected based on the official OGB repository 4, and the RevGAT and language model hyperparameters follow those used in the GLEM repository 5. It is important to note that these hyperparameters were not tuned on a per-dataset basis, but instead were used consistently across all three TAG datasets based on those from prior work, and also set consistently across both our proposed method and the baselines. This demonstrates the generality and ease of use of our method, as well as its compatibility with existing GNN baselines.
472
+
473
+ Table 10: Hyperparameters for the GCN, SAGE, and RevGAT models.
474
+
475
+ <table><tr><td>Hyperparameters</td><td>GCN</td><td>SAGE</td><td>RevGAT</td></tr><tr><td>#layers</td><td>3</td><td>3</td><td>3</td></tr><tr><td>hidden dim</td><td>256</td><td>256</td><td>256</td></tr><tr><td>learning rate</td><td>0.01</td><td>0.01</td><td>0.002</td></tr><tr><td>dropout</td><td>0.5</td><td>0.5</td><td>0.75</td></tr><tr><td>epoch</td><td>1000</td><td>1000</td><td>1000</td></tr><tr><td>warmup epochs</td><td>0</td><td>0</td><td>50</td></tr><tr><td>early stop</td><td>50</td><td>50</td><td>50</td></tr></table>
476
+
477
+ # H.3 DETAILED ABLATION STUDY
478
+
479
+ We conducted a detailed ablation study on the ogbn-arxiv dataset to assess the impact of different sources of node features. The study focused on three types of node features: original text features $( h _ { \mathrm { o r i g } } )$ , explanation as features $( h _ { \mathrm { e x p l } } )$ , and predictions as features $( h _ { \mathrm { p r e d } } )$ . We systematically removed one of these features at a time while keeping the other components unchanged in our model.
480
+
481
+ The results of the ablation study are illustrated in Figure 4. The figure presents the performance of the model when each type of node feature is removed. It is observed that using the full set of features
482
+
483
+ <table><tr><td>Ablation</td><td>GCN</td><td>SAGE</td><td>RevGAT</td></tr><tr><td>Full</td><td>0.7520± 0.0003</td><td>0.7672 ± 0.0007</td><td>0.7750 ± 0.0012</td></tr><tr><td>- horig</td><td>0.7471 ± 0.0007</td><td>0.7433 ± 0.0005</td><td>0.7656 ± 0.0038</td></tr><tr><td>- hexpl</td><td>0.7506 ± 0.0011</td><td>0.7528 ± 0.0024</td><td>0.7693 ± 0.0033</td></tr><tr><td>- hpred</td><td>0.7519 ± 0.0019</td><td>0.7605 ± 0.0008</td><td>0.7686 ± 0.0051</td></tr></table>
484
+
485
+ Figure 4: Effect of node features. We study the effects of different sources of node features on the ogbn-arxiv dataset, i.e., original text features $( h _ { \mathrm { o r i g } } )$ , explanation as features $( h _ { \mathrm { e x p l } } )$ and predictions as features $( h _ { \mathrm { p r e d } } )$ , by removing one of them in turn from our model while keeping the other components unchanged.
486
+
487
+ yields the best performance, while leaving out any of the features leads to a drop in performance.
488
+ However, the extent of the performance drop may vary depending on the specific GNN model used.
489
+
490
+ This ablation study provides additional insights to complement the findings presented in section 5.3. While Table 3 compared the performance of using the full set of features versus using just one of them, this ablation study specifically focuses on comparing the performance of using the full set of features versus leaving one of them out. Although the experimental design differs, the overall message conveyed remains consistent, emphasizing the significance of considering all the various sources of node features for achieving optimal performance in node classification tasks.
491
+
492
+ # I EFFECT OF LM FINETUNING
493
+
494
+ We conduct an ablation study on ogbn-arxiv to explore the impact of language model (LM) fine-tuning. Specifically, we aim to address the following research questions (RQs):
495
+
496
+ • RQ1: Is fine-tuning the LM necessary? • RQ2: Is it necessary to use different LMs for encoding the original text and explanations?
497
+
498
+ To address these questions, we examine three settings: 1) Without Fine-Tuning: Utilizing a pretrained LM to encode the original text and the explanations without any fine-tuning. 2) Fine-Tuning (Same LM): Fine-tuning a single LM for both the original text and the explanations. 3) Fine-Tuning (Different LMs): Fine-tuning two separate LMs, one for the original text and another for the explanations.
499
+
500
+ Table 11: Effect of LM finetuning on ogbn-arxiv
501
+
502
+ <table><tr><td>LM</td><td>MLP</td><td>GCN</td><td>SAGE</td><td>RevGAT</td></tr><tr><td>Without Fine-Tuning</td><td>0.5797 ± 0.0217</td><td>0.4178 ± 0.1148</td><td>0.4507 ± 0.0529</td><td>0.7507 ± 0.0189</td></tr><tr><td>Fine-Tuning (Same LM)</td><td>0.7566 ± 0.0015</td><td>0.7442 ± 0.0012</td><td>0.7676 ± 0.0032</td><td>0.7728 ± 0.0014</td></tr><tr><td>Fine-Tuning (Different LMs)</td><td>0.7587 ± 0.0015</td><td>0.7520 ± 0.0003</td><td>0.7672 ±0.0007</td><td>0.7750 ±0.0012</td></tr></table>
503
+
504
+ Our observations include:
505
+
506
+ For RQ1: Table 11 underscores the importance of fine-tuning the LM. It reveals a marked decline in performance without fine-tuning, compared with the settings where the LM is fine-tuned.
507
+
508
+ For RQ2: Fine-tuning, whether with the same LM or with different LMs, yields similar outcomes, with a slight advantage for using two distinct LMs. However, the marginal difference suggests that our approach could be simplified and expedited by utilizing a single LM.
509
+
510
+ # J EFFECT OF DIFFERENT LMS
511
+
512
+ To access the influence of different LMs, we expand our investigation beyond deberta-base. Specifically, following the approach taken in SimTAG (Duan et al., 2023), we include two additional widely-used LMs from the MTEB (Muennighoff et al., 2022) leaderboard. The selection is based on
513
+
514
+ their model size and performance in classification and retrieval tasks: all-roberta-large-v1 (Reimers & Gurevych, 2019) and e5-large (Wang et al., 2022). The outcomes of our study are detailed in
515
+
516
+ Table 12: Effect of different LMs on ogbn-arxiv
517
+
518
+ <table><tr><td>LM</td><td>MLP</td><td>GCN</td><td>SAGE</td><td>RevGAT</td></tr><tr><td>deberta-base</td><td>0.7587 ± 0.0015</td><td>0.7520 ± 0.0003</td><td>0.7672 ± 0.0007</td><td>0.7750 ± 0.0012</td></tr><tr><td>all-roberta-large-v1</td><td>0.7587 ± 0.0003</td><td>0.7412 ± 0.0015</td><td>0.7695 ± 0.0008</td><td>0.7737 ± 0.0004</td></tr><tr><td>e5-large</td><td>0.7595 ± 0.0015</td><td>0.7443 ± 0.0021</td><td>0.7688 ± 0.0010</td><td>0.7730 ± 0.0006</td></tr></table>
519
+
520
+ Table 12. Notably, our model exhibits insensitivity to the choice of a specific LM, underscoring its robustness to variations in LM selection.
521
+
522
+ # K MEMORY UTILIZATION
523
+
524
+ Table 13 presents the memory utilization for experiments conducted on the ogbn-arxiv dataset.
525
+
526
+ Table 13: Memory Usage on ogbn-arxiv dataset with DeBERTa-base ad LM backbone and RevGAT as GNN backbone for comparision of different training paradigms of fusing LMs and GNNs, including our proposed method and the state-of-the-art GLEM method. All experiments are performed on 4 NVIDIA RTX A5000 24GB GPUs with a batch size of 36.
527
+
528
+ <table><tr><td rowspan="2">Model</td><td colspan="2">Memory</td><td rowspan="2">Accuracy</td></tr><tr><td>LM</td><td>GNN</td></tr><tr><td>Pure LM</td><td>8,834 MB</td><td>1</td><td>0.7361 ± 0.0004</td></tr><tr><td>GNN w/ shallow feature</td><td>一</td><td>4,430 MB</td><td>0.7083 ± 0.0017</td></tr><tr><td>LM-based GLEM</td><td>11,064 MB</td><td>8,112 MB</td><td>0.7657 ± 0.0029</td></tr><tr><td>LLM-based TAPE (Ours)</td><td>8,834 MB</td><td>4,430 MB</td><td>0.7750 ± 0.0012</td></tr></table>
529
+
530
+ There is a trade-off between memory consumption and accuracy. Our model appears to be the most efficient in terms of memory-to-accuracy ratio. It does not require more memory than the pure LM or GNN with shallow feature models, yet it delivers the best accuracy.
531
+
532
+ # L GLEM
533
+
534
+ Zhao et al. (2022) evaluated GLEM on the ogbn-arxiv dataset. We extended our evaluation of GLEM with the Cora and PubMed datasets for a more comprehensive comparison with our method. Results are reported in Table 14
535
+
536
+ Table 14: GLEM (Zhao et al., 2022)
537
+
538
+ <table><tr><td>Dataset</td><td>GCN</td><td>SAGE</td><td>RevGAT</td></tr><tr><td>Cora</td><td>0.8732 ± 0.0066</td><td>0.8801 ±0.0054</td><td>0.8856± 0.006</td></tr><tr><td>PubMed</td><td>0.9469 ± 0.0010</td><td>0.9459 ± 0.0018</td><td>0.9471 ± 0.002</td></tr><tr><td>ogbn-arxiv</td><td>0.7593 ± 0.0019</td><td>0.7550 ± 0.0024</td><td>0.7697 ± 0.0019</td></tr></table>
parse/test/RXFVcynVe1/RXFVcynVe1_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/RXFVcynVe1/RXFVcynVe1_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/RXFVcynVe1/RXFVcynVe1_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/UU9Icwbhin/UU9Icwbhin.md ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RETENTIVE NETWORK: A SUCCESSOR TO TRANSFORMER FOR LARGE LANGUAGE MODELS
2
+
3
+ Anonymous authors Paper under double-blind review
4
+
5
+ # ABSTRACT
6
+
7
+ In this work, we propose Retentive Network (RETNET) as a foundation architecture for large language models, simultaneously achieving training parallelism, low-cost inference, and good performance. We theoretically derive the connection between recurrence and attention. Then we propose the retention mechanism for sequence modeling, which supports three computation paradigms, i.e., parallel, recurrent, and chunkwise recurrent. Specifically, the parallel representation allows for training parallelism. The recurrent representation enables low-cost $O ( 1 )$ inference, which improves decoding throughput, latency, and GPU memory without sacrificing performance. The chunkwise recurrent representation facilitates efficient long-sequence modeling with linear complexity, where each chunk is encoded parallelly while recurrently summarizing the chunks. Experimental results on language modeling show that RETNET achieves favorable scaling results, parallel training, low-cost deployment, and efficient inference. The intriguing properties make RETNET a strong successor to Transformer for large language models.
8
+
9
+ # 1 INTRODUCTION
10
+
11
+ Transformer (Vaswani et al., 2017) has become the de facto architecture for large language models, which was initially proposed to overcome the sequential training issue of recurrent models (Hochreiter & Schmidhuber, 1997). However, training parallelism of Transformers is at the cost of inefficient inference, because of the $O ( N )$ complexity per step and memory-bound key-value cache (Shazeer, 2019), which renders Transformers unfriendly to deployment. The growing sequence length increases GPU memory consumption as well as latency and reduces inference speed. Numerous efforts have continued to develop the next-generation architecture, aiming at retaining training parallelism and competitive performance as Transformers while having efficient $O ( 1 )$ inference. It is challenging to achieve the above goals simultaneously, i.e., the so-called “impossible triangle” as shown in Figure 1.
12
+
13
+ ![](images/0b06bf283b78d4d56e7c361dd512c4d9871fd3cc7e676ab044d9a87052a06add.jpg)
14
+ Figure 1: RetNet makes the “impossible triangle” possible, which achieves training parallelism, good performance, and low inference cost simultaneously.
15
+
16
+ There have been three main strands of research. First, linearized attention (Katharopoulos et al., 2020) approximates standard attention scores $\exp ( \pmb q \cdot \pmb k )$ with kernels $\phi ( \pmb q ) \cdot \phi ( \pmb k )$ , so that autoregressive inference can be rewritten in a recurrent form. However, the modeling capability and performance are worse than Transformers, which hinders the method’s popularity. The second strand returns to recurrent models for efficient inference while sacrificing training parallelism. As a remedy, elementwise operators (Peng et al., 2023) are used for acceleration, however, representation capacity and performance are harmed. The third line explores replacing attention with other mechanisms, such as S4 (Gu et al., 2021), and its variants (Dao et al., 2022b; Poli et al., 2023). None of the previous work can break through the impossible triangle, resulting in no clear winner compared with Transformers.
17
+
18
+ In this work, we propose retentive networks (RetNet), achieving low-cost inference, efficient longsequence modeling, Transformer-comparable performance, and parallel model training simultaneously. Specifically, we introduce a multi-scale retention mechanism to substitute multi-head attention, which has three computation paradigms, i.e., parallel, recurrent, and chunkwise recurrent representations. First, the parallel representation empowers training parallelism to utilize GPU devices fully. Second, the recurrent representation enables efficient $O ( 1 )$ inference in terms of memory and computation. The deployment cost and latency can be significantly reduced. Moreover, the implementation is greatly simplified without key-value cache tricks. Third, the chunkwise recurrent representation can perform efficient long-sequence modeling. We parallelly encode each local block for computation speed while recurrently encoding the global blocks to save GPU memory.
19
+
20
+ We compare RetNet with Transformer and its variants. Experimental results on language modeling show that RetNet is consistently competitive in terms of both scaling curves and in-context learning. Moreover, the inference cost of RetNet is length-invariant. For a 7B model and 8k sequence length, RetNet decodes $8 . 4 \times$ faster and saves $70 \%$ of memory than Transformers with key-value caches. During training, RetNet also achieves $2 5 { - } 5 0 \%$ memory saving and $7 \times$ acceleration than standard Transformer and an advantage towards highly-optimized FlashAttention (Dao et al., 2022a). Besides, RetNet’s inference latency is insensitive to batch size, allowing enormous throughput. The intriguing properties make RetNet a strong successor to Transformer for large language models.
21
+
22
+ # 2 RETENTIVE NETWORKS
23
+
24
+ Retentive network (RetNet) is stacked with $L$ identical blocks, which follows a similar layout (i.e., residual connection, and pre-LayerNorm) as in Transformer (Vaswani et al., 2017). Each RetNet block contains two modules: a multi-scale retention (MSR) module, and a feed-forward network (FFN) module. We introduce the MSR module in the following sections. Given an input sequence $x = x _ { 1 } \cdot \cdot \cdot x _ { | x | }$ , RetNet encodes the sequence in an autoregressive way. The input vectors $\{ \bar { \pmb { x } } _ { i } \} _ { i = 1 } ^ { | x | }$ is first packed into $X ^ { 0 } = [ \pmb { x } _ { 1 } , \cdot \cdot \cdot , \pmb { x } _ { | x | } ] \in \mathbb { R } ^ { | x | \times d _ { \mathrm { m o d e l } } }$ , where $d _ { \mathrm { m o d e l } }$ is hidden dimension. Then we compute contextualized vector representations $X ^ { l } = \mathrm { R e t N e t } _ { l } ( X ^ { l - 1 } ) , l \in [ 1 , L ]$ .
25
+
26
+ # 2.1 RETENTION
27
+
28
+ In this section, we introduce the retention mechanism that has a dual form of recurrence and parallelism. So we can train the models in a parallel way while recurrently conducting inference.
29
+
30
+ Given input $X \in \mathbb { R } ^ { | x | \times d _ { \mathrm { m o d e l } } }$ , we project it to one-dimensional function $v ( n ) = X _ { n } \cdot w _ { V }$ . Consider a sequence modeling problem that maps $v ( n ) \mapsto o ( n )$ through states $s _ { n }$ . Let $v _ { n } , o _ { n }$ denote $v ( n ) , o ( n )$ for simplicity. We formulate the mapping in a recurrent manner:
31
+
32
+ $$
33
+ \begin{array} { r l r } { { \pmb { s } _ { n } = { \cal A } \pmb { s } _ { n - 1 } + { \cal K } _ { n } ^ { \top } \boldsymbol { v } _ { n } , } } & { \ } & { \boldsymbol { A } \in \mathbb { R } ^ { d \times d } , { \cal K } _ { n } \in \mathbb { R } ^ { 1 \times d } } \\ & { o _ { n } = { \cal Q } _ { n } \pmb { s } _ { n } = \sum _ { m = 1 } ^ { n } { \cal Q } _ { n } { \cal A } ^ { n - m } { \cal K } _ { m } ^ { \top } \boldsymbol { v } _ { m } , } & { \ } & { \ { \cal Q } _ { n } \in \mathbb { R } ^ { 1 \times d } } \end{array}
34
+ $$
35
+
36
+ where we map $v _ { n }$ to the state vector $s _ { n }$ , and then implement a linear transform to encode sequence information recurrently. Next, we make the projection $Q _ { n } , K _ { n }$ content-aware:
37
+
38
+ $$
39
+ Q = X W _ { Q } , \quad K = X W _ { K }
40
+ $$
41
+
42
+ where $W _ { Q } , W _ { K } \in \mathbb { R } ^ { d \times d }$ are learnable matrices.
43
+
44
+ We diagonalize the matrix $A ~ = ~ \Lambda ( \gamma e ^ { i \theta } ) \Lambda ^ { - 1 }$ , where $\gamma , \theta \ \in \ \mathbb { R } ^ { d }$ . Then we obtain $A ^ { n - m } =$ $\Lambda ( \gamma e ^ { i \theta } ) ^ { \smile - m } \Lambda ^ { - 1 }$ . By absorbing $\Lambda$ into $W _ { Q }$ and $W _ { K }$ , we can rewrite Equation (1) as:
45
+
46
+ $$
47
+ \begin{array} { c } { { \displaystyle o _ { n } = \sum _ { m = 1 } ^ { n } Q _ { n } ( \gamma e ^ { i \theta } ) ^ { n - m } K _ { m } ^ { \intercal } v _ { m } } } \\ { { \displaystyle \ } } \\ { { \displaystyle = \sum _ { m = 1 } ^ { n } ( Q _ { n } ( \gamma e ^ { i \theta } ) ^ { n } ) ( K _ { m } ( \gamma e ^ { i \theta } ) ^ { - m } ) ^ { \intercal } v _ { m } } } \end{array}
48
+ $$
49
+
50
+ where $Q _ { n } ( \gamma e ^ { i \theta } ) ^ { n } , K _ { m } ( \gamma e ^ { i \theta } ) ^ { - m }$ is known as xPos (Sun et al., 2023), i.e., a relative position embedding proposed for Transformer. We further simplify $\gamma$ as a scalar, Equation (3) becomes:
51
+
52
+ $$
53
+ o _ { n } = \sum _ { m = 1 } ^ { n } \gamma ^ { n - m } ( Q _ { n } e ^ { i n \theta } ) ( K _ { m } e ^ { i m \theta } ) ^ { \dagger } v _ { m }
54
+ $$
55
+
56
+ ![](images/9457e55c2304d3514442227b8bfe9a67528dbd5917edf3647beb3b6e49273926.jpg)
57
+ Figure 2: Dual form of RetNet. “GN” is short for GroupNorm.
58
+
59
+ where † is the conjugate transpose. The formulation is easily parallelizable within training instances.
60
+
61
+ In summary, we start with recurrent modeling as shown in Equation (1), and then derive its parallel formulation in Equation (4). We consider the original mapping $v ( n ) \mapsto o ( n )$ as vectors and obtain the retention mechanism as follows.
62
+
63
+ The Parallel Representation of Retention As shown in Figure 2a, the retention layer is defined as:
64
+
65
+ $$
66
+ \begin{array} { c c } { { Q = ( X W _ { Q } ) \odot \Theta , } } & { { K = ( X W _ { K } ) \odot \overline { { { \Theta } } } , \quad V = X W _ { V } } } \\ { { } } & { { } } \\ { { \Theta _ { n } = e ^ { i n \theta } , \quad D _ { n m } = \left\{ \begin{array} { l l } { { \gamma ^ { n - m } , } } & { { n \geq m } } \\ { { 0 , } } & { { n < m } } \end{array} \right. } } \\ { { } } & { { \mathrm { R e t e n t i o n } ( X ) = ( Q K ^ { \top } \odot D ) V } } \end{array}
67
+ $$
68
+
69
+ where $D \in \mathbb { R } ^ { | x | \times | x | }$ combines causal masking and exponential decay along relative distance as one matrix, and $\overline { { \Theta } }$ is the complex conjugate of $\Theta$ . In practice, we map $Q , K \in \mathbb { R } ^ { d } \to \mathbb { C } ^ { d / 2 }$ , add the complex position embedding $\Theta$ , then map them back to $\mathbb { R } ^ { d }$ , following the implementation trick as in LLaMA (Touvron et al., 2023a; Su et al., 2021). Similar to self-attention, the parallel representation enables us to train the models with GPUs efficiently.
70
+
71
+ The Recurrent Representation of Retention As shown in Figure 2b, the proposed mechanism can also be written as recurrent neural networks (RNNs), which is favorable for inference. For the $n$ -th timestep, we recurrently obtain the output as:
72
+
73
+ $$
74
+ \begin{array} { r l } & { S _ { n } = \gamma S _ { n - 1 } + K _ { n } ^ { \intercal } V _ { n } } \\ & { \mathrm { R e t e n t i o n } ( X _ { n } ) = Q _ { n } S _ { n } , \quad n = 1 , \cdots , | x | } \end{array}
75
+ $$
76
+
77
+ where $Q , K , V , \gamma$ are the same as in Equation (5).
78
+
79
+ The Chunkwise Recurrent Representation of Retention A hybrid form of parallel representation and recurrent representation is available to accelerate training, especially for long sequences. We divide the input sequences into chunks. Within each chunk, we follow the parallel representation (Equation (5)) to conduct computation. In contrast, cross-chunk information is passed following the recurrent representation (Equation (6)). Specifically, let $B$ denote the chunk length. We compute the retention output of the $i$ -th chunk via:
80
+
81
+ $$
82
+ \begin{array} { r l } & { Q _ { [ i ] } = Q _ { B i : B ( i + 1 ) } , \quad K _ { [ i ] } = K _ { B i : B ( i + 1 ) } , \quad V _ { [ i ] } = V _ { B i : B ( i + 1 ) } } \\ & { \qquad R _ { i } = K _ { [ i ] } ^ { \top } ( V _ { [ i ] } \odot \zeta ) + \gamma ^ { B } R _ { i - 1 } , \quad \zeta _ { i j } = \gamma ^ { B - i - 1 } } \\ & { \mathrm { R e t e n t i o n } ( X _ { [ i ] } ) = \underbrace { ( Q _ { [ i ] } K _ { [ i ] } ^ { \top } \odot D ) V _ { [ i ] } } _ { \mathrm { I n n e r - C h u n k } } + \underbrace { ( Q _ { [ i ] } R _ { i - 1 } ) \odot \xi } _ { \mathrm { C r o s s - C h u n k } } , \quad \xi _ { i j } = \gamma ^ { i + 1 } } \end{array}
83
+ $$
84
+
85
+ where $[ i ]$ indicates the $i$ -th chunk, i.e., $x _ { [ i ] } = [ x _ { ( i - 1 ) B + 1 } , \cdot \cdot \cdot , x _ { i B } ]$ .
86
+
87
+ # 2.2 GATED MULTI-SCALE RETENTION
88
+
89
+ We use $h = \left. d _ { \mathrm { m o d e l } } \right/ d$ retention heads in each layer, where $d$ is the head dimension. The heads use different parameter matrices $W _ { Q } , W _ { K } , W _ { V } \in \bar { \mathbb { R } } ^ { d \times d }$ . Moreover, multi-scale retention (MSR) assigns different $\gamma$ for each head. For simplicity, we set $\gamma$ identical among different layers and keep them fixed. In addition, we add a swish gate (Hendrycks & Gimpel, 2016; Ramachandran et al., 2017) to increase the non-linearity of retention layers. Formally, given input $X$ , we define the layer as:
90
+
91
+ $$
92
+ { \begin{array} { r l } & { \qquad \gamma = 1 - 2 ^ { - 5 - \operatorname { a r a n g e } ( 0 , h ) } \in \mathbb { R } ^ { h } } \\ & { { \mathrm { h e a d } } _ { i } = { \mathrm { R e t e n t i o n } } ( X , \gamma _ { i } ) } \\ & { \qquad Y = \operatorname { G r o u p N o r m } _ { h } ( \operatorname { C o n c a t } ( { \mathrm { h e a d } } _ { 1 } , \cdots , { \mathrm { h e a d } } _ { h } ) ) } \\ & { { \mathrm { M S R } } ( X ) = ( { \mathrm { s w i s h } } ( X W _ { G } ) \odot Y ) W _ { O } } \end{array} }
93
+ $$
94
+
95
+ where $W _ { G } , W _ { O } \in \mathbb { R } ^ { d _ { \mathrm { m o d e l } } \times d _ { \mathrm { m o d e l } } }$ are learnable parameters, and GroupNorm (Wu & He, 2018) normalizes the output of each head, following SubLN proposed in (Shoeybi et al., 2019). Notice that the heads use multiple $\gamma$ scales, which results in different variance statistics. So we normalize the head outputs separately. The pseudocode of retention is summarized in Appendix D.
96
+
97
+ Retention Score Normalization We utilize the scale-invariant nature of GroupNorm to improve numerical precision of retention layers. Specifically, multiplying a scalar value within GroupNorm does not affect outputs and backward gradients, i.e., $\mathrm { G r o u p N o r m } ( \alpha { * } \mathrm { h e a d } _ { i } ) = \mathrm { G r o u p N o r m } ( \mathrm { h e a d } _ { i } )$ . We implement three normalization factors in Equation (5). First, we normalize $Q K ^ { \mathsf { T } }$ as $Q K ^ { \tau } / \sqrt { d }$ . Second, we replace $D$ with $\tilde { D } _ { n m } = { \cal D } _ { n m } \big / \sqrt { \textstyle \sum _ { i = 1 } ^ { n } D _ { n i } }$ . Third, let $R$ denote the retention scores $R = Q K ^ { \tau } \odot D$ , we normalize it as $\tilde { R } _ { n m } = { R _ { n m } } \Big / { \operatorname* { m a x } } ( | \sum _ { i = 1 } ^ { n } R _ { n i } | , 1 )$ . Then the retention output becomes Retention $\mathbf { \boldsymbol { \mathbf { \rho } } } _ { \mathbf { \boldsymbol { \mathbf { \lambda } } } } ( \boldsymbol { X } ) = \tilde { \boldsymbol { R } } \boldsymbol { V }$ . The above tricks do not affect the final results while stabilizing the numerical flow of both forward and backward passes, because of the scale-invariant property.
98
+
99
+ # 2.3 OVERALL ARCHITECTURE OF RETENTION NETWORKS
100
+
101
+ For an $L$ -layer retention network, we stack multi-scale retention (MSR) and feed-forward network (FFN) to build the model. Formally, the input sequence $\{ x _ { i } \} _ { i = 1 } ^ { | x | }$ is transformed to vectors by a word embedding layer. We use the packed embeddings $X ^ { 0 } = [ \pmb { x } _ { 1 } , \cdot \cdot \cdot , \pmb { x } _ { | x | } ] \in \mathbb { R } ^ { | x | \times d _ { \mathrm { m o d e l } } }$ as the input and compute the model output $X ^ { L }$ :
102
+
103
+ $$
104
+ \begin{array} { r } { Y ^ { l } = \mathrm { M S R } ( \mathrm { L N } ( X ^ { l } ) ) + X ^ { l } } \\ { X ^ { l + 1 } = \mathrm { F F N } ( \mathrm { L N } ( Y ^ { l } ) ) + Y ^ { l } } \end{array}
105
+ $$
106
+
107
+ where $\mathrm { L N } ( \cdot )$ is LayerNorm (Ba et al., 2016). The FFN part is computed as $\mathrm { F F N } ( X ) \ =$ $\operatorname { g e l u } ( X W _ { 1 } ) { \dot { W } } _ { 2 }$ , where $W _ { 1 } , W _ { 2 }$ are parameter matrices.
108
+
109
+ Training We use the parallel (Equation (5)) and chunkwise recurrent (Equation (7)) representations during the training process. The parallelization within sequences or chunks efficiently utilizes GPUs to accelerate computation. More favorably, chunkwise recurrence is especially useful for long-sequence training, which is efficient in terms of both FLOPs and memory consumption.
110
+
111
+ Inference The recurrent representation (Equation (6)) is employed during the inference, which nicely fits autoregressive decoding. The $O ( 1 )$ complexity reduces memory and inference latency while achieving equivalent results.
112
+
113
+ # 2.4 RELATION TO AND DIFFERENCES FROM PREVIOUS METHODS
114
+
115
+ Table 1 compares RetNet with previous methods from various perspectives. The comparison results echo the “impossible triangle” presented in Figure 1. Moreover, RetNet has linear memory complexity for long sequences due to the chunkwise recurrent representation. We also summarize the comparisons with specific methods as follows.
116
+
117
+ Table 1: Model comparison from various perspectives. The inference cost is measured as one-step inference complexity. RetNet achieves training parallelization, constant inference cost, linear longsequence memory complexity, and good performance. $" * >$ : whether the training implementation is sequentially parallelized, although RWKV uses channel-wise parallelism.
118
+
119
+ <table><tr><td>Architectures</td><td>Paraington</td><td>Inference Cost</td><td>MLmonrySComplexity</td><td>Performance</td></tr><tr><td>Transformer</td><td></td><td>O(N)</td><td>O(N2)</td><td>×x</td></tr><tr><td>Linear Transformer</td><td></td><td>0(1)</td><td>O(N)</td><td></td></tr><tr><td>Recurrent NN</td><td>&gt;&gt;x</td><td>0(1)</td><td>O(N)</td><td></td></tr><tr><td>RWKV</td><td></td><td>0(1)</td><td>O(N)</td><td>&gt;&gt;&gt;</td></tr><tr><td>H3/S4</td><td></td><td>0(1)</td><td>O(N log N)</td><td></td></tr><tr><td>Hyena</td><td>&gt;&gt;&gt;</td><td>O(N)</td><td>O(N log N)</td><td></td></tr><tr><td>RetNet</td><td></td><td>0(1)</td><td>O(N)</td><td></td></tr></table>
120
+
121
+ Transformer The parallel representation of retention shares similar spirits as Transformers (Vaswani et al., 2017). The most related Transformer variant is Lex Transformer (Sun et al., 2023) which implements xPos as position embeddings. As described in Equation (3), the derivation of retention aligns with xPos. In comparison with attention, retention removes softmax and enables recurrent formulation, which significantly benefits inference.
122
+
123
+ S4 Unlike Equation (2), if $Q _ { n }$ and $K _ { n }$ are content-unaware, the formulation can be degenerated to S4 (Gu et al., 2021), where ${ \cal O } = ( Q K ^ { \tau } , Q A K ^ { \tau } , . . , Q A ^ { | x | - 1 } K ^ { \tau } ) * V$ .
124
+
125
+ Linear Attention The variants typically use various kernels $\begin{array} { r l } { \phi ( q _ { i } ) \phi ( k _ { j } ) \Bigl / \sum _ { n = 1 } ^ { | x | } \phi ( q _ { i } ) \phi ( k _ { n } ) } & { { } } \end{array}$ to replace the softmax function. However, linear attention struggles to effectively encode position information, rendering the models less performant. Besides, we reexamine sequence modeling from scratch, rather than aiming at approximating softmax.
126
+
127
+ AFT/RWKV Attention Free Transformer (AFT) simplifies dot-product attention to element-wise operations and moves softmax to key vectors. RWKV replaces AFT’s position embeddings with exponential decay and runs the models recurrently for training and inference. In comparison, retention preserves high-dimensional states to encode sequence information, which contributes to expressive ability and better performance.
128
+
129
+ xPos/RoPE Compared with relative position embedding methods proposed for Transformers, Equation (3) presents a similar formulation as xPos (Sun et al., 2023) and RoPE (Su et al., 2021).
130
+
131
+ Sub-LayerNorm As shown in Equation (8), the retention layer uses Sub-LayerNorm (Wang et al., 2022b) to normalize outputs. Because the multi-scale modeling leads to different variances for the heads, we replace the original LayerNorm with GroupNorm.
132
+
133
+ # 3 EXPERIMENTS
134
+
135
+ We conduct experiments on language modeling to evaluate RetNet. We evaluate the proposed architecture with language modeling performance and zero-/few-shot learning on downstream tasks. Moreover, for training and inference, we compare speed, memory consumption, and latency.
136
+
137
+ # 3.1 SETUP
138
+
139
+ Parameter Allocation We re-allocate the parameters in MSR and FFN for fair comparisons. Let $d$ denote $d _ { \mathrm { m o d e l } }$ for simplicity here. In Transformers, there are about $4 d ^ { 2 }$ parameters in self-attention where $W _ { Q } , W _ { K } , W _ { V } , W _ { O } \in \mathbb { R } ^ { d \times d }$ , and $8 d ^ { 2 }$ parameters in FFN where the intermediate dimension is $4 d$ . In comparison, RetNet has $8 d ^ { 2 }$ parameters in retention, where $W _ { Q } , W _ { K } \in \mathbb { R } ^ { d \times d } , W _ { G } , W _ { V } \in$ $\mathbb { R } ^ { d \times 2 d } , W _ { O } \in \mathbb { R } ^ { 2 d \times d }$ . Notice that the head dimension of $V$ is twice $Q , K$ . The widened dimension is projected back to $d$ by $W _ { O }$ . In order to keep the parameter number the same as Transformer, the FFN intermediate dimension in RetNet is $2 d$ . Meanwhile, we set the head dimension to 256, i.e., 256 for queries and keys, and 512 for values. For fair comparison, we keep $\gamma$ identical among different model sizes, where $\bar { \gamma = 1 } - e ^ { \mathrm { l i n s p a c e } ( \log 1 / 3 2 , \log 1 / 5 1 2 , h ) } \in \bar { \mathbb { R } } ^ { h }$ instead of the default value in Equation (8).
140
+
141
+ ![](images/aa7a7a8cfb2ace74a97d32993bf65d25e32240eb13cb5c30d3e0f9f07becccc7.jpg)
142
+ Figure 3: Perplexity decreases along with scaling up the model size. We empirically observe that RetNet tends to outperform Transformer when the model size is larger than 2B.
143
+
144
+ <table><tr><td></td><td>HS</td><td>BoolQ</td><td>COPA</td><td>PIQA</td><td>Winograd</td><td>Winogrande</td><td>sC</td><td>Avg</td></tr><tr><td>Zero-Shot</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Transformer</td><td>55.9</td><td>62.0</td><td>69.0</td><td>74.6</td><td>69.5</td><td>56.5</td><td>75.0</td><td>66.07</td></tr><tr><td>RetNet</td><td>60.7</td><td>62.2</td><td>77.0</td><td>75.4</td><td>77.2</td><td>58.1</td><td>76.0</td><td>69.51</td></tr><tr><td>4-Shot</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Transformer</td><td>55.8</td><td>58.7</td><td>71.0</td><td>75.0</td><td>71.9</td><td>57.3</td><td>75.4</td><td>66.44</td></tr><tr><td>RetNet</td><td>60.5</td><td>60.1</td><td>78.0</td><td>76.0</td><td>77.9</td><td>59.9</td><td>75.9</td><td>69.76</td></tr></table>
145
+
146
+ Table 2: Zero-shot and few-shot learning with Transformer and RetNet. The model size is 6.7B.
147
+
148
+ Language Model Training We train language models with various sizes (i.e., 1.3B, 2.7B, and 6.7B) from scratch. The hyper-parameters are attached in Appendix A. The training corpus is a curated compilation of The Pile (Gao et al., 2020), C4 (Dodge et al., 2021), and The Stack (Kocetkov et al., 2022). We append the <bos> token to indicate the start of a sequence1. The training batch size is 4M tokens with 2048 maximal length. We train the models with 100B tokens, i.e., $2 5 \mathrm { k }$ steps. We use the AdamW (Loshchilov & Hutter, 2019) optimizer with $\beta _ { 1 } = 0 . 9 , \beta _ { 2 } = 0 . 9 8$ , and weight decay is set to 0.05. The number of warmup steps is 375 with linear learning rate decay. The parameters are initialized following DeepNet (Wang et al., 2022a) to guarantee training stability. The implementation is based on TorchScale (Ma et al., 2022). We train the models with 512 AMD MI200 GPUs.
149
+
150
+ # 3.2 COMPARISONS WITH TRANSFORMER
151
+
152
+ Language Modeling As shown in Figure 3, we report perplexity on the validation set for the language models based on Transformer and RetNet. We present the scaling curves with three model sizes, i.e., 1.3B, 2.7B, and 6.7B. RetNet achieves comparable results with Transformers. More importantly, the results indicate that RetNet is favorable regarding size scaling. Besides performance, the RetNet training is quite stable in our experiments. Experimental results show that RetNet is a strong competitor to Transformer for large language models. Empirically, we find that RetNet starts to outperform Transformer when the model size is larger than 2B. We also summarize the language modeling results with different context lengths in Appendix B.
153
+
154
+ Zero-Shot and Few-Shot Evaluation on Downstream Tasks We also compare the language models on a wide range of downstream tasks. We evaluate zero-shot and 4-shot learning with the 6.7B models. As shown in Table 2, the datasets include HellaSwag (HS; Zellers et al. 2019), BoolQ (Clark et al., 2019), COPA (Wang et al., 2019), PIQA (Bisk et al., 2020), Winograd, Winogrande (Levesque et al., 2012), and StoryCloze (SC; Mostafazadeh et al. 2017). The accuracy numbers are consistent with language modeling perplexity presented in Figure 3. RetNet achieves comparable performance with Transformer on zero-shot and in-context learning settings.
155
+
156
+ Table 3: Training cost of Transformer (Trm), Transformer with FlashAttention $\mathrm { T r m } +$ FlashAttn), and RetNet. We report memory consumption and training throughput (word per second; wps).
157
+
158
+ <table><tr><td rowspan="2">Model Size</td><td colspan="3"></td><td colspan="3">Throm+lashAtm) RetNet</td></tr><tr><td>Trm</td><td>TrmmFry AtRetNet</td><td></td><td>Trm</td><td></td><td></td></tr><tr><td>1.3B</td><td>74.8</td><td>38.8</td><td>34.5</td><td>10832.4</td><td>63965.2</td><td>73344.8</td></tr><tr><td>2.7B</td><td>69.6</td><td>42.1</td><td>42.0</td><td>5186.0</td><td>34990.2</td><td>38921.2</td></tr><tr><td>6.7B</td><td>69.0</td><td>51.4</td><td>48.0</td><td>2754.4</td><td>16230.1</td><td>17458.6</td></tr><tr><td>13B</td><td>61.4</td><td>46.3</td><td>45.9</td><td>1208.9</td><td>7945.1</td><td>8642.2</td></tr></table>
159
+
160
+ # 3.3 TRAINING COST
161
+
162
+ As shown in Table 3, we compare the training speed and memory consumption of Transformer and RetNet, where the training sequence length is 8192. We also compare with FlashAttention (Dao et al., 2022a), which improves speed and reduces GPU memory IO by recomputation and kernel fusion. In comparison, we implement RetNet using vanilla PyTorch code, and leave kernel fusion or FlashAttention-like acceleration for future work. We use chunkwise recurrent representation of retention as described in Equation (7). The chunk size is set to 512. We evaluate the results with eight Nvidia A100-80GB GPUs, because FlashAttention is highly optimized for A100. Tensor parallelism is enabled for 6.7B and 13B models.
163
+
164
+ Experimental results show that RetNet is more memory-efficient and has higher throughput than Transformers during training. Even compared with FlashAttention, RetNet is still competitive in terms of speed and memory cost. Moreover, without relying on specific kernels, it is easy to train RetNet on other platforms efficiently. For example, we train the RetNet models on an AMD MI200 cluster with decent throughput. It is notable that RetNet has the potential to further reduce cost via advanced implementation, such as kernel fusion.
165
+
166
+ # 3.4 INFERENCE COST
167
+
168
+ As shown in Figure 4, we compare memory cost, throughput, and latency of Transformer and RetNet during inference. Transformers reuse KV caches of previously decoded tokens. RetNet uses the recurrent representation as described in Equation (6). We evaluate the 6.7B model on the A100-80GB GPU. Figure 4 shows that RetNet outperforms Transformer in terms of inference cost.
169
+
170
+ Memory As shown in Figure 4a, the memory cost of Transformer increases linearly due to KV caches. In contrast, the memory consumption of RetNet remains consistent even for long sequences, requiring much less GPU memory to host RetNet. The additional memory consumption of RetNet is almost negligible (i.e., about $3 \%$ ) while the model weights occupy $9 7 \%$ .
171
+
172
+ Throughput As presented in Figure 4b, the throughput of Transformer drops along with the decoding length increases. In comparison, RetNet has higher and length-invariant throughput during decoding, by utilizing the recurrent representation of retention.
173
+
174
+ Latency Latency is an important metric in deployment, which greatly affects user experience. We report decoding latency in Figure 4c. Experimental results show that increasing batch size renders Transformer’s latency larger. Moreover, the latency of Transformers grows faster with longer input. In order to make latency acceptable, we have to restrict the batch size, which harms the overall inference throughput of Transformers. By contrast, RetNet’s decoding latency outperforms Transformers and keeps almost the same across different batch sizes and input lengths.
175
+
176
+ ![](images/d62ff85842603d69bbb88c6b503ad61bbf22a5bc48b867894d63f7d87068c4b1.jpg)
177
+ (c) Inference latency with different batch sizes.
178
+ Figure 4: Inference cost of Transformer and RetNet with a model size of 6.7B. RetNet outperforms Transformers in terms of memory consumption, throughput, and latency.
179
+
180
+ <table><tr><td>Method</td><td>In-Domain</td><td>PG22</td><td>QMSum</td><td>GovReport</td><td>SummScreen</td></tr><tr><td>RWKV</td><td>30.92</td><td>51.41</td><td>28.17</td><td>19.80</td><td>25.78</td></tr><tr><td>H3</td><td>29.97</td><td>49.17</td><td>24.29</td><td>19.19</td><td>25.11</td></tr><tr><td>Hyena</td><td>32.08</td><td>52.75</td><td>28.18</td><td>20.55</td><td>26.51</td></tr><tr><td>Linear Transformer</td><td>40.24</td><td>63.86</td><td>28.45</td><td>25.33</td><td>32.02</td></tr><tr><td>RetNet</td><td>26.05</td><td>45.27</td><td>21.33</td><td>16.52</td><td>22.48</td></tr></table>
181
+
182
+ Table 4: Perplexity results on language modeling. RetNet outperforms other architectures on both the in-domain evaluation set and various out-of-domain corpora.
183
+
184
+ # 3.5 COMPARISON WITH TRANSFORMER VARIANTS
185
+
186
+ Apart from Transformer, we compare RetNet with various efficient Transformer variants, including Linear Transformer (Katharopoulos et al., 2020), RWKV (Peng et al., 2023), H3 (Dao et al., 2022b), and Hyena (Poli et al., 2023). All models have 200M parameters with 16 layers and a hidden dimension of 1024. For H3, we set the head dimension as 8. For RWKV, we use the TimeMix module to substitute self-attention layers while keeping FFN layers consistent with other models for fair comparisons. We train the models with 10k steps with a batch size of 0.5M tokens. Most hyperparameters and training corpora are kept the same as in Section 3.1.
187
+
188
+ Table 4 reports the perplexity numbers on the in-domain validation set and other out-of-domain corpora, e.g., Project Gutenberg 2019-2022 (PG22; Sun et al. 2023), QMSum (Zhong et al., 2021), GovReport (Huang et al., 2021), SummScreen (Chen et al., 2021; Shaham et al., 2022). Overall, RetNet outperforms previous methods across different datasets. RetNet not only achieves better evaluation results on the in-domain corpus but also obtains lower perplexity on several out-of-domain datasets. The favorable performance makes RetNet a strong successor to Transformer, besides the benefits of significant cost reduction (Sections 3.3 and 3.4).
189
+
190
+ Table 5: Ablation results on in-domain and out-of-domain corpora.
191
+
192
+ <table><tr><td>Method</td><td>In-Domain</td><td>PG22</td><td>QMSum</td><td>GovReport</td><td> SummScreen</td></tr><tr><td>RetNet</td><td>26.05</td><td>45.27</td><td>21.33</td><td>16.52</td><td>22.48</td></tr><tr><td>- swish gate</td><td>27.84</td><td>49.44</td><td>22.52</td><td>17.45</td><td>23.72</td></tr><tr><td>- GroupNorm</td><td>27.54</td><td>46.95</td><td>22.61</td><td>17.59</td><td>23.73</td></tr><tr><td>- γ decay</td><td>27.86</td><td>47.85</td><td>21.99</td><td>17.49</td><td>23.70</td></tr><tr><td>- multi-scale decay</td><td>27.02</td><td>47.18</td><td>22.08</td><td>17.17</td><td>23.38</td></tr><tr><td>Reduce head dimension</td><td>27.68</td><td>47.72</td><td>23.09</td><td>17.46</td><td>23.41</td></tr></table>
193
+
194
+ In addition, we discuss the training and inference efficiency of the compared methods. Let $d$ denote the hidden dimension, and $n$ the sequence length. For training, RWKV’s token-mixing complexity is $O ( d n )$ while Hyena’s is $O ( d n \log n )$ with Fast Fourier Transform acceleration. The above two methods reduce training FLOPS via employing element-wise operators to trade-off modeling capacity. In comparison with retention, the chunk-wise recurrent representation is $O ( d n ( b + h ) )$ , where $b$ is the chunk size, $h$ is the head dimension, and we usually set $b = 5 1 2$ , $h = 2 5 6$ . For either large model size (i.e., larger $d$ ) or sequence length, the additional $b + h$ has negligible effects. So the RetNet training is quite efficient without sacrificing the modeling performance. For inference, among the compared efficient architectures, Hyena has the same complexity (i.e., $O ( n )$ per step) as Transformer while the others can perform $O ( 1 )$ decoding.
195
+
196
+ # 3.6 ABLATION STUDIES
197
+
198
+ We ablate various design choices of RetNet and report the language modeling results in Table 5. The evaluation settings and metrics are the same as in Section 3.5.
199
+
200
+ Architecture We ablate the swish gate and GroupNorm as described in Equation (8). Table 5 shows that the above two components improve performance. First, the gating module is essential for enhancing non-linearity and improving model capability. Notice that we use the same parameter allocation as Transformers after removing the gate. Second, group normalization in retention balances the variances of multi-head outputs, which improves training stability and language modeling results.
201
+
202
+ Multi-Scale Decay Equation (8) shows that we use different $\gamma$ as the decay rates for the retention heads. In the ablation studies, we examine removing $\gamma$ decay (i.e., $^ { 6 6 } - \gamma$ decay”) and applying the same decay rate across heads (i.e., “− multi-scale decay”). Specifically, ablating $\gamma$ decay is equivalent to $\gamma = 1$ . In the second setting, we set $\gamma = 1 2 7 / 1 2 8$ for all heads. Table 5 indicates that both the decay mechanism and using multiple decay rates can improve the language modeling performance.
203
+
204
+ Head Dimension As indicated by the recurrent perspective of Equation (1), the head dimension implies the memory capacity of hidden states. In ablation, we reduce the default head dimension from 256 to 64, i.e., 64 for queries and keys, and 128 for values. We keep the hidden dimension $d _ { \mathrm { m o d e l } }$ the same. Table 5 shows that the larger head dimension achieves better performance.
205
+
206
+ # 4 CONCLUSION
207
+
208
+ In this work, we propose retentive networks (RetNet) for sequence modeling, which enables various representations, i.e., parallel, recurrent, and chunkwise recurrent. RetNet achieves significantly better inference efficiency (in terms of memory, speed, and latency), favorable training parallelization, and competitive performance compared with Transformers. The above advantages make RetNet an ideal successor to Transformers for large language models, especially considering the deployment benefits brought by the $O ( 1 )$ inference complexity. In the future, we would like to scale up RetNet in terms of model size and training steps. In addition, we are interested in deploying RetNet models on various edge devices, such as mobile phones.
209
+
210
+ # REFERENCES
211
+
212
+ Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón, and Sumit Sanghai. GQA: Training generalized multi-query Transformer models from multi-head checkpoints. arXiv preprint arXiv:2305.13245, 2023.
213
+ Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016.
214
+ Yonatan Bisk, Rowan Zellers, Ronan Le Bras, Jianfeng Gao, and Yejin Choi. Piqa: Reasoning about physical commonsense in natural language. In Thirty-Fourth AAAI Conference on Artificial Intelligence, 2020.
215
+ Mingda Chen, Zewei Chu, Sam Wiseman, and Kevin Gimpel. Summscreen: A dataset for abstractive screenplay summarization. arXiv preprint arXiv:2104.07091, 2021.
216
+ Christopher Clark, Kenton Lee, Ming-Wei Chang, Tom Kwiatkowski, Michael Collins, and Kristina Toutanova. BoolQ: Exploring the surprising difficulty of natural yes/no questions. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics, pp. 2924–2936, 2019. doi: 10.18653/v1/N19-1300.
217
+ Tri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Ré. Flashattention: Fast and memoryefficient exact attention with io-awareness. Advances in Neural Information Processing Systems, 35:16344–16359, 2022a.
218
+ Tri Dao, Daniel Y Fu, Khaled K Saab, Armin W Thomas, Atri Rudra, and Christopher Ré. Hungry hungry hippos: Towards language modeling with state space models. arXiv preprint arXiv:2212.14052, 2022b.
219
+ Jesse Dodge, Ana Marasovic, Gabriel Ilharco, Dirk Groeneveld, Margaret Mitchell, and Matt Gardner. ´ Documenting large webtext corpora: A case study on the colossal clean crawled corpus. In Conference on Empirical Methods in Natural Language Processing, 2021.
220
+ Leo Gao, Stella Biderman, Sid Black, Laurence Golding, 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.
221
+ Albert Gu, Karan Goel, and Christopher Ré. Efficiently modeling long sequences with structured state spaces. arXiv preprint arXiv:2111.00396, 2021.
222
+ Dan Hendrycks and Kevin Gimpel. Gaussian error linear units (GELUs). arXiv: Learning, 2016.
223
+ Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural Computation, 9: 1735–1780, November 1997.
224
+ Luyang Huang, Shuyang Cao, Nikolaus Parulian, Heng Ji, and Lu Wang. Efficient attentions for long document summarization. arXiv preprint arXiv:2104.02112, 2021.
225
+ Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret. Transformers are rnns: Fast autoregressive transformers with linear attention. In International Conference on Machine Learning, pp. 5156–5165. PMLR, 2020.
226
+ Denis Kocetkov, Raymond Li, Loubna Ben Allal, Jia Li, Chenghao Mou, Carlos Muñoz Ferrandis, Yacine Jernite, Margaret Mitchell, Sean Hughes, Thomas Wolf, Dzmitry Bahdanau, Leandro von Werra, and Harm de Vries. The Stack: 3TB of permissively licensed source code. Preprint, 2022.
227
+ Hector Levesque, Ernest Davis, and Leora Morgenstern. The winograd schema challenge. In Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning, 2012.
228
+ Ilya Loshchilov and Frank Hutter. Decoupled weight decay regularization. In International Conference on Learning Representations, 2019.
229
+ Shuming Ma, Hongyu Wang, Shaohan Huang, Wenhui Wang, Zewen Chi, Li Dong, Alon Benhaim, Barun Patra, Vishrav Chaudhary, Xia Song, and Furu Wei. TorchScale: Transformers at scale. CoRR, abs/2211.13184, 2022.
230
+ Nasrin Mostafazadeh, Michael Roth, Annie Louis, Nathanael Chambers, and James Allen. Lsdsem 2017 shared task: The story cloze test. In Proceedings of the 2nd Workshop on Linking Models of Lexical, Sentential and Discourse-level Semantics, pp. 46–51, 2017.
231
+ Antonio Orvieto, Samuel L. Smith, Albert Gu, Anushan Fernando, Caglar Gulcehre, Razvan Pascanu, and Soham De. Resurrecting recurrent neural networks for long sequences. ArXiv, abs/2303.06349, 2023.
232
+ Bo Peng, Eric Alcaide, Quentin G. Anthony, Alon Albalak, Samuel Arcadinho, Huanqi Cao, Xin Cheng, Michael Chung, Matteo Grella, G Kranthikiran, Xuming He, Haowen Hou, et al. RWKV: Reinventing RNNs for the Transformer era. ArXiv, abs/2305.13048, 2023.
233
+ Michael Poli, Stefano Massaroli, Eric Nguyen, Daniel Y Fu, Tri Dao, Stephen Baccus, Yoshua Bengio, Stefano Ermon, and Christopher Ré. Hyena hierarchy: Towards larger convolutional language models. arXiv preprint arXiv:2302.10866, 2023.
234
+ Prajit Ramachandran, Barret Zoph, and Quoc V. Le. Swish: a self-gated activation function. arXiv: Neural and Evolutionary Computing, 2017.
235
+ Uri Shaham, Elad Segal, Maor Ivgi, Avia Efrat, Ori Yoran, Adi Haviv, Ankit Gupta, Wenhan Xiong, Mor Geva, Jonathan Berant, et al. Scrolls: Standardized comparison over long language sequences. arXiv preprint arXiv:2201.03533, 2022.
236
+ Noam M. Shazeer. Fast Transformer decoding: One write-head is all you need. ArXiv, abs/1911.02150, 2019.
237
+ Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. Megatron-LM: Training multi-billion parameter language models using model parallelism. arXiv preprint arXiv:1909.08053, 2019.
238
+ Jianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. arXiv preprint arXiv:2104.09864, 2021.
239
+ Yutao Sun, Li Dong, Barun Patra, Shuming Ma, Shaohan Huang, Alon Benhaim, Vishrav Chaudhary, Xia Song, and Furu Wei. A length-extrapolatable transformer. In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 14590– 14604, Toronto, Canada, July 2023. Association for Computational Linguistics.
240
+ 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. LLaMA: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023a.
241
+ 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, 2023b.
242
+ Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, 4-9 December 2017, Long Beach, CA, USA, pp. 6000–6010, 2017.
243
+ Alex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. SuperGLUE: A stickier benchmark for general-purpose language understanding systems. arXiv preprint arXiv:1905.00537, 2019.
244
+ Hongyu Wang, Shuming Ma, Li Dong, Shaohan Huang, Dongdong Zhang, and Furu Wei. DeepNet:
245
+
246
+ Scaling Transformers to 1,000 layers. ArXiv, abs/2203.00555, 2022a.
247
+
248
+ Hongyu Wang, Shuming Ma, Shaohan Huang, Li Dong, Wenhui Wang, Zhiliang Peng, Yu Wu, Payal Bajaj, Saksham Singhal, Alon Benhaim, et al. Foundation transformers. arXiv preprint arXiv:2210.06423, 2022b.
249
+ Yuxin Wu and Kaiming He. Group normalization. In Proceedings of the European conference on computer vision (ECCV), pp. 3–19, 2018.
250
+ Rowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. Hellaswag: Can a machine really finish your sentence? In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, 2019.
251
+ Ming Zhong, Da Yin, Tao Yu, Ahmad Zaidi, Mutethia Mutuma, Rahul Jha, Ahmed Hassan Awadallah, Asli Celikyilmaz, Yang Liu, Xipeng Qiu, et al. Qmsum: A new benchmark for query-based multidomain meeting summarization. arXiv preprint arXiv:2104.05938, 2021.
252
+
253
+ A HYPERPARAMETERS
254
+ Table 6: Hyperparamters used for the models in Section 3.
255
+
256
+ <table><tr><td>Hyperparameters</td><td>1.3B</td><td>2.7B</td><td>6.7B</td></tr><tr><td>Layers</td><td>24</td><td>32</td><td>32</td></tr><tr><td>Hidden size</td><td>2048</td><td>2560</td><td>4096</td></tr><tr><td>FFN size Heads</td><td>4096 8</td><td>5120 10</td><td>8192 16</td></tr><tr><td>Learning rate LR scheduler Warm-up steps</td><td>6 ×10-4</td><td>3×10-4 Linear decay 375</td><td>3×10-4</td></tr><tr><td>Tokens per batch Adam β</td><td></td><td>4M (0.9, 0.98)</td><td></td></tr><tr><td>Training steps</td><td></td><td>25,000</td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td>Gradient clipping</td><td></td><td>2.0</td><td></td></tr><tr><td>Dropout</td><td></td><td>0.1</td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td>Weight decay</td><td></td><td>0.01</td><td></td></tr></table>
257
+
258
+ # B RESULTS WITH DIFFERENT CONTEXT LENGTHS
259
+
260
+ As shown in Table 7, we report language modeling results with different context lengths. In order to make the numbers comparable, we use 2048 text chunks as evaluation data and only compute perplexity for the last 128 tokens. Experimental results show that RetNet outperforms Transformer across different context lengths. Besides, RetNet can utilize longer context for better results.
261
+
262
+ <table><tr><td>Model</td><td>512</td><td>1024</td><td>2048</td></tr><tr><td>Transformer</td><td>13.55</td><td>12.56</td><td>12.35</td></tr><tr><td>RetNet</td><td>13.09</td><td>12.14</td><td>11.98</td></tr></table>
263
+
264
+ Table 7: Language modeling perplexity of RetNet and Transformer with different context length. The results show that RetNet has a consistent advantage across sequence length.
265
+
266
+ # C INFERENCE COST OF GROUPED-QUERY RETENTION
267
+
268
+ We compare with grouped-query attention (Ainslie et al., 2023) and evaluate the method in the context of RetNet. Grouped-query attention makes a trade-off between performance and efficiency, which has been successfully verified in LLaMA2 34B/70B (Touvron et al., 2023b). The method reduces the overhead of key/value cache during inference. Moreover, the performance of grouped-query attention is better than multi-query attention (Shazeer, 2019), overcoming the quality degradation brought by using one-head key value.
269
+
270
+ As shown in Table 8, we compare the inference cost with grouped-query attention and apply the method for RetNet. For the LLaMA2 70B model, the number of key/value heads is reduced by $8 \times$ , where the query head number is 64 while the key/value head number is 8. For RetNet-70B, the parameter allocation is identical to LLaMA (Touvron et al., 2023a), where the dimension is 8192, and the head number is 32 for RetNet. For RetNet-70B-GQ2, the key-value head number is 16, where grouped-query retention is applied. We run the inference with four A100 GPUs without quantization.
271
+
272
+ When the batch size is 256, LLaMA2 runs out of memory while RetNet without group query still has a high throughput. When equipped with grouped-query retention, RetNet-70B achieves $38 \%$ acceleration and saves $30 \%$ memory.
273
+
274
+ We evaluate LLaMA2 under $2 \mathrm { k }$ and $^ { 8 \mathrm { k } }$ lengths separately. The batch size is decreased to 8 so that LLaMA2 can be run without out of memory. Table 8 shows that the inference cost of Transformers increases with the sequence length. In contrast, RetNet is length-invariant. Moreover, RetNet-70BGQ2 achieves better latency, throughput, and GPU memory than LLaMA2-70B-2k/8k equipped with grouped-query attention. Notice that evaluation metrics are averaged over positions of different sequence lengths for fair comparison, rather than only considering the inference cost of maximum length.
275
+
276
+ Table 8: Inference cost of RetNet and LLaMA2-70B with difference batch size and length. LLaMA2- 70B is equipped with grouped-query attention, reducing key/value heads by $8 \times$ . “-GQ2” means grouped-query retention, which reduces half of key/value heads. $\ddot { \mathbf { \eta } } ^ { 6 6 } - 2 \mathbf { k } ^ { \mathbf { \eta } , \mathbf { \eta } }$ and “-8k” indicate sequence length for LLaMA2, while RetNet is length-invariant. RetNet is capable of large-batch inference and is favourable in terms of latency, throughput, and GPU memory.
277
+
278
+ # D PSEUDO CODE OF RETENTION
279
+
280
+ # def ParallelRetention(
281
+
282
+ q, # bsz $^ *$ num_head $^ *$ len $^ *$ qk_dim k, # bsz $^ *$ num_head $^ *$ len $^ *$ qk_dim v, # bsz $^ *$ num_head $^ *$ len $^ *$ v_dim decay_mask $\#$ num_head $^ *$ len $^ *$ len ):
283
+ retention $=$ q @ k.transpose(−1, −2) retention $=$ retention $^ *$ decay_mask output $=$ retention @ v
284
+ output $=$ group_norm(output)
285
+ return output
286
+
287
+ Figure 5: Pseudocode for the three computation paradigms of retention.
288
+
289
+ <table><tr><td>Model</td><td>Batch Size</td><td>Latency (ms)↓</td><td>Throughput (wps)↑</td><td>Memory (GB)↓</td></tr><tr><td>LLaMA2-70B-2k</td><td>256</td><td></td><td></td><td>0OM</td></tr><tr><td>LLaMA2-70B-8k</td><td>256</td><td></td><td></td><td>0OM</td></tr><tr><td>RetNet-70B</td><td>256</td><td>639.1</td><td>410.19</td><td>72.469</td></tr><tr><td>RetNet-70B-GQ2</td><td>256</td><td>461.8</td><td>567.66</td><td>52.726</td></tr><tr><td>LLaMA2-70B-2k</td><td>8</td><td>184.5</td><td>44.42</td><td>33.374</td></tr><tr><td>LLaMA2-70B-8k</td><td>8</td><td>277.7</td><td>29.50</td><td>37.386</td></tr><tr><td>RetNet-70B-GQ2</td><td>8</td><td>106.2</td><td>77.02</td><td>32.301</td></tr></table>
290
+
291
+ # def RecurrentRetention(
292
+
293
+ q, k, v, # bsz $^ *$ num_head $^ *$ len $^ *$ qkv_dim
294
+ past_kv, # bsz $^ *$ num_head $^ *$ qk_dim $^ *$ v_dim
295
+ decay # num_head $* \ 1 \ * \ 1$
296
+ ):
297
+ current_kv $=$ decay $^ *$ past_kv $^ +$ k.unsqueeze $( - 1 ) ~ * ~ \mathtt { v }$ .unsqueeze(−2)
298
+ output $=$ torch.sum(q.unsqueeze(−1) ∗ current_kv, ${ \dot { \mathsf { d i m } } } = - 2$ )
299
+ output $=$ group_norm(output)
300
+ return output, current_kv
301
+
302
+ # def ChunkwiseRetention(
303
+
304
+ ![](images/248c102384ad8db62124a64abbf33a97ed18e252042627104445726a3db4f83c.jpg)
parse/test/UU9Icwbhin/UU9Icwbhin_content_list.json ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "type": "text",
4
+ "text": "RETENTIVE NETWORK: A SUCCESSOR TO TRANSFORMER FOR LARGE LANGUAGE MODELS ",
5
+ "text_level": 1,
6
+ "page_idx": 0
7
+ },
8
+ {
9
+ "type": "text",
10
+ "text": "Anonymous authors Paper under double-blind review ",
11
+ "page_idx": 0
12
+ },
13
+ {
14
+ "type": "text",
15
+ "text": "ABSTRACT ",
16
+ "text_level": 1,
17
+ "page_idx": 0
18
+ },
19
+ {
20
+ "type": "text",
21
+ "text": "In this work, we propose Retentive Network (RETNET) as a foundation architecture for large language models, simultaneously achieving training parallelism, low-cost inference, and good performance. We theoretically derive the connection between recurrence and attention. Then we propose the retention mechanism for sequence modeling, which supports three computation paradigms, i.e., parallel, recurrent, and chunkwise recurrent. Specifically, the parallel representation allows for training parallelism. The recurrent representation enables low-cost $O ( 1 )$ inference, which improves decoding throughput, latency, and GPU memory without sacrificing performance. The chunkwise recurrent representation facilitates efficient long-sequence modeling with linear complexity, where each chunk is encoded parallelly while recurrently summarizing the chunks. Experimental results on language modeling show that RETNET achieves favorable scaling results, parallel training, low-cost deployment, and efficient inference. The intriguing properties make RETNET a strong successor to Transformer for large language models. ",
22
+ "page_idx": 0
23
+ },
24
+ {
25
+ "type": "text",
26
+ "text": "1 INTRODUCTION ",
27
+ "text_level": 1,
28
+ "page_idx": 0
29
+ },
30
+ {
31
+ "type": "text",
32
+ "text": "Transformer (Vaswani et al., 2017) has become the de facto architecture for large language models, which was initially proposed to overcome the sequential training issue of recurrent models (Hochreiter & Schmidhuber, 1997). However, training parallelism of Transformers is at the cost of inefficient inference, because of the $O ( N )$ complexity per step and memory-bound key-value cache (Shazeer, 2019), which renders Transformers unfriendly to deployment. The growing sequence length increases GPU memory consumption as well as latency and reduces inference speed. Numerous efforts have continued to develop the next-generation architecture, aiming at retaining training parallelism and competitive performance as Transformers while having efficient $O ( 1 )$ inference. It is challenging to achieve the above goals simultaneously, i.e., the so-called “impossible triangle” as shown in Figure 1. ",
33
+ "page_idx": 0
34
+ },
35
+ {
36
+ "type": "image",
37
+ "img_path": "images/0b06bf283b78d4d56e7c361dd512c4d9871fd3cc7e676ab044d9a87052a06add.jpg",
38
+ "image_caption": [
39
+ "Figure 1: RetNet makes the “impossible triangle” possible, which achieves training parallelism, good performance, and low inference cost simultaneously. "
40
+ ],
41
+ "image_footnote": [],
42
+ "page_idx": 0
43
+ },
44
+ {
45
+ "type": "text",
46
+ "text": "There have been three main strands of research. First, linearized attention (Katharopoulos et al., 2020) approximates standard attention scores $\\exp ( \\pmb q \\cdot \\pmb k )$ with kernels $\\phi ( \\pmb q ) \\cdot \\phi ( \\pmb k )$ , so that autoregressive inference can be rewritten in a recurrent form. However, the modeling capability and performance are worse than Transformers, which hinders the method’s popularity. The second strand returns to recurrent models for efficient inference while sacrificing training parallelism. As a remedy, elementwise operators (Peng et al., 2023) are used for acceleration, however, representation capacity and performance are harmed. The third line explores replacing attention with other mechanisms, such as S4 (Gu et al., 2021), and its variants (Dao et al., 2022b; Poli et al., 2023). None of the previous work can break through the impossible triangle, resulting in no clear winner compared with Transformers. ",
47
+ "page_idx": 0
48
+ },
49
+ {
50
+ "type": "text",
51
+ "text": "In this work, we propose retentive networks (RetNet), achieving low-cost inference, efficient longsequence modeling, Transformer-comparable performance, and parallel model training simultaneously. Specifically, we introduce a multi-scale retention mechanism to substitute multi-head attention, which has three computation paradigms, i.e., parallel, recurrent, and chunkwise recurrent representations. First, the parallel representation empowers training parallelism to utilize GPU devices fully. Second, the recurrent representation enables efficient $O ( 1 )$ inference in terms of memory and computation. The deployment cost and latency can be significantly reduced. Moreover, the implementation is greatly simplified without key-value cache tricks. Third, the chunkwise recurrent representation can perform efficient long-sequence modeling. We parallelly encode each local block for computation speed while recurrently encoding the global blocks to save GPU memory. ",
52
+ "page_idx": 0
53
+ },
54
+ {
55
+ "type": "text",
56
+ "text": "",
57
+ "page_idx": 1
58
+ },
59
+ {
60
+ "type": "text",
61
+ "text": "We compare RetNet with Transformer and its variants. Experimental results on language modeling show that RetNet is consistently competitive in terms of both scaling curves and in-context learning. Moreover, the inference cost of RetNet is length-invariant. For a 7B model and 8k sequence length, RetNet decodes $8 . 4 \\times$ faster and saves $70 \\%$ of memory than Transformers with key-value caches. During training, RetNet also achieves $2 5 { - } 5 0 \\%$ memory saving and $7 \\times$ acceleration than standard Transformer and an advantage towards highly-optimized FlashAttention (Dao et al., 2022a). Besides, RetNet’s inference latency is insensitive to batch size, allowing enormous throughput. The intriguing properties make RetNet a strong successor to Transformer for large language models. ",
62
+ "page_idx": 1
63
+ },
64
+ {
65
+ "type": "text",
66
+ "text": "2 RETENTIVE NETWORKS ",
67
+ "text_level": 1,
68
+ "page_idx": 1
69
+ },
70
+ {
71
+ "type": "text",
72
+ "text": "Retentive network (RetNet) is stacked with $L$ identical blocks, which follows a similar layout (i.e., residual connection, and pre-LayerNorm) as in Transformer (Vaswani et al., 2017). Each RetNet block contains two modules: a multi-scale retention (MSR) module, and a feed-forward network (FFN) module. We introduce the MSR module in the following sections. Given an input sequence $x = x _ { 1 } \\cdot \\cdot \\cdot x _ { | x | }$ , RetNet encodes the sequence in an autoregressive way. The input vectors $\\{ \\bar { \\pmb { x } } _ { i } \\} _ { i = 1 } ^ { | x | }$ is first packed into $X ^ { 0 } = [ \\pmb { x } _ { 1 } , \\cdot \\cdot \\cdot , \\pmb { x } _ { | x | } ] \\in \\mathbb { R } ^ { | x | \\times d _ { \\mathrm { m o d e l } } }$ , where $d _ { \\mathrm { m o d e l } }$ is hidden dimension. Then we compute contextualized vector representations $X ^ { l } = \\mathrm { R e t N e t } _ { l } ( X ^ { l - 1 } ) , l \\in [ 1 , L ]$ . ",
73
+ "page_idx": 1
74
+ },
75
+ {
76
+ "type": "text",
77
+ "text": "2.1 RETENTION ",
78
+ "text_level": 1,
79
+ "page_idx": 1
80
+ },
81
+ {
82
+ "type": "text",
83
+ "text": "In this section, we introduce the retention mechanism that has a dual form of recurrence and parallelism. So we can train the models in a parallel way while recurrently conducting inference. ",
84
+ "page_idx": 1
85
+ },
86
+ {
87
+ "type": "text",
88
+ "text": "Given input $X \\in \\mathbb { R } ^ { | x | \\times d _ { \\mathrm { m o d e l } } }$ , we project it to one-dimensional function $v ( n ) = X _ { n } \\cdot w _ { V }$ . Consider a sequence modeling problem that maps $v ( n ) \\mapsto o ( n )$ through states $s _ { n }$ . Let $v _ { n } , o _ { n }$ denote $v ( n ) , o ( n )$ for simplicity. We formulate the mapping in a recurrent manner: ",
89
+ "page_idx": 1
90
+ },
91
+ {
92
+ "type": "equation",
93
+ "img_path": "images/641522a9e9656e442c5cb47a2b28a63ecd0c896b7d09b61a7ba2ff5cd55d2063.jpg",
94
+ "text": "$$\n\\begin{array} { r l r } { { \\pmb { s } _ { n } = { \\cal A } \\pmb { s } _ { n - 1 } + { \\cal K } _ { n } ^ { \\top } \\boldsymbol { v } _ { n } , } } & { \\ } & { \\boldsymbol { A } \\in \\mathbb { R } ^ { d \\times d } , { \\cal K } _ { n } \\in \\mathbb { R } ^ { 1 \\times d } } \\\\ & { o _ { n } = { \\cal Q } _ { n } \\pmb { s } _ { n } = \\sum _ { m = 1 } ^ { n } { \\cal Q } _ { n } { \\cal A } ^ { n - m } { \\cal K } _ { m } ^ { \\top } \\boldsymbol { v } _ { m } , } & { \\ } & { \\ { \\cal Q } _ { n } \\in \\mathbb { R } ^ { 1 \\times d } } \\end{array}\n$$",
95
+ "text_format": "latex",
96
+ "page_idx": 1
97
+ },
98
+ {
99
+ "type": "text",
100
+ "text": "where we map $v _ { n }$ to the state vector $s _ { n }$ , and then implement a linear transform to encode sequence information recurrently. Next, we make the projection $Q _ { n } , K _ { n }$ content-aware: ",
101
+ "page_idx": 1
102
+ },
103
+ {
104
+ "type": "equation",
105
+ "img_path": "images/5705f2b8a0dfe026e74d5898d40ae7b3a7d3ea52578134414beea39cc478f7d3.jpg",
106
+ "text": "$$\nQ = X W _ { Q } , \\quad K = X W _ { K }\n$$",
107
+ "text_format": "latex",
108
+ "page_idx": 1
109
+ },
110
+ {
111
+ "type": "text",
112
+ "text": "where $W _ { Q } , W _ { K } \\in \\mathbb { R } ^ { d \\times d }$ are learnable matrices. ",
113
+ "page_idx": 1
114
+ },
115
+ {
116
+ "type": "text",
117
+ "text": "We diagonalize the matrix $A ~ = ~ \\Lambda ( \\gamma e ^ { i \\theta } ) \\Lambda ^ { - 1 }$ , where $\\gamma , \\theta \\ \\in \\ \\mathbb { R } ^ { d }$ . Then we obtain $A ^ { n - m } =$ $\\Lambda ( \\gamma e ^ { i \\theta } ) ^ { \\smile - m } \\Lambda ^ { - 1 }$ . By absorbing $\\Lambda$ into $W _ { Q }$ and $W _ { K }$ , we can rewrite Equation (1) as: ",
118
+ "page_idx": 1
119
+ },
120
+ {
121
+ "type": "equation",
122
+ "img_path": "images/e1104f37e686b24c2028f986adf3318a2b73e7a22081218f8f8f4c9264f049fd.jpg",
123
+ "text": "$$\n\\begin{array} { c } { { \\displaystyle o _ { n } = \\sum _ { m = 1 } ^ { n } Q _ { n } ( \\gamma e ^ { i \\theta } ) ^ { n - m } K _ { m } ^ { \\intercal } v _ { m } } } \\\\ { { \\displaystyle \\ } } \\\\ { { \\displaystyle = \\sum _ { m = 1 } ^ { n } ( Q _ { n } ( \\gamma e ^ { i \\theta } ) ^ { n } ) ( K _ { m } ( \\gamma e ^ { i \\theta } ) ^ { - m } ) ^ { \\intercal } v _ { m } } } \\end{array}\n$$",
124
+ "text_format": "latex",
125
+ "page_idx": 1
126
+ },
127
+ {
128
+ "type": "text",
129
+ "text": "where $Q _ { n } ( \\gamma e ^ { i \\theta } ) ^ { n } , K _ { m } ( \\gamma e ^ { i \\theta } ) ^ { - m }$ is known as xPos (Sun et al., 2023), i.e., a relative position embedding proposed for Transformer. We further simplify $\\gamma$ as a scalar, Equation (3) becomes: ",
130
+ "page_idx": 1
131
+ },
132
+ {
133
+ "type": "equation",
134
+ "img_path": "images/eae1007252a612397477e2d89ac9ebdd7bd59814c1a89ab1aa1f1e4d314290f0.jpg",
135
+ "text": "$$\no _ { n } = \\sum _ { m = 1 } ^ { n } \\gamma ^ { n - m } ( Q _ { n } e ^ { i n \\theta } ) ( K _ { m } e ^ { i m \\theta } ) ^ { \\dagger } v _ { m }\n$$",
136
+ "text_format": "latex",
137
+ "page_idx": 1
138
+ },
139
+ {
140
+ "type": "image",
141
+ "img_path": "images/9457e55c2304d3514442227b8bfe9a67528dbd5917edf3647beb3b6e49273926.jpg",
142
+ "image_caption": [
143
+ "Figure 2: Dual form of RetNet. “GN” is short for GroupNorm. "
144
+ ],
145
+ "image_footnote": [],
146
+ "page_idx": 2
147
+ },
148
+ {
149
+ "type": "text",
150
+ "text": "where † is the conjugate transpose. The formulation is easily parallelizable within training instances. ",
151
+ "page_idx": 2
152
+ },
153
+ {
154
+ "type": "text",
155
+ "text": "In summary, we start with recurrent modeling as shown in Equation (1), and then derive its parallel formulation in Equation (4). We consider the original mapping $v ( n ) \\mapsto o ( n )$ as vectors and obtain the retention mechanism as follows. ",
156
+ "page_idx": 2
157
+ },
158
+ {
159
+ "type": "text",
160
+ "text": "The Parallel Representation of Retention As shown in Figure 2a, the retention layer is defined as: ",
161
+ "page_idx": 2
162
+ },
163
+ {
164
+ "type": "equation",
165
+ "img_path": "images/3de1625f651f2325df3d125ad029018245837bc1e755fcbaa279350264aee100.jpg",
166
+ "text": "$$\n\\begin{array} { c c } { { Q = ( X W _ { Q } ) \\odot \\Theta , } } & { { K = ( X W _ { K } ) \\odot \\overline { { { \\Theta } } } , \\quad V = X W _ { V } } } \\\\ { { } } & { { } } \\\\ { { \\Theta _ { n } = e ^ { i n \\theta } , \\quad D _ { n m } = \\left\\{ \\begin{array} { l l } { { \\gamma ^ { n - m } , } } & { { n \\geq m } } \\\\ { { 0 , } } & { { n < m } } \\end{array} \\right. } } \\\\ { { } } & { { \\mathrm { R e t e n t i o n } ( X ) = ( Q K ^ { \\top } \\odot D ) V } } \\end{array}\n$$",
167
+ "text_format": "latex",
168
+ "page_idx": 2
169
+ },
170
+ {
171
+ "type": "text",
172
+ "text": "where $D \\in \\mathbb { R } ^ { | x | \\times | x | }$ combines causal masking and exponential decay along relative distance as one matrix, and $\\overline { { \\Theta } }$ is the complex conjugate of $\\Theta$ . In practice, we map $Q , K \\in \\mathbb { R } ^ { d } \\to \\mathbb { C } ^ { d / 2 }$ , add the complex position embedding $\\Theta$ , then map them back to $\\mathbb { R } ^ { d }$ , following the implementation trick as in LLaMA (Touvron et al., 2023a; Su et al., 2021). Similar to self-attention, the parallel representation enables us to train the models with GPUs efficiently. ",
173
+ "page_idx": 2
174
+ },
175
+ {
176
+ "type": "text",
177
+ "text": "The Recurrent Representation of Retention As shown in Figure 2b, the proposed mechanism can also be written as recurrent neural networks (RNNs), which is favorable for inference. For the $n$ -th timestep, we recurrently obtain the output as: ",
178
+ "page_idx": 2
179
+ },
180
+ {
181
+ "type": "equation",
182
+ "img_path": "images/42c350bd8570170665134c07d31e833c9ad3253396e3dcbea91eff77dff43110.jpg",
183
+ "text": "$$\n\\begin{array} { r l } & { S _ { n } = \\gamma S _ { n - 1 } + K _ { n } ^ { \\intercal } V _ { n } } \\\\ & { \\mathrm { R e t e n t i o n } ( X _ { n } ) = Q _ { n } S _ { n } , \\quad n = 1 , \\cdots , | x | } \\end{array}\n$$",
184
+ "text_format": "latex",
185
+ "page_idx": 2
186
+ },
187
+ {
188
+ "type": "text",
189
+ "text": "where $Q , K , V , \\gamma$ are the same as in Equation (5). ",
190
+ "page_idx": 2
191
+ },
192
+ {
193
+ "type": "text",
194
+ "text": "The Chunkwise Recurrent Representation of Retention A hybrid form of parallel representation and recurrent representation is available to accelerate training, especially for long sequences. We divide the input sequences into chunks. Within each chunk, we follow the parallel representation (Equation (5)) to conduct computation. In contrast, cross-chunk information is passed following the recurrent representation (Equation (6)). Specifically, let $B$ denote the chunk length. We compute the retention output of the $i$ -th chunk via: ",
195
+ "page_idx": 2
196
+ },
197
+ {
198
+ "type": "equation",
199
+ "img_path": "images/8fb3c30137ba8a8590e7fad917f93984a56ab68fd0950c34777f3808bd7f69e4.jpg",
200
+ "text": "$$\n\\begin{array} { r l } & { Q _ { [ i ] } = Q _ { B i : B ( i + 1 ) } , \\quad K _ { [ i ] } = K _ { B i : B ( i + 1 ) } , \\quad V _ { [ i ] } = V _ { B i : B ( i + 1 ) } } \\\\ & { \\qquad R _ { i } = K _ { [ i ] } ^ { \\top } ( V _ { [ i ] } \\odot \\zeta ) + \\gamma ^ { B } R _ { i - 1 } , \\quad \\zeta _ { i j } = \\gamma ^ { B - i - 1 } } \\\\ & { \\mathrm { R e t e n t i o n } ( X _ { [ i ] } ) = \\underbrace { ( Q _ { [ i ] } K _ { [ i ] } ^ { \\top } \\odot D ) V _ { [ i ] } } _ { \\mathrm { I n n e r - C h u n k } } + \\underbrace { ( Q _ { [ i ] } R _ { i - 1 } ) \\odot \\xi } _ { \\mathrm { C r o s s - C h u n k } } , \\quad \\xi _ { i j } = \\gamma ^ { i + 1 } } \\end{array}\n$$",
201
+ "text_format": "latex",
202
+ "page_idx": 2
203
+ },
204
+ {
205
+ "type": "text",
206
+ "text": "where $[ i ]$ indicates the $i$ -th chunk, i.e., $x _ { [ i ] } = [ x _ { ( i - 1 ) B + 1 } , \\cdot \\cdot \\cdot , x _ { i B } ]$ . ",
207
+ "page_idx": 2
208
+ },
209
+ {
210
+ "type": "text",
211
+ "text": "2.2 GATED MULTI-SCALE RETENTION ",
212
+ "text_level": 1,
213
+ "page_idx": 3
214
+ },
215
+ {
216
+ "type": "text",
217
+ "text": "We use $h = \\left. d _ { \\mathrm { m o d e l } } \\right/ d$ retention heads in each layer, where $d$ is the head dimension. The heads use different parameter matrices $W _ { Q } , W _ { K } , W _ { V } \\in \\bar { \\mathbb { R } } ^ { d \\times d }$ . Moreover, multi-scale retention (MSR) assigns different $\\gamma$ for each head. For simplicity, we set $\\gamma$ identical among different layers and keep them fixed. In addition, we add a swish gate (Hendrycks & Gimpel, 2016; Ramachandran et al., 2017) to increase the non-linearity of retention layers. Formally, given input $X$ , we define the layer as: ",
218
+ "page_idx": 3
219
+ },
220
+ {
221
+ "type": "equation",
222
+ "img_path": "images/d1d68cc3d3b2f1218fac6637bca6d5da71d78efae3e1635f88886cc8cbe95505.jpg",
223
+ "text": "$$\n{ \\begin{array} { r l } & { \\qquad \\gamma = 1 - 2 ^ { - 5 - \\operatorname { a r a n g e } ( 0 , h ) } \\in \\mathbb { R } ^ { h } } \\\\ & { { \\mathrm { h e a d } } _ { i } = { \\mathrm { R e t e n t i o n } } ( X , \\gamma _ { i } ) } \\\\ & { \\qquad Y = \\operatorname { G r o u p N o r m } _ { h } ( \\operatorname { C o n c a t } ( { \\mathrm { h e a d } } _ { 1 } , \\cdots , { \\mathrm { h e a d } } _ { h } ) ) } \\\\ & { { \\mathrm { M S R } } ( X ) = ( { \\mathrm { s w i s h } } ( X W _ { G } ) \\odot Y ) W _ { O } } \\end{array} }\n$$",
224
+ "text_format": "latex",
225
+ "page_idx": 3
226
+ },
227
+ {
228
+ "type": "text",
229
+ "text": "where $W _ { G } , W _ { O } \\in \\mathbb { R } ^ { d _ { \\mathrm { m o d e l } } \\times d _ { \\mathrm { m o d e l } } }$ are learnable parameters, and GroupNorm (Wu & He, 2018) normalizes the output of each head, following SubLN proposed in (Shoeybi et al., 2019). Notice that the heads use multiple $\\gamma$ scales, which results in different variance statistics. So we normalize the head outputs separately. The pseudocode of retention is summarized in Appendix D. ",
230
+ "page_idx": 3
231
+ },
232
+ {
233
+ "type": "text",
234
+ "text": "Retention Score Normalization We utilize the scale-invariant nature of GroupNorm to improve numerical precision of retention layers. Specifically, multiplying a scalar value within GroupNorm does not affect outputs and backward gradients, i.e., $\\mathrm { G r o u p N o r m } ( \\alpha { * } \\mathrm { h e a d } _ { i } ) = \\mathrm { G r o u p N o r m } ( \\mathrm { h e a d } _ { i } )$ . We implement three normalization factors in Equation (5). First, we normalize $Q K ^ { \\mathsf { T } }$ as $Q K ^ { \\tau } / \\sqrt { d }$ . Second, we replace $D$ with $\\tilde { D } _ { n m } = { \\cal D } _ { n m } \\big / \\sqrt { \\textstyle \\sum _ { i = 1 } ^ { n } D _ { n i } }$ . Third, let $R$ denote the retention scores $R = Q K ^ { \\tau } \\odot D$ , we normalize it as $\\tilde { R } _ { n m } = { R _ { n m } } \\Big / { \\operatorname* { m a x } } ( | \\sum _ { i = 1 } ^ { n } R _ { n i } | , 1 )$ . Then the retention output becomes Retention $\\mathbf { \\boldsymbol { \\mathbf { \\rho } } } _ { \\mathbf { \\boldsymbol { \\mathbf { \\lambda } } } } ( \\boldsymbol { X } ) = \\tilde { \\boldsymbol { R } } \\boldsymbol { V }$ . The above tricks do not affect the final results while stabilizing the numerical flow of both forward and backward passes, because of the scale-invariant property. ",
235
+ "page_idx": 3
236
+ },
237
+ {
238
+ "type": "text",
239
+ "text": "2.3 OVERALL ARCHITECTURE OF RETENTION NETWORKS ",
240
+ "text_level": 1,
241
+ "page_idx": 3
242
+ },
243
+ {
244
+ "type": "text",
245
+ "text": "For an $L$ -layer retention network, we stack multi-scale retention (MSR) and feed-forward network (FFN) to build the model. Formally, the input sequence $\\{ x _ { i } \\} _ { i = 1 } ^ { | x | }$ is transformed to vectors by a word embedding layer. We use the packed embeddings $X ^ { 0 } = [ \\pmb { x } _ { 1 } , \\cdot \\cdot \\cdot , \\pmb { x } _ { | x | } ] \\in \\mathbb { R } ^ { | x | \\times d _ { \\mathrm { m o d e l } } }$ as the input and compute the model output $X ^ { L }$ : ",
246
+ "page_idx": 3
247
+ },
248
+ {
249
+ "type": "equation",
250
+ "img_path": "images/f196d073a2660747c9c66bfd11c45b4b776c8a8a4a437ae340c68ff39da1e469.jpg",
251
+ "text": "$$\n\\begin{array} { r } { Y ^ { l } = \\mathrm { M S R } ( \\mathrm { L N } ( X ^ { l } ) ) + X ^ { l } } \\\\ { X ^ { l + 1 } = \\mathrm { F F N } ( \\mathrm { L N } ( Y ^ { l } ) ) + Y ^ { l } } \\end{array}\n$$",
252
+ "text_format": "latex",
253
+ "page_idx": 3
254
+ },
255
+ {
256
+ "type": "text",
257
+ "text": "where $\\mathrm { L N } ( \\cdot )$ is LayerNorm (Ba et al., 2016). The FFN part is computed as $\\mathrm { F F N } ( X ) \\ =$ $\\operatorname { g e l u } ( X W _ { 1 } ) { \\dot { W } } _ { 2 }$ , where $W _ { 1 } , W _ { 2 }$ are parameter matrices. ",
258
+ "page_idx": 3
259
+ },
260
+ {
261
+ "type": "text",
262
+ "text": "Training We use the parallel (Equation (5)) and chunkwise recurrent (Equation (7)) representations during the training process. The parallelization within sequences or chunks efficiently utilizes GPUs to accelerate computation. More favorably, chunkwise recurrence is especially useful for long-sequence training, which is efficient in terms of both FLOPs and memory consumption. ",
263
+ "page_idx": 3
264
+ },
265
+ {
266
+ "type": "text",
267
+ "text": "Inference The recurrent representation (Equation (6)) is employed during the inference, which nicely fits autoregressive decoding. The $O ( 1 )$ complexity reduces memory and inference latency while achieving equivalent results. ",
268
+ "page_idx": 3
269
+ },
270
+ {
271
+ "type": "text",
272
+ "text": "2.4 RELATION TO AND DIFFERENCES FROM PREVIOUS METHODS ",
273
+ "text_level": 1,
274
+ "page_idx": 3
275
+ },
276
+ {
277
+ "type": "text",
278
+ "text": "Table 1 compares RetNet with previous methods from various perspectives. The comparison results echo the “impossible triangle” presented in Figure 1. Moreover, RetNet has linear memory complexity for long sequences due to the chunkwise recurrent representation. We also summarize the comparisons with specific methods as follows. ",
279
+ "page_idx": 3
280
+ },
281
+ {
282
+ "type": "table",
283
+ "img_path": "images/2665cf006527261cae8bfa75bfda137f32665ca9d85cc8cb68859016ce0dbd0a.jpg",
284
+ "table_caption": [
285
+ "Table 1: Model comparison from various perspectives. The inference cost is measured as one-step inference complexity. RetNet achieves training parallelization, constant inference cost, linear longsequence memory complexity, and good performance. $\" * >$ : whether the training implementation is sequentially parallelized, although RWKV uses channel-wise parallelism. "
286
+ ],
287
+ "table_footnote": [],
288
+ "table_body": "<table><tr><td>Architectures</td><td>Paraington</td><td>Inference Cost</td><td>MLmonrySComplexity</td><td>Performance</td></tr><tr><td>Transformer</td><td></td><td>O(N)</td><td>O(N2)</td><td>×x</td></tr><tr><td>Linear Transformer</td><td></td><td>0(1)</td><td>O(N)</td><td></td></tr><tr><td>Recurrent NN</td><td>&gt;&gt;x</td><td>0(1)</td><td>O(N)</td><td></td></tr><tr><td>RWKV</td><td></td><td>0(1)</td><td>O(N)</td><td>&gt;&gt;&gt;</td></tr><tr><td>H3/S4</td><td></td><td>0(1)</td><td>O(N log N)</td><td></td></tr><tr><td>Hyena</td><td>&gt;&gt;&gt;</td><td>O(N)</td><td>O(N log N)</td><td></td></tr><tr><td>RetNet</td><td></td><td>0(1)</td><td>O(N)</td><td></td></tr></table>",
289
+ "page_idx": 4
290
+ },
291
+ {
292
+ "type": "text",
293
+ "text": "Transformer The parallel representation of retention shares similar spirits as Transformers (Vaswani et al., 2017). The most related Transformer variant is Lex Transformer (Sun et al., 2023) which implements xPos as position embeddings. As described in Equation (3), the derivation of retention aligns with xPos. In comparison with attention, retention removes softmax and enables recurrent formulation, which significantly benefits inference. ",
294
+ "page_idx": 4
295
+ },
296
+ {
297
+ "type": "text",
298
+ "text": "S4 Unlike Equation (2), if $Q _ { n }$ and $K _ { n }$ are content-unaware, the formulation can be degenerated to S4 (Gu et al., 2021), where ${ \\cal O } = ( Q K ^ { \\tau } , Q A K ^ { \\tau } , . . , Q A ^ { | x | - 1 } K ^ { \\tau } ) * V$ . ",
299
+ "page_idx": 4
300
+ },
301
+ {
302
+ "type": "text",
303
+ "text": "Linear Attention The variants typically use various kernels $\\begin{array} { r l } { \\phi ( q _ { i } ) \\phi ( k _ { j } ) \\Bigl / \\sum _ { n = 1 } ^ { | x | } \\phi ( q _ { i } ) \\phi ( k _ { n } ) } & { { } } \\end{array}$ to replace the softmax function. However, linear attention struggles to effectively encode position information, rendering the models less performant. Besides, we reexamine sequence modeling from scratch, rather than aiming at approximating softmax. ",
304
+ "page_idx": 4
305
+ },
306
+ {
307
+ "type": "text",
308
+ "text": "AFT/RWKV Attention Free Transformer (AFT) simplifies dot-product attention to element-wise operations and moves softmax to key vectors. RWKV replaces AFT’s position embeddings with exponential decay and runs the models recurrently for training and inference. In comparison, retention preserves high-dimensional states to encode sequence information, which contributes to expressive ability and better performance. ",
309
+ "page_idx": 4
310
+ },
311
+ {
312
+ "type": "text",
313
+ "text": "xPos/RoPE Compared with relative position embedding methods proposed for Transformers, Equation (3) presents a similar formulation as xPos (Sun et al., 2023) and RoPE (Su et al., 2021). ",
314
+ "page_idx": 4
315
+ },
316
+ {
317
+ "type": "text",
318
+ "text": "Sub-LayerNorm As shown in Equation (8), the retention layer uses Sub-LayerNorm (Wang et al., 2022b) to normalize outputs. Because the multi-scale modeling leads to different variances for the heads, we replace the original LayerNorm with GroupNorm. ",
319
+ "page_idx": 4
320
+ },
321
+ {
322
+ "type": "text",
323
+ "text": "3 EXPERIMENTS ",
324
+ "text_level": 1,
325
+ "page_idx": 4
326
+ },
327
+ {
328
+ "type": "text",
329
+ "text": "We conduct experiments on language modeling to evaluate RetNet. We evaluate the proposed architecture with language modeling performance and zero-/few-shot learning on downstream tasks. Moreover, for training and inference, we compare speed, memory consumption, and latency. ",
330
+ "page_idx": 4
331
+ },
332
+ {
333
+ "type": "text",
334
+ "text": "3.1 SETUP ",
335
+ "text_level": 1,
336
+ "page_idx": 4
337
+ },
338
+ {
339
+ "type": "text",
340
+ "text": "Parameter Allocation We re-allocate the parameters in MSR and FFN for fair comparisons. Let $d$ denote $d _ { \\mathrm { m o d e l } }$ for simplicity here. In Transformers, there are about $4 d ^ { 2 }$ parameters in self-attention where $W _ { Q } , W _ { K } , W _ { V } , W _ { O } \\in \\mathbb { R } ^ { d \\times d }$ , and $8 d ^ { 2 }$ parameters in FFN where the intermediate dimension is $4 d$ . In comparison, RetNet has $8 d ^ { 2 }$ parameters in retention, where $W _ { Q } , W _ { K } \\in \\mathbb { R } ^ { d \\times d } , W _ { G } , W _ { V } \\in$ $\\mathbb { R } ^ { d \\times 2 d } , W _ { O } \\in \\mathbb { R } ^ { 2 d \\times d }$ . Notice that the head dimension of $V$ is twice $Q , K$ . The widened dimension is projected back to $d$ by $W _ { O }$ . In order to keep the parameter number the same as Transformer, the FFN intermediate dimension in RetNet is $2 d$ . Meanwhile, we set the head dimension to 256, i.e., 256 for queries and keys, and 512 for values. For fair comparison, we keep $\\gamma$ identical among different model sizes, where $\\bar { \\gamma = 1 } - e ^ { \\mathrm { l i n s p a c e } ( \\log 1 / 3 2 , \\log 1 / 5 1 2 , h ) } \\in \\bar { \\mathbb { R } } ^ { h }$ instead of the default value in Equation (8). ",
341
+ "page_idx": 4
342
+ },
343
+ {
344
+ "type": "image",
345
+ "img_path": "images/aa7a7a8cfb2ace74a97d32993bf65d25e32240eb13cb5c30d3e0f9f07becccc7.jpg",
346
+ "image_caption": [
347
+ "Figure 3: Perplexity decreases along with scaling up the model size. We empirically observe that RetNet tends to outperform Transformer when the model size is larger than 2B. "
348
+ ],
349
+ "image_footnote": [],
350
+ "page_idx": 5
351
+ },
352
+ {
353
+ "type": "table",
354
+ "img_path": "images/dc98cb75484f45cea3e3e7f89a10b8c4c7c6ff391f36fafbd45b4a628fe77a93.jpg",
355
+ "table_caption": [],
356
+ "table_footnote": [
357
+ "Table 2: Zero-shot and few-shot learning with Transformer and RetNet. The model size is 6.7B. "
358
+ ],
359
+ "table_body": "<table><tr><td></td><td>HS</td><td>BoolQ</td><td>COPA</td><td>PIQA</td><td>Winograd</td><td>Winogrande</td><td>sC</td><td>Avg</td></tr><tr><td>Zero-Shot</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Transformer</td><td>55.9</td><td>62.0</td><td>69.0</td><td>74.6</td><td>69.5</td><td>56.5</td><td>75.0</td><td>66.07</td></tr><tr><td>RetNet</td><td>60.7</td><td>62.2</td><td>77.0</td><td>75.4</td><td>77.2</td><td>58.1</td><td>76.0</td><td>69.51</td></tr><tr><td>4-Shot</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Transformer</td><td>55.8</td><td>58.7</td><td>71.0</td><td>75.0</td><td>71.9</td><td>57.3</td><td>75.4</td><td>66.44</td></tr><tr><td>RetNet</td><td>60.5</td><td>60.1</td><td>78.0</td><td>76.0</td><td>77.9</td><td>59.9</td><td>75.9</td><td>69.76</td></tr></table>",
360
+ "page_idx": 5
361
+ },
362
+ {
363
+ "type": "text",
364
+ "text": "",
365
+ "page_idx": 5
366
+ },
367
+ {
368
+ "type": "text",
369
+ "text": "Language Model Training We train language models with various sizes (i.e., 1.3B, 2.7B, and 6.7B) from scratch. The hyper-parameters are attached in Appendix A. The training corpus is a curated compilation of The Pile (Gao et al., 2020), C4 (Dodge et al., 2021), and The Stack (Kocetkov et al., 2022). We append the <bos> token to indicate the start of a sequence1. The training batch size is 4M tokens with 2048 maximal length. We train the models with 100B tokens, i.e., $2 5 \\mathrm { k }$ steps. We use the AdamW (Loshchilov & Hutter, 2019) optimizer with $\\beta _ { 1 } = 0 . 9 , \\beta _ { 2 } = 0 . 9 8$ , and weight decay is set to 0.05. The number of warmup steps is 375 with linear learning rate decay. The parameters are initialized following DeepNet (Wang et al., 2022a) to guarantee training stability. The implementation is based on TorchScale (Ma et al., 2022). We train the models with 512 AMD MI200 GPUs. ",
370
+ "page_idx": 5
371
+ },
372
+ {
373
+ "type": "text",
374
+ "text": "3.2 COMPARISONS WITH TRANSFORMER ",
375
+ "text_level": 1,
376
+ "page_idx": 5
377
+ },
378
+ {
379
+ "type": "text",
380
+ "text": "Language Modeling As shown in Figure 3, we report perplexity on the validation set for the language models based on Transformer and RetNet. We present the scaling curves with three model sizes, i.e., 1.3B, 2.7B, and 6.7B. RetNet achieves comparable results with Transformers. More importantly, the results indicate that RetNet is favorable regarding size scaling. Besides performance, the RetNet training is quite stable in our experiments. Experimental results show that RetNet is a strong competitor to Transformer for large language models. Empirically, we find that RetNet starts to outperform Transformer when the model size is larger than 2B. We also summarize the language modeling results with different context lengths in Appendix B. ",
381
+ "page_idx": 5
382
+ },
383
+ {
384
+ "type": "text",
385
+ "text": "Zero-Shot and Few-Shot Evaluation on Downstream Tasks We also compare the language models on a wide range of downstream tasks. We evaluate zero-shot and 4-shot learning with the 6.7B models. As shown in Table 2, the datasets include HellaSwag (HS; Zellers et al. 2019), BoolQ (Clark et al., 2019), COPA (Wang et al., 2019), PIQA (Bisk et al., 2020), Winograd, Winogrande (Levesque et al., 2012), and StoryCloze (SC; Mostafazadeh et al. 2017). The accuracy numbers are consistent with language modeling perplexity presented in Figure 3. RetNet achieves comparable performance with Transformer on zero-shot and in-context learning settings. ",
386
+ "page_idx": 5
387
+ },
388
+ {
389
+ "type": "table",
390
+ "img_path": "images/ebd423a9878f562eeca76962609f89ed27cc13b3d4ea2606a718010d8593f0bd.jpg",
391
+ "table_caption": [
392
+ "Table 3: Training cost of Transformer (Trm), Transformer with FlashAttention $\\mathrm { T r m } +$ FlashAttn), and RetNet. We report memory consumption and training throughput (word per second; wps). "
393
+ ],
394
+ "table_footnote": [],
395
+ "table_body": "<table><tr><td rowspan=\"2\">Model Size</td><td colspan=\"3\"></td><td colspan=\"3\">Throm+lashAtm) RetNet</td></tr><tr><td>Trm</td><td>TrmmFry AtRetNet</td><td></td><td>Trm</td><td></td><td></td></tr><tr><td>1.3B</td><td>74.8</td><td>38.8</td><td>34.5</td><td>10832.4</td><td>63965.2</td><td>73344.8</td></tr><tr><td>2.7B</td><td>69.6</td><td>42.1</td><td>42.0</td><td>5186.0</td><td>34990.2</td><td>38921.2</td></tr><tr><td>6.7B</td><td>69.0</td><td>51.4</td><td>48.0</td><td>2754.4</td><td>16230.1</td><td>17458.6</td></tr><tr><td>13B</td><td>61.4</td><td>46.3</td><td>45.9</td><td>1208.9</td><td>7945.1</td><td>8642.2</td></tr></table>",
396
+ "page_idx": 6
397
+ },
398
+ {
399
+ "type": "text",
400
+ "text": "",
401
+ "page_idx": 6
402
+ },
403
+ {
404
+ "type": "text",
405
+ "text": "3.3 TRAINING COST ",
406
+ "text_level": 1,
407
+ "page_idx": 6
408
+ },
409
+ {
410
+ "type": "text",
411
+ "text": "As shown in Table 3, we compare the training speed and memory consumption of Transformer and RetNet, where the training sequence length is 8192. We also compare with FlashAttention (Dao et al., 2022a), which improves speed and reduces GPU memory IO by recomputation and kernel fusion. In comparison, we implement RetNet using vanilla PyTorch code, and leave kernel fusion or FlashAttention-like acceleration for future work. We use chunkwise recurrent representation of retention as described in Equation (7). The chunk size is set to 512. We evaluate the results with eight Nvidia A100-80GB GPUs, because FlashAttention is highly optimized for A100. Tensor parallelism is enabled for 6.7B and 13B models. ",
412
+ "page_idx": 6
413
+ },
414
+ {
415
+ "type": "text",
416
+ "text": "Experimental results show that RetNet is more memory-efficient and has higher throughput than Transformers during training. Even compared with FlashAttention, RetNet is still competitive in terms of speed and memory cost. Moreover, without relying on specific kernels, it is easy to train RetNet on other platforms efficiently. For example, we train the RetNet models on an AMD MI200 cluster with decent throughput. It is notable that RetNet has the potential to further reduce cost via advanced implementation, such as kernel fusion. ",
417
+ "page_idx": 6
418
+ },
419
+ {
420
+ "type": "text",
421
+ "text": "3.4 INFERENCE COST ",
422
+ "text_level": 1,
423
+ "page_idx": 6
424
+ },
425
+ {
426
+ "type": "text",
427
+ "text": "As shown in Figure 4, we compare memory cost, throughput, and latency of Transformer and RetNet during inference. Transformers reuse KV caches of previously decoded tokens. RetNet uses the recurrent representation as described in Equation (6). We evaluate the 6.7B model on the A100-80GB GPU. Figure 4 shows that RetNet outperforms Transformer in terms of inference cost. ",
428
+ "page_idx": 6
429
+ },
430
+ {
431
+ "type": "text",
432
+ "text": "Memory As shown in Figure 4a, the memory cost of Transformer increases linearly due to KV caches. In contrast, the memory consumption of RetNet remains consistent even for long sequences, requiring much less GPU memory to host RetNet. The additional memory consumption of RetNet is almost negligible (i.e., about $3 \\%$ ) while the model weights occupy $9 7 \\%$ . ",
433
+ "page_idx": 6
434
+ },
435
+ {
436
+ "type": "text",
437
+ "text": "Throughput As presented in Figure 4b, the throughput of Transformer drops along with the decoding length increases. In comparison, RetNet has higher and length-invariant throughput during decoding, by utilizing the recurrent representation of retention. ",
438
+ "page_idx": 6
439
+ },
440
+ {
441
+ "type": "text",
442
+ "text": "Latency Latency is an important metric in deployment, which greatly affects user experience. We report decoding latency in Figure 4c. Experimental results show that increasing batch size renders Transformer’s latency larger. Moreover, the latency of Transformers grows faster with longer input. In order to make latency acceptable, we have to restrict the batch size, which harms the overall inference throughput of Transformers. By contrast, RetNet’s decoding latency outperforms Transformers and keeps almost the same across different batch sizes and input lengths. ",
443
+ "page_idx": 6
444
+ },
445
+ {
446
+ "type": "image",
447
+ "img_path": "images/d62ff85842603d69bbb88c6b503ad61bbf22a5bc48b867894d63f7d87068c4b1.jpg",
448
+ "image_caption": [
449
+ "(c) Inference latency with different batch sizes. ",
450
+ "Figure 4: Inference cost of Transformer and RetNet with a model size of 6.7B. RetNet outperforms Transformers in terms of memory consumption, throughput, and latency. "
451
+ ],
452
+ "image_footnote": [],
453
+ "page_idx": 7
454
+ },
455
+ {
456
+ "type": "table",
457
+ "img_path": "images/87b32f340f21fa49b7dae7c9e5b707d2750e7ea57f0ef3dc6b382b65b37b8149.jpg",
458
+ "table_caption": [],
459
+ "table_footnote": [],
460
+ "table_body": "<table><tr><td>Method</td><td>In-Domain</td><td>PG22</td><td>QMSum</td><td>GovReport</td><td>SummScreen</td></tr><tr><td>RWKV</td><td>30.92</td><td>51.41</td><td>28.17</td><td>19.80</td><td>25.78</td></tr><tr><td>H3</td><td>29.97</td><td>49.17</td><td>24.29</td><td>19.19</td><td>25.11</td></tr><tr><td>Hyena</td><td>32.08</td><td>52.75</td><td>28.18</td><td>20.55</td><td>26.51</td></tr><tr><td>Linear Transformer</td><td>40.24</td><td>63.86</td><td>28.45</td><td>25.33</td><td>32.02</td></tr><tr><td>RetNet</td><td>26.05</td><td>45.27</td><td>21.33</td><td>16.52</td><td>22.48</td></tr></table>",
461
+ "page_idx": 7
462
+ },
463
+ {
464
+ "type": "text",
465
+ "text": "Table 4: Perplexity results on language modeling. RetNet outperforms other architectures on both the in-domain evaluation set and various out-of-domain corpora. ",
466
+ "page_idx": 7
467
+ },
468
+ {
469
+ "type": "text",
470
+ "text": "3.5 COMPARISON WITH TRANSFORMER VARIANTS ",
471
+ "text_level": 1,
472
+ "page_idx": 7
473
+ },
474
+ {
475
+ "type": "text",
476
+ "text": "Apart from Transformer, we compare RetNet with various efficient Transformer variants, including Linear Transformer (Katharopoulos et al., 2020), RWKV (Peng et al., 2023), H3 (Dao et al., 2022b), and Hyena (Poli et al., 2023). All models have 200M parameters with 16 layers and a hidden dimension of 1024. For H3, we set the head dimension as 8. For RWKV, we use the TimeMix module to substitute self-attention layers while keeping FFN layers consistent with other models for fair comparisons. We train the models with 10k steps with a batch size of 0.5M tokens. Most hyperparameters and training corpora are kept the same as in Section 3.1. ",
477
+ "page_idx": 7
478
+ },
479
+ {
480
+ "type": "text",
481
+ "text": "Table 4 reports the perplexity numbers on the in-domain validation set and other out-of-domain corpora, e.g., Project Gutenberg 2019-2022 (PG22; Sun et al. 2023), QMSum (Zhong et al., 2021), GovReport (Huang et al., 2021), SummScreen (Chen et al., 2021; Shaham et al., 2022). Overall, RetNet outperforms previous methods across different datasets. RetNet not only achieves better evaluation results on the in-domain corpus but also obtains lower perplexity on several out-of-domain datasets. The favorable performance makes RetNet a strong successor to Transformer, besides the benefits of significant cost reduction (Sections 3.3 and 3.4). ",
482
+ "page_idx": 7
483
+ },
484
+ {
485
+ "type": "table",
486
+ "img_path": "images/d32ed25b2cb94fbd6eb2f408bd4289267483a57fa024a3faa67de8a9a1ee2f66.jpg",
487
+ "table_caption": [
488
+ "Table 5: Ablation results on in-domain and out-of-domain corpora. "
489
+ ],
490
+ "table_footnote": [],
491
+ "table_body": "<table><tr><td>Method</td><td>In-Domain</td><td>PG22</td><td>QMSum</td><td>GovReport</td><td> SummScreen</td></tr><tr><td>RetNet</td><td>26.05</td><td>45.27</td><td>21.33</td><td>16.52</td><td>22.48</td></tr><tr><td>- swish gate</td><td>27.84</td><td>49.44</td><td>22.52</td><td>17.45</td><td>23.72</td></tr><tr><td>- GroupNorm</td><td>27.54</td><td>46.95</td><td>22.61</td><td>17.59</td><td>23.73</td></tr><tr><td>- γ decay</td><td>27.86</td><td>47.85</td><td>21.99</td><td>17.49</td><td>23.70</td></tr><tr><td>- multi-scale decay</td><td>27.02</td><td>47.18</td><td>22.08</td><td>17.17</td><td>23.38</td></tr><tr><td>Reduce head dimension</td><td>27.68</td><td>47.72</td><td>23.09</td><td>17.46</td><td>23.41</td></tr></table>",
492
+ "page_idx": 8
493
+ },
494
+ {
495
+ "type": "text",
496
+ "text": "",
497
+ "page_idx": 8
498
+ },
499
+ {
500
+ "type": "text",
501
+ "text": "In addition, we discuss the training and inference efficiency of the compared methods. Let $d$ denote the hidden dimension, and $n$ the sequence length. For training, RWKV’s token-mixing complexity is $O ( d n )$ while Hyena’s is $O ( d n \\log n )$ with Fast Fourier Transform acceleration. The above two methods reduce training FLOPS via employing element-wise operators to trade-off modeling capacity. In comparison with retention, the chunk-wise recurrent representation is $O ( d n ( b + h ) )$ , where $b$ is the chunk size, $h$ is the head dimension, and we usually set $b = 5 1 2$ , $h = 2 5 6$ . For either large model size (i.e., larger $d$ ) or sequence length, the additional $b + h$ has negligible effects. So the RetNet training is quite efficient without sacrificing the modeling performance. For inference, among the compared efficient architectures, Hyena has the same complexity (i.e., $O ( n )$ per step) as Transformer while the others can perform $O ( 1 )$ decoding. ",
502
+ "page_idx": 8
503
+ },
504
+ {
505
+ "type": "text",
506
+ "text": "3.6 ABLATION STUDIES ",
507
+ "text_level": 1,
508
+ "page_idx": 8
509
+ },
510
+ {
511
+ "type": "text",
512
+ "text": "We ablate various design choices of RetNet and report the language modeling results in Table 5. The evaluation settings and metrics are the same as in Section 3.5. ",
513
+ "page_idx": 8
514
+ },
515
+ {
516
+ "type": "text",
517
+ "text": "Architecture We ablate the swish gate and GroupNorm as described in Equation (8). Table 5 shows that the above two components improve performance. First, the gating module is essential for enhancing non-linearity and improving model capability. Notice that we use the same parameter allocation as Transformers after removing the gate. Second, group normalization in retention balances the variances of multi-head outputs, which improves training stability and language modeling results. ",
518
+ "page_idx": 8
519
+ },
520
+ {
521
+ "type": "text",
522
+ "text": "Multi-Scale Decay Equation (8) shows that we use different $\\gamma$ as the decay rates for the retention heads. In the ablation studies, we examine removing $\\gamma$ decay (i.e., $^ { 6 6 } - \\gamma$ decay”) and applying the same decay rate across heads (i.e., “− multi-scale decay”). Specifically, ablating $\\gamma$ decay is equivalent to $\\gamma = 1$ . In the second setting, we set $\\gamma = 1 2 7 / 1 2 8$ for all heads. Table 5 indicates that both the decay mechanism and using multiple decay rates can improve the language modeling performance. ",
523
+ "page_idx": 8
524
+ },
525
+ {
526
+ "type": "text",
527
+ "text": "Head Dimension As indicated by the recurrent perspective of Equation (1), the head dimension implies the memory capacity of hidden states. In ablation, we reduce the default head dimension from 256 to 64, i.e., 64 for queries and keys, and 128 for values. We keep the hidden dimension $d _ { \\mathrm { m o d e l } }$ the same. Table 5 shows that the larger head dimension achieves better performance. ",
528
+ "page_idx": 8
529
+ },
530
+ {
531
+ "type": "text",
532
+ "text": "4 CONCLUSION ",
533
+ "text_level": 1,
534
+ "page_idx": 8
535
+ },
536
+ {
537
+ "type": "text",
538
+ "text": "In this work, we propose retentive networks (RetNet) for sequence modeling, which enables various representations, i.e., parallel, recurrent, and chunkwise recurrent. RetNet achieves significantly better inference efficiency (in terms of memory, speed, and latency), favorable training parallelization, and competitive performance compared with Transformers. The above advantages make RetNet an ideal successor to Transformers for large language models, especially considering the deployment benefits brought by the $O ( 1 )$ inference complexity. In the future, we would like to scale up RetNet in terms of model size and training steps. In addition, we are interested in deploying RetNet models on various edge devices, such as mobile phones. ",
539
+ "page_idx": 8
540
+ },
541
+ {
542
+ "type": "text",
543
+ "text": "REFERENCES ",
544
+ "text_level": 1,
545
+ "page_idx": 9
546
+ },
547
+ {
548
+ "type": "text",
549
+ "text": "Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón, and Sumit Sanghai. GQA: Training generalized multi-query Transformer models from multi-head checkpoints. arXiv preprint arXiv:2305.13245, 2023. \nJimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016. \nYonatan Bisk, Rowan Zellers, Ronan Le Bras, Jianfeng Gao, and Yejin Choi. Piqa: Reasoning about physical commonsense in natural language. In Thirty-Fourth AAAI Conference on Artificial Intelligence, 2020. \nMingda Chen, Zewei Chu, Sam Wiseman, and Kevin Gimpel. Summscreen: A dataset for abstractive screenplay summarization. arXiv preprint arXiv:2104.07091, 2021. \nChristopher Clark, Kenton Lee, Ming-Wei Chang, Tom Kwiatkowski, Michael Collins, and Kristina Toutanova. BoolQ: Exploring the surprising difficulty of natural yes/no questions. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics, pp. 2924–2936, 2019. doi: 10.18653/v1/N19-1300. \nTri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Ré. Flashattention: Fast and memoryefficient exact attention with io-awareness. Advances in Neural Information Processing Systems, 35:16344–16359, 2022a. \nTri Dao, Daniel Y Fu, Khaled K Saab, Armin W Thomas, Atri Rudra, and Christopher Ré. Hungry hungry hippos: Towards language modeling with state space models. arXiv preprint arXiv:2212.14052, 2022b. \nJesse Dodge, Ana Marasovic, Gabriel Ilharco, Dirk Groeneveld, Margaret Mitchell, and Matt Gardner. ´ Documenting large webtext corpora: A case study on the colossal clean crawled corpus. In Conference on Empirical Methods in Natural Language Processing, 2021. \nLeo Gao, Stella Biderman, Sid Black, Laurence Golding, 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. \nAlbert Gu, Karan Goel, and Christopher Ré. Efficiently modeling long sequences with structured state spaces. arXiv preprint arXiv:2111.00396, 2021. \nDan Hendrycks and Kevin Gimpel. Gaussian error linear units (GELUs). arXiv: Learning, 2016. \nSepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural Computation, 9: 1735–1780, November 1997. \nLuyang Huang, Shuyang Cao, Nikolaus Parulian, Heng Ji, and Lu Wang. Efficient attentions for long document summarization. arXiv preprint arXiv:2104.02112, 2021. \nAngelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret. Transformers are rnns: Fast autoregressive transformers with linear attention. In International Conference on Machine Learning, pp. 5156–5165. PMLR, 2020. \nDenis Kocetkov, Raymond Li, Loubna Ben Allal, Jia Li, Chenghao Mou, Carlos Muñoz Ferrandis, Yacine Jernite, Margaret Mitchell, Sean Hughes, Thomas Wolf, Dzmitry Bahdanau, Leandro von Werra, and Harm de Vries. The Stack: 3TB of permissively licensed source code. Preprint, 2022. \nHector Levesque, Ernest Davis, and Leora Morgenstern. The winograd schema challenge. In Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning, 2012. \nIlya Loshchilov and Frank Hutter. Decoupled weight decay regularization. In International Conference on Learning Representations, 2019. \nShuming Ma, Hongyu Wang, Shaohan Huang, Wenhui Wang, Zewen Chi, Li Dong, Alon Benhaim, Barun Patra, Vishrav Chaudhary, Xia Song, and Furu Wei. TorchScale: Transformers at scale. CoRR, abs/2211.13184, 2022. \nNasrin Mostafazadeh, Michael Roth, Annie Louis, Nathanael Chambers, and James Allen. Lsdsem 2017 shared task: The story cloze test. In Proceedings of the 2nd Workshop on Linking Models of Lexical, Sentential and Discourse-level Semantics, pp. 46–51, 2017. \nAntonio Orvieto, Samuel L. Smith, Albert Gu, Anushan Fernando, Caglar Gulcehre, Razvan Pascanu, and Soham De. Resurrecting recurrent neural networks for long sequences. ArXiv, abs/2303.06349, 2023. \nBo Peng, Eric Alcaide, Quentin G. Anthony, Alon Albalak, Samuel Arcadinho, Huanqi Cao, Xin Cheng, Michael Chung, Matteo Grella, G Kranthikiran, Xuming He, Haowen Hou, et al. RWKV: Reinventing RNNs for the Transformer era. ArXiv, abs/2305.13048, 2023. \nMichael Poli, Stefano Massaroli, Eric Nguyen, Daniel Y Fu, Tri Dao, Stephen Baccus, Yoshua Bengio, Stefano Ermon, and Christopher Ré. Hyena hierarchy: Towards larger convolutional language models. arXiv preprint arXiv:2302.10866, 2023. \nPrajit Ramachandran, Barret Zoph, and Quoc V. Le. Swish: a self-gated activation function. arXiv: Neural and Evolutionary Computing, 2017. \nUri Shaham, Elad Segal, Maor Ivgi, Avia Efrat, Ori Yoran, Adi Haviv, Ankit Gupta, Wenhan Xiong, Mor Geva, Jonathan Berant, et al. Scrolls: Standardized comparison over long language sequences. arXiv preprint arXiv:2201.03533, 2022. \nNoam M. Shazeer. Fast Transformer decoding: One write-head is all you need. ArXiv, abs/1911.02150, 2019. \nMohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. Megatron-LM: Training multi-billion parameter language models using model parallelism. arXiv preprint arXiv:1909.08053, 2019. \nJianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. arXiv preprint arXiv:2104.09864, 2021. \nYutao Sun, Li Dong, Barun Patra, Shuming Ma, Shaohan Huang, Alon Benhaim, Vishrav Chaudhary, Xia Song, and Furu Wei. A length-extrapolatable transformer. In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 14590– 14604, Toronto, Canada, July 2023. Association for Computational Linguistics. \nHugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, et al. LLaMA: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023a. \nHugo 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, 2023b. \nAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, 4-9 December 2017, Long Beach, CA, USA, pp. 6000–6010, 2017. \nAlex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. SuperGLUE: A stickier benchmark for general-purpose language understanding systems. arXiv preprint arXiv:1905.00537, 2019. \nHongyu Wang, Shuming Ma, Li Dong, Shaohan Huang, Dongdong Zhang, and Furu Wei. DeepNet: ",
550
+ "page_idx": 9
551
+ },
552
+ {
553
+ "type": "text",
554
+ "text": "",
555
+ "page_idx": 10
556
+ },
557
+ {
558
+ "type": "text",
559
+ "text": "Scaling Transformers to 1,000 layers. ArXiv, abs/2203.00555, 2022a. ",
560
+ "page_idx": 10
561
+ },
562
+ {
563
+ "type": "text",
564
+ "text": "Hongyu Wang, Shuming Ma, Shaohan Huang, Li Dong, Wenhui Wang, Zhiliang Peng, Yu Wu, Payal Bajaj, Saksham Singhal, Alon Benhaim, et al. Foundation transformers. arXiv preprint arXiv:2210.06423, 2022b. \nYuxin Wu and Kaiming He. Group normalization. In Proceedings of the European conference on computer vision (ECCV), pp. 3–19, 2018. \nRowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. Hellaswag: Can a machine really finish your sentence? In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, 2019. \nMing Zhong, Da Yin, Tao Yu, Ahmad Zaidi, Mutethia Mutuma, Rahul Jha, Ahmed Hassan Awadallah, Asli Celikyilmaz, Yang Liu, Xipeng Qiu, et al. Qmsum: A new benchmark for query-based multidomain meeting summarization. arXiv preprint arXiv:2104.05938, 2021. ",
565
+ "page_idx": 11
566
+ },
567
+ {
568
+ "type": "table",
569
+ "img_path": "images/9e2611013fe45ddd403e04ea63eb7e5de5ed3bceec401139b809f8296b5f5972.jpg",
570
+ "table_caption": [
571
+ "A HYPERPARAMETERS ",
572
+ "Table 6: Hyperparamters used for the models in Section 3. "
573
+ ],
574
+ "table_footnote": [],
575
+ "table_body": "<table><tr><td>Hyperparameters</td><td>1.3B</td><td>2.7B</td><td>6.7B</td></tr><tr><td>Layers</td><td>24</td><td>32</td><td>32</td></tr><tr><td>Hidden size</td><td>2048</td><td>2560</td><td>4096</td></tr><tr><td>FFN size Heads</td><td>4096 8</td><td>5120 10</td><td>8192 16</td></tr><tr><td>Learning rate LR scheduler Warm-up steps</td><td>6 ×10-4</td><td>3×10-4 Linear decay 375</td><td>3×10-4</td></tr><tr><td>Tokens per batch Adam β</td><td></td><td>4M (0.9, 0.98)</td><td></td></tr><tr><td>Training steps</td><td></td><td>25,000</td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td>Gradient clipping</td><td></td><td>2.0</td><td></td></tr><tr><td>Dropout</td><td></td><td>0.1</td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td>Weight decay</td><td></td><td>0.01</td><td></td></tr></table>",
576
+ "page_idx": 12
577
+ },
578
+ {
579
+ "type": "text",
580
+ "text": "B RESULTS WITH DIFFERENT CONTEXT LENGTHS ",
581
+ "text_level": 1,
582
+ "page_idx": 12
583
+ },
584
+ {
585
+ "type": "text",
586
+ "text": "As shown in Table 7, we report language modeling results with different context lengths. In order to make the numbers comparable, we use 2048 text chunks as evaluation data and only compute perplexity for the last 128 tokens. Experimental results show that RetNet outperforms Transformer across different context lengths. Besides, RetNet can utilize longer context for better results. ",
587
+ "page_idx": 12
588
+ },
589
+ {
590
+ "type": "table",
591
+ "img_path": "images/0b90e738cf3336d792f0bdd8aee59c65097fccc0ea807e77342414a29ffa28f5.jpg",
592
+ "table_caption": [],
593
+ "table_footnote": [],
594
+ "table_body": "<table><tr><td>Model</td><td>512</td><td>1024</td><td>2048</td></tr><tr><td>Transformer</td><td>13.55</td><td>12.56</td><td>12.35</td></tr><tr><td>RetNet</td><td>13.09</td><td>12.14</td><td>11.98</td></tr></table>",
595
+ "page_idx": 12
596
+ },
597
+ {
598
+ "type": "text",
599
+ "text": "Table 7: Language modeling perplexity of RetNet and Transformer with different context length. The results show that RetNet has a consistent advantage across sequence length. ",
600
+ "page_idx": 12
601
+ },
602
+ {
603
+ "type": "text",
604
+ "text": "C INFERENCE COST OF GROUPED-QUERY RETENTION",
605
+ "text_level": 1,
606
+ "page_idx": 12
607
+ },
608
+ {
609
+ "type": "text",
610
+ "text": "We compare with grouped-query attention (Ainslie et al., 2023) and evaluate the method in the context of RetNet. Grouped-query attention makes a trade-off between performance and efficiency, which has been successfully verified in LLaMA2 34B/70B (Touvron et al., 2023b). The method reduces the overhead of key/value cache during inference. Moreover, the performance of grouped-query attention is better than multi-query attention (Shazeer, 2019), overcoming the quality degradation brought by using one-head key value. ",
611
+ "page_idx": 12
612
+ },
613
+ {
614
+ "type": "text",
615
+ "text": "As shown in Table 8, we compare the inference cost with grouped-query attention and apply the method for RetNet. For the LLaMA2 70B model, the number of key/value heads is reduced by $8 \\times$ , where the query head number is 64 while the key/value head number is 8. For RetNet-70B, the parameter allocation is identical to LLaMA (Touvron et al., 2023a), where the dimension is 8192, and the head number is 32 for RetNet. For RetNet-70B-GQ2, the key-value head number is 16, where grouped-query retention is applied. We run the inference with four A100 GPUs without quantization. ",
616
+ "page_idx": 12
617
+ },
618
+ {
619
+ "type": "text",
620
+ "text": "When the batch size is 256, LLaMA2 runs out of memory while RetNet without group query still has a high throughput. When equipped with grouped-query retention, RetNet-70B achieves $38 \\%$ acceleration and saves $30 \\%$ memory. ",
621
+ "page_idx": 12
622
+ },
623
+ {
624
+ "type": "text",
625
+ "text": "We evaluate LLaMA2 under $2 \\mathrm { k }$ and $^ { 8 \\mathrm { k } }$ lengths separately. The batch size is decreased to 8 so that LLaMA2 can be run without out of memory. Table 8 shows that the inference cost of Transformers increases with the sequence length. In contrast, RetNet is length-invariant. Moreover, RetNet-70BGQ2 achieves better latency, throughput, and GPU memory than LLaMA2-70B-2k/8k equipped with grouped-query attention. Notice that evaluation metrics are averaged over positions of different sequence lengths for fair comparison, rather than only considering the inference cost of maximum length. ",
626
+ "page_idx": 13
627
+ },
628
+ {
629
+ "type": "text",
630
+ "text": "Table 8: Inference cost of RetNet and LLaMA2-70B with difference batch size and length. LLaMA2- 70B is equipped with grouped-query attention, reducing key/value heads by $8 \\times$ . “-GQ2” means grouped-query retention, which reduces half of key/value heads. $\\ddot { \\mathbf { \\eta } } ^ { 6 6 } - 2 \\mathbf { k } ^ { \\mathbf { \\eta } , \\mathbf { \\eta } }$ and “-8k” indicate sequence length for LLaMA2, while RetNet is length-invariant. RetNet is capable of large-batch inference and is favourable in terms of latency, throughput, and GPU memory. ",
631
+ "page_idx": 13
632
+ },
633
+ {
634
+ "type": "text",
635
+ "text": "D PSEUDO CODE OF RETENTION ",
636
+ "text_level": 1,
637
+ "page_idx": 13
638
+ },
639
+ {
640
+ "type": "text",
641
+ "text": "def ParallelRetention( ",
642
+ "text_level": 1,
643
+ "page_idx": 13
644
+ },
645
+ {
646
+ "type": "text",
647
+ "text": "q, # bsz $^ *$ num_head $^ *$ len $^ *$ qk_dim k, # bsz $^ *$ num_head $^ *$ len $^ *$ qk_dim v, # bsz $^ *$ num_head $^ *$ len $^ *$ v_dim decay_mask $\\#$ num_head $^ *$ len $^ *$ len ): \nretention $=$ q @ k.transpose(−1, −2) retention $=$ retention $^ *$ decay_mask output $=$ retention @ v \noutput $=$ group_norm(output) \nreturn output ",
648
+ "page_idx": 13
649
+ },
650
+ {
651
+ "type": "table",
652
+ "img_path": "images/8e3f770e113203a831b07150e84179ea86c939d6a0bb705e1506c8e2e12574e9.jpg",
653
+ "table_caption": [
654
+ "Figure 5: Pseudocode for the three computation paradigms of retention. "
655
+ ],
656
+ "table_footnote": [],
657
+ "table_body": "<table><tr><td>Model</td><td>Batch Size</td><td>Latency (ms)↓</td><td>Throughput (wps)↑</td><td>Memory (GB)↓</td></tr><tr><td>LLaMA2-70B-2k</td><td>256</td><td></td><td></td><td>0OM</td></tr><tr><td>LLaMA2-70B-8k</td><td>256</td><td></td><td></td><td>0OM</td></tr><tr><td>RetNet-70B</td><td>256</td><td>639.1</td><td>410.19</td><td>72.469</td></tr><tr><td>RetNet-70B-GQ2</td><td>256</td><td>461.8</td><td>567.66</td><td>52.726</td></tr><tr><td>LLaMA2-70B-2k</td><td>8</td><td>184.5</td><td>44.42</td><td>33.374</td></tr><tr><td>LLaMA2-70B-8k</td><td>8</td><td>277.7</td><td>29.50</td><td>37.386</td></tr><tr><td>RetNet-70B-GQ2</td><td>8</td><td>106.2</td><td>77.02</td><td>32.301</td></tr></table>",
658
+ "page_idx": 13
659
+ },
660
+ {
661
+ "type": "text",
662
+ "text": "def RecurrentRetention( ",
663
+ "text_level": 1,
664
+ "page_idx": 13
665
+ },
666
+ {
667
+ "type": "text",
668
+ "text": "q, k, v, # bsz $^ *$ num_head $^ *$ len $^ *$ qkv_dim \npast_kv, # bsz $^ *$ num_head $^ *$ qk_dim $^ *$ v_dim \ndecay # num_head $* \\ 1 \\ * \\ 1$ \n): \ncurrent_kv $=$ decay $^ *$ past_kv $^ +$ k.unsqueeze $( - 1 ) ~ * ~ \\mathtt { v }$ .unsqueeze(−2) \noutput $=$ torch.sum(q.unsqueeze(−1) ∗ current_kv, ${ \\dot { \\mathsf { d i m } } } = - 2$ ) \noutput $=$ group_norm(output) \nreturn output, current_kv ",
669
+ "page_idx": 13
670
+ },
671
+ {
672
+ "type": "text",
673
+ "text": "def ChunkwiseRetention( ",
674
+ "text_level": 1,
675
+ "page_idx": 13
676
+ },
677
+ {
678
+ "type": "image",
679
+ "img_path": "images/248c102384ad8db62124a64abbf33a97ed18e252042627104445726a3db4f83c.jpg",
680
+ "image_caption": [],
681
+ "image_footnote": [],
682
+ "page_idx": 13
683
+ }
684
+ ]
parse/test/UU9Icwbhin/UU9Icwbhin_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/UU9Icwbhin/UU9Icwbhin_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Vi8AepAXGy/Vi8AepAXGy.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Vi8AepAXGy/Vi8AepAXGy_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Vi8AepAXGy/Vi8AepAXGy_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/Vi8AepAXGy/Vi8AepAXGy_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/ZPQhzTSWA7/ZPQhzTSWA7.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/ZPQhzTSWA7/ZPQhzTSWA7_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/ZPQhzTSWA7/ZPQhzTSWA7_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/ZPQhzTSWA7/ZPQhzTSWA7_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/dsUB4bst9S/dsUB4bst9S.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/dsUB4bst9S/dsUB4bst9S_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/dsUB4bst9S/dsUB4bst9S_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/dsUB4bst9S/dsUB4bst9S_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/fvhJu0FODp/fvhJu0FODp.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/fvhJu0FODp/fvhJu0FODp_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/fvhJu0FODp/fvhJu0FODp_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/fvhJu0FODp/fvhJu0FODp_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/nnVO1PvbTv/nnVO1PvbTv.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/nnVO1PvbTv/nnVO1PvbTv_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/nnVO1PvbTv/nnVO1PvbTv_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/nnVO1PvbTv/nnVO1PvbTv_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/pyW37euNXb/pyW37euNXb.md ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UPGRADING VAE TRAINING WITH UNLIMITED DATA PLANS PROVIDED BY DIFFUSION MODELS
2
+
3
+ Anonymous authors Paper under double-blind review
4
+
5
+ # ABSTRACT
6
+
7
+ Variational autoencoders (VAEs) are popular models for representation learning but their encoders are susceptible to overfitting (Cremer et al., 2018) because they are trained on a finite training set instead of the true (continuous) data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . Diffusion models, on the other hand, avoid this issue by keeping the encoder fixed. This makes their representations less interpretable, but it simplifies training, enabling accurate and continuous approximations of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . In this paper, we show that overfitting encoders in VAEs can be effectively mitigated by training on samples from a pre-trained diffusion model. These results are somewhat unexpected as recent findings (Alemohammad et al., 2023; Shumailov et al., 2023) observe a decay in generative performance when models are trained on data generated by another generative model. We analyze generalization performance, amortization gap, and robustness of VAEs trained with our proposed method on three different data sets. We find improvements in all metrics compared to both normal training and conventional data augmentation methods, and we show that a modest amount of samples from the diffusion model suffices to obtain these gains.
8
+
9
+ # 1 INTRODUCTION
10
+
11
+ Variational autoencoders (VAEs, Kingma & Welling (2014); Rezende et al. (2014)) are a class of deep probabilistic models. They model the underlying data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ from which a given training set ${ \mathcal { D } } _ { \mathrm { t r a i n } } = \{ { \pmb x } _ { i } \} _ { i = 1 } ^ { N }$ was drawn. Beyond their generative modeling capabilities, VAEs have many other favorable properties by design which lead to applications such as representation learning (van den Oord et al., 2017) and compression (Yang et al., 2023). However, these properties can be compromised if the VAE is overfitted. Specifically, the encoder $f _ { \phi } ( \pmb { x } )$ is more susceptible to overfitting (Wu et al., 2017; Cremer et al., 2018; Shu et al., 2018) than the decoder since a finite training set $\mathcal { D } _ { \mathrm { t r a i n } }$ is repeatedly fed into the encoder. By contrast, the decoder is trained on unique samples from the approximate posterior distribution inferred by the encoder.
12
+
13
+ Overfitting in the encoder implies that the learned mapping $f _ { \phi } ( \pmb { x } )$ does not generalize well to unseen data, which can negatively impact the performance of generative modeling, amortized inference, and adversarial robustness. For generative modeling, as the number of training epochs increases, an overfitted VAE will have a higher evidence lower bound (ELBO) on the training set but a lower ELBO on the test set. For amortized inference, an overfitted encoder is more likely to map unseen data to a suboptimal set of variational parameters. This results in a lower ELBO when compared to the ELBO obtained by directly optimizing these parameters. For robustness, an overfitted encoder often learns a less smooth $f _ { \phi } ( \pmb { x } )$ , such that a small change in the input $_ { \textbf { \em x } }$ can result in a large difference in the latent space. This makes VAEs vulnerable to adversarial attacks, causing realistic and hardly distinguishable inputs to yield semantically different outputs (Kuzina et al., 2022).
14
+
15
+ One major cause of overfitting in VAEs is the multiple iterations over the insufficient amount of training data (more details in Section 5). Ideally, we aim to train VAEs with unique samples drawn from $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . But in practice, we only have access to the finite training set $\mathcal { D } _ { \mathrm { t r a i n } }$ . Hence, we ask the question: “Can we have infinite training samples drawn from $p _ { \mathrm { d a t a } } ( \pmb { x } )$ ?” The answer is likely to be “No”, unless we have access to the true data generating process. However, we do have a class of models, known as diffusion models (Sohl-Dickstein et al., 2015; Ho et al., 2020; Song et al., 2021), that can estimate $p _ { \mathrm { d a t a } } ( \pmb { x } )$ very well, and that can generate as many sample as we want. Diffusion models achieve the state of the art performance at data generation, but they lack the
16
+
17
+ Ideal:
18
+
19
+ $$
20
+ \mathcal { L } = \mathbb { E } _ { { \pmb x } \sim p _ { \mathrm { d a t a } } ( \pmb x ) } \left[ \mathrm { E L B O } _ { \Theta } ( { \pmb x } ) \right]
21
+ $$
22
+
23
+ $$
24
+ \mathcal { L } = \mathbb { E } _ { \boldsymbol { x } \sim \mathcal { D } _ { \mathrm { t r a i n } } } \left[ \mathrm { E L B O } _ { \Theta } ( \pmb { x } ) \right]
25
+ $$
26
+
27
+ $$
28
+ \mathcal { L } = \mathbb { E } _ { { x } \sim \mathcal { D } _ { \mathrm { t r a i n } } } \left[ \mathbb { E } _ { p _ { \mathrm { a u g } } ( { x ^ { \prime } } \mid x ) } \left[ \mathrm { E L B O } _ { \Theta } ( { x ^ { \prime } } ) \right] \right]
29
+ $$
30
+
31
+ ![](images/90ae5c6fbb210892ebec22ee07f3be2145a770bfcb4915059fb3499853f29470.jpg)
32
+ Figure 1: Left: training distributions for the VAE. Note that $p _ { \mathrm { a u g } } ( { \pmb x } ^ { \prime } ) = \mathbb { E } _ { { \pmb x } \sim \mathcal { D } _ { \mathrm { t r a i n } } } [ p _ { \mathrm { a u g } } ( { \pmb x } ^ { \prime } \mid { \pmb x } ) ]$ only extrapolates from individual data points $x \sim \mathcal { D } _ { \mathrm { t r a i n } }$ and has density outside the support of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ (e.g., when flipping the digit $^ { 6 6 } 2 ^ { , 5 }$ ). By contrast, the pre-trained diffusion model $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ can interpolate between data ${ \mathbf { \boldsymbol { x } } } \sim \mathcal { D } _ { \mathrm { t r a i n } }$ . Right: corresponding VAE training objectives.
33
+
34
+ DMaaPx (proposed):
35
+
36
+ $$
37
+ \mathcal { L } = \mathbb { E } _ { x ^ { \prime } \sim p _ { \mathrm { D M } } ( x ^ { \prime } ) } \left[ \mathrm { E L B O } _ { \Theta } ( x ^ { \prime } ) \right]
38
+ $$
39
+
40
+ nice properties we want from VAEs, such as semantically meaningful representations. If diffusion models are indeed close estimates for $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , we should be able to alleviate the overfitting problem in VAEs using samples from pre-trained diffusion models. In this work, we investigate the effect of modifying the normal training procedure of VAEs by replacing the finite training set $\mathcal { D } _ { \mathrm { t r a i n } }$ with unlimited samples generated by a pre-trained diffusion model $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ . This idea can be considered as cross-model-class distillation, i.e., distilling from a diffusion model to a VAE.
41
+
42
+ Data augmentation is another method that can generate unlimited data, and it is used to reduce overfitting. However, selecting appropriate augmentations requires human expertise, and the augmented data might inaccurately represent $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . Hence, augmentation might lead to training a wrong probabilistic model, even though it can reduce overfitting. Figure 1, discussed further in Section 4, illustrates the relation between the underlying data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , the training set $\mathcal { D } _ { \mathrm { t r a i n } }$ , the augmented training data distribution $p _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } )$ , and the pre-trained diffusion model $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ .
43
+
44
+ We empirically show that the new method can indeed alleviate the overfitting issue in VAEs. Specifically, VAEs trained with the new method have better test set performance on estimating the density, on doing approximate inference, and on robustness against adversarial attacks. We also show that we do not need infinite data to gain such generalization performance. As an additional contribution, we publish all the samples we used to train our VAEs, so others do not need to spend compute to train and sample from diffusion models again.
45
+
46
+ # 2 PERFORMANCE GAPS IN VAES
47
+
48
+ VAEs model the data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ by assuming that its generative process first draws a latent variable $_ z$ from $p ( z )$ and then draws $_ { \textbf { \em x } }$ from $p _ { \theta } ( \pmb { x } | \pmb { z } )$ with model parameters $\theta$ . Given a training data distribution $p ( { \pmb x } )$ that approximates $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , naive maximum likelihood learning would maximize
49
+
50
+ $$
51
+ \operatorname* { m a x } _ { \theta } \mathbb { E } _ { \mathbf { x } \sim p ( \mathbf { x } ) } \big [ \log p _ { \theta } ( \mathbf { x } ) \big ] = \operatorname* { m a x } _ { \theta } \mathbb { E } _ { \mathbf { x } \sim p ( \mathbf { x } ) } \bigg [ \log \int p _ { \theta } ( \mathbf { x } \mid z ) p ( z ) \mathrm { d } z \bigg ] .
52
+ $$
53
+
54
+ Generally, maximizing this likelihood is difficult since we need to integrate over the latent variable $_ { z }$ . Hence, VAEs turn to an approximate inference method, called variational inference. This method introduces an approximate posterior $q _ { \phi } ( \pmb { z } | \pmb { x } )$ within a tractable variational family, and maximizes a lower bound of Eq. (5), known as the evidence lower bound (ELBO; Blei et al. (2017))
55
+
56
+ $$
57
+ \begin{array} { r } { \log p _ { \theta } ( \pmb { x } ) \geq \mathbb { E } _ { z \sim q _ { \phi } ( z \mid \pmb { x } ) } \big [ \log p _ { \theta } ( \pmb { x } \mid z ) + \log p ( z ) - \log q _ { \phi } ( z \mid \pmb { x } ) \big ] = : \mathrm { E L B O } _ { \Theta } ( \pmb { x } ) , } \end{array}
58
+ $$
59
+
60
+ where $\Theta = \{ \theta , \phi \}$ . In VAEs, the approximate posterior $q _ { \phi } ( \pmb { z } | \pmb { x } )$ is usually a Gaussian distribution parameterized by the output of a neural network $f _ { \phi } ( \pmb { x } )$ with weights $\phi$ . We call $p _ { \theta } ( \pmb { x } | \pmb { z } )$ the conditional likelihood to distinguish it from the likelihood $p _ { \theta } ( { \pmb x } )$ . The distribution of $p _ { \theta } ( \pmb { x } | \pmb { z } )$ is also parameterized by the output of a network $g _ { \boldsymbol { \theta } } ( z )$ with weights $\theta$ . We often refer to $f _ { \phi } ( \pmb { x } )$ as the inference network (or the encoder) and $g _ { \boldsymbol { \theta } } ( z )$ as the generative network (or the decoder).
61
+
62
+ Combining Eq. (5) and Eq. (6), we have the training objective of VAEs, i.e., to maximize
63
+
64
+ $$
65
+ \begin{array} { r } { \mathcal { L } = \mathbb { E } _ { { \pmb { x } } \sim p ( { \pmb x } ) } \left[ \mathrm { E L B O } _ { \Theta } ( { \pmb x } ) \right] . } \end{array}
66
+ $$
67
+
68
+ Ideally, we would like to use $p _ { \mathrm { d a t a } } ( \pmb { x } )$ for $p ( { \pmb x } )$ , but in reality we only have access to $\mathcal { D } _ { \mathrm { t r a i n } }$ . We now discuss three performance metrics for VAEs to evaluate the degree and the impact of overfitting. These metrics are defined in term of gaps, and will be used in the experiment section below.
69
+
70
+ Generalization gap. One signal for overfitting is that a model performs better on the training set $\mathcal { D } _ { \mathrm { t r a i n } }$ than on the test set $\mathcal { D } _ { \mathrm { t e s t } }$ , and the test set performance decreases over training epochs. For VAEs, we refer to the difference between training and test set ELBO as the generalization gap
71
+
72
+ $$
73
+ \begin{array} { r } { \mathcal { G } _ { \mathrm { g } } \ = \ \mathbb { E } _ { \pmb { x } \sim \mathcal { D } _ { \mathrm { t r a i n } } } \left[ \mathrm { E L B O } _ { \Theta } ( \pmb { x } ) \right] \ - \ \mathbb { E } _ { \pmb { x } \sim \mathcal { D } _ { \mathrm { t e s t } } } \left[ \mathrm { E L B O } _ { \Theta } ( \pmb { x } ) \right] . } \end{array}
74
+ $$
75
+
76
+ Since $\mathcal { D } _ { \mathrm { t r a i n } }$ and $\mathcal { D } _ { \mathrm { t e s t } }$ both consist of samples from the same distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , and training maximizes the ELBO on $\mathcal { D } _ { \mathrm { t r a i n } }$ , the ELBO on $\mathcal { D } _ { \mathrm { t r a i n } }$ is greater than or equal to the ELBO on $\mathcal { D } _ { \mathrm { t e s t } }$ . Therefore, $\mathcal { G } _ { \mathrm { g } } \geq 0$ . A smaller $\mathcal { G } _ { \mathrm { g } }$ corresponds to a better generalization performance of a VAE.
77
+
78
+ Remark (Test data entropy can also affect the ELBO value). Note that from Eqs. (6) and (7), we have
79
+
80
+ $$
81
+ \mathbb { E } _ { { \mathbf Z } \sim p ( { \mathbf x } ) } \left[ \mathrm { E L B O } _ { \Theta } ( { \mathbf x } ) \right] \le \mathbb { E } _ { { \mathbf x } \sim p ( { \mathbf x } ) } \left[ \log p _ { \theta } ( { \mathbf x } ) \right] = - H [ p ( { \mathbf x } ) , p _ { \theta } ( { \mathbf x } ) ] \le - H [ p ( { \mathbf x } ) ] ,
82
+ $$
83
+
84
+ where $H$ denotes the (cross) entropy. Therefore, the ELBO on $\mathcal { D } _ { \mathrm { t e s t } }$ can be higher than the ELBO on $\mathcal { D } _ { \mathrm { t r a i n } }$ , if $\mathcal { D } _ { \mathrm { t r a i n } }$ and $\mathcal { D } _ { \mathrm { t e s t } }$ are not drawn from the same distribution, and $\mathcal { D } _ { \mathrm { t e s t } }$ has a lower entropy than $\mathcal { D } _ { \mathrm { t r a i n } }$ . Indeed, this phenomenon has been observed in the out-of-distribution setting when testing on a low-entropy data set (Nalisnick et al., 2018). We will refer back to this in Section 5.6.
85
+
86
+ Amortization gap. VAEs use amortized inference, i.e., they set the variational parameters of $q _ { \phi } ( \pmb { z } | \pmb { x } )$ to the output of the encoder $f _ { \phi } ( \pmb { x } )$ for all given $_ { \textbf { \em x } }$ . At test time, we can further maximize the ELBO over the individual variational parameters for each $_ { \textbf { \em x } }$ , which is more expensive but typically results in a better variational distribution $q ^ { * } ( z \mid x )$ . We then study the amortization gap,
87
+
88
+ $$
89
+ \mathcal { G } _ { \mathrm { a } } = \mathbb { E } _ { \mathbf { x } \sim \mathcal { D } _ { \mathrm { t e s t } } } [ \mathrm { E L B O } _ { \theta } ^ { * } ( \mathbf { x } ) ] - \mathbb { E } _ { \mathbf { x } \sim \mathcal { D } _ { \mathrm { t e s t } } } [ \mathrm { E L B O } _ { \Theta } ( \mathbf { x } ) ]
90
+ $$
91
+
92
+ where $\begin{array} { r } { \operatorname { E L B O } _ { \theta } ^ { * } ( \pmb { x } ) = \operatorname { \mathbb { E } } _ { z \sim q ^ { * } ( z \mid \pmb { x } ) } \left[ \log p _ { \theta } ( \pmb { x } \mid z ) + \log p ( z ) - \log q ^ { * } ( z \mid \pmb { x } ) \right] . } \end{array}$ . As mentioned before, the encoder $f _ { \phi } ( \pmb { x } )$ is more susceptible to overfitting than the decoder in VAEs. When the encoder overfits, its inference ability might not generalize to test data, which results in lower ELBO value and larger amortization gap. The amortization gap $\mathcal { G } _ { \mathrm { a } }$ is non-negative and a smaller $\mathcal { G } _ { \mathrm { a } }$ corresponds to better generalization performance of the inference model (or encoder).
93
+
94
+ Robustness gap. An overfitted encoder $f _ { \phi } ( \pmb { x } )$ often learns a less smooth function such that a small change in the input space can lead to a huge difference in the output space. Hence, it is easier to construct an adversarial sample ${ \pmb x } ^ { \mathrm { a } } = { \pmb x } ^ { \mathrm { r } } + { \pmb \epsilon }$ (s.t. $\| \epsilon \| \le \delta )$ from a real data point ${ \pmb x } ^ { \mathrm { r } } \in \mathcal { D } _ { \mathrm { t e s t } }$ . This is done by maximizing the symmetrized KL-divergence (Kullback & Leibler, 1951) between $q _ { \phi } ( z | \boldsymbol { x } ^ { \mathrm { r } } )$ and $q _ { \phi } ( z | x ^ { \mathrm { a } } )$ within a given attack radius $\delta$ (Kuzina et al., 2022). A successful attack means that the attack reconstruction $\tilde { \pmb { x } } ^ { \mathrm { a } } = g _ { \theta } ( z ^ { \mathrm { a } } )$ , $z ^ { \mathrm { a } } \sim q _ { \phi } ( z | x ^ { \mathrm { a } } )$ , is very different from the real data reconstruction $\tilde { \pmb { x } } ^ { \mathrm { r } } = g _ { \theta } ( z ^ { \mathrm { r } } )$ , ${ \boldsymbol { z } } ^ { \mathrm { { r } } } \sim q _ { \phi } ( { \boldsymbol { z } } | { \boldsymbol { x } } ^ { \mathrm { { r } } } )$ , even though the inputs $\pmb { x } ^ { \mathrm { a } }$ and ${ \pmb x } ^ { \mathrm { r } }$ are similar. Using the image similarity metric MS-SSIM (Wang et al., 2003), we define the robustness gap as
95
+
96
+ $$
97
+ \mathcal { G } _ { \mathrm { r } } = \mathbb { E } _ { { \mathbf { x } } ^ { \mathrm { a } } \sim p ( { \mathbf { x } } ^ { \mathrm { a } } \mid { \mathbf { x } } ^ { \mathrm { r } } ) } \mathbb { E } _ { { \mathbf { x } } ^ { \mathrm { r } } \sim \mathcal { D } _ { \mathrm { t e s t } } } \big [ \mathbf { M S } \mathrm { - S S I M } \left[ { \mathbf { x } } ^ { \mathrm { r } } , { \mathbf { x } } ^ { \mathrm { a } } \right] - \mathbf { M S } \mathrm { - S S I M } \left[ { \tilde { \mathbf { x } } } ^ { \mathrm { r } } , { \tilde { \mathbf { x } } } ^ { \mathrm { a } } \right] \big ] .
98
+ $$
99
+
100
+ Note that a higher MS-SSIM corresponds to a more similar data pair. Hence, MS-SSIM $[ { \pmb x } ^ { \mathrm { r } } , { \pmb x } ^ { \mathrm { a } } ]$ is greater than or equal to $\mathbf { M S - S S I M } [ \tilde { { \boldsymbol { x } } } ^ { \mathrm { r } } , \tilde { { \boldsymbol { x } } } ^ { \mathrm { a } } ]$ , and the gap $\mathcal { G } _ { \mathrm { r } }$ is a non-negative value. A more robust VAE has a higher $\mathbf { M S - S S I M } [ \tilde { { \pmb x } } ^ { \mathrm { r } } , \tilde { { \pmb x } } ^ { \mathrm { a } } ]$ than the less robust one. Therefore, a smaller $\mathcal { G } _ { \mathrm { r } }$ corresponds to a more robust VAE. For more details on the attack see Appendix A.
101
+
102
+ # 3 RELATED WORK
103
+
104
+ We group related work into using diffusion models as data sources and attempts to closing the three performance gaps. Work related to data augmentation and distillation is discussed in Section 4.
105
+
106
+ Use samples from pre-trained diffusion models. There are many recent attempts to solve various tasks with data generated by diffusion models. Azizi et al. (2023) fine-tuned a text-to-image diffusion model on ImageNet, generated state-of-the-art samples with class labels, and trained a classifier on the samples. Their result shows that the classifier trained on generated data does not outperform the classifier trained on real data. In the adversarial training setting, using generated data by diffusion models shows significant improvements on classification robustness (Croce et al., 2021; Wang et al., 2023). Tian et al. (2023) found that the visual representations learned from samples generated by text-to-image diffusion models outperform the representations learned by SimCLR and CLIP. Alemohammad et al. (2023) trained new diffusion models with samples from previously trained diffusion models, and they found that their sample quality and diversity progressively decrease. In this work, we find that using diffusion models as data sources improves the performance of VAEs.
107
+
108
+ Improve generalization, amortized inference, and robustness in VAEs. Cremer et al. (2018) study the amortization gap in VAEs, and they notice that overfitting in the encoder is one of the contributing factors of the gap, and it hurts the generalization of VAEs. Many subsequent works try to close the amortization gap by introducing new inference techniques or procedures (Marino et al., 2018; Shu et al., 2018; Zhao et al., 2019). To close the generalization gap and reduce encoder overfitting, Zhang et al. (2022) propose to freeze the decoder after a certain amount of training steps, but further train the encoder by using reconstruction samples as part of the training data. As for adversarial robustness in VAEs, Kuzina et al. (2022) propose to defend a pre-trained VAE by running MCMC during inference to move $_ z$ towards “safer” regions in the latent space. Our proposed method can be used on top of these existing methods, since it does not require changing the original inference procedure. It also takes into account all three gaps at the same time.
109
+
110
+ # 4 DIFFUSION MODEL AS A $p _ { \mathrm { d a t a } } ( \pmb { x } )$
111
+
112
+ In this section, we introduce a new method for reducing overfitting in VAEs (Section 4.1). We also discuss how the new method is fundamentally different from naive data augmentation (Section 4.2), and how it can be understood from a cross-model-class distillation perspective (Section 4.3).
113
+
114
+ # 4.1 PROPOSED METHOD
115
+
116
+ The ideal training objective for VAEs is to maximize $\mathbb { E } _ { { \pmb x } \sim p _ { \mathrm { d a t a } } ( { \pmb x } ) } \left[ \mathrm { E L B O } _ { \Theta } ( { \pmb x } ) \right]$ (see Eq. (1) in Figure 1). However, in practice, we only have $\mathcal { D } _ { \mathrm { t r a i n } }$ as a finite approximation of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . Hence, we normally maximize $\mathbb { E } _ { \pmb { x } \sim \mathcal { D } _ { \mathrm { t r a i n } } }$ $[ \mathrm { E L B O } _ { \Theta } ( { \pmb x } ) ]$ (see Eq. (2)) to train a VAE, which can lead to overfitting. Rather than focusing on model architectures or training techniques as in prior works, we aim to mitigate overfitting by seeking a better approximation for $p _ { \mathrm { d a t a } } ( \pmb { x } )$ than $\mathcal { D } _ { \mathrm { t r a i n } }$ . Here, we make two assumptions: first, the training data distribution should fulfill two criteria; it should be
117
+
118
+ (1) a continuous distribution, i.e., we can sample unlimited data to avoid overfitting; and (2) an accurate approximation of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , i.e., we are indeed modeling $p _ { \mathrm { d a t a } } ( \pmb { x } )$ rather than some different distribution (in practice, it needs to be an accurate model of $\mathcal { D } _ { \mathrm { t r a i n } } ,$ ).
119
+
120
+ Our second assumption is that a good diffusion model1 that has been pre-trained on $\mathcal { D } _ { \mathrm { t r a i n } }$ satisfies these two criteria: (1) we can generate unlimited samples from it, and (2) its training objective is designed to model $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , allowing us to generate samples with state-of-the-art quality across various data types. Therefore, we investigate training VAEs using a pre-trained diffusion model $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ instead of $\mathcal { D } _ { \mathrm { t r a i n } }$ as an approximation of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , i.e., to maximize $\mathbb { E } _ { { \pmb x } \sim p _ { \mathrm { D M } } ( { \pmb x } ^ { \prime } ) } \left[ \mathrm { E L B O } _ { \Theta } ( { \pmb x } ^ { \prime } ) \right]$ (see Eq. (4)). We denote this method DMaaPx, short for “Diffusion Model as a $p _ { \mathrm { d a t a } } ( { \pmb x } ) ^ { \prime }$ .
121
+
122
+ Figure 1 illustrates the intuition behind this idea. The blue dots represent the finite data set $\mathcal { D } _ { \mathrm { t r a i n } }$ . They are i.i.d. samples from the underlying data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ (shown by the dark-edged region). The green regions represent the distribution learned by $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ . We use areas, not dots, to highlight that $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ models a continuous distribution that can generate infinitely many samples.
123
+
124
+ Note that diffusion models for data types other than images are less explored and might not accurately approximate $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . Hence, diffusion models might not satisfy criterion (2). Moreover, due to the data processing inequality, information on $p _ { \mathrm { d a t a } } ( \pmb { x } )$ captured by a diffusion model that was trained on $\mathcal { D } _ { \mathrm { t r a i n } }$ cannot exceed the information contained in $\mathcal { D } _ { \mathrm { t r a i n } }$ . In reality, state-of-the-art diffusion models are not able to fit $\mathcal { D } _ { \mathrm { t r a i n } }$ perfectly. Indeed, many recent works observe that in both image and text settings, training generative models from generated data leads to worse performance overall (Alemohammad et al., 2023; Shumailov et al., 2023). Hence, the continuity we gain by replacing $\mathcal { D } _ { \mathrm { t r a i n } }$ with $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ is not for free, we lose a small amount of information about $\mathcal { D } _ { \mathrm { t r a i n } }$ .
125
+
126
+ # 4.2 DIFFERENCE BETWEEN DATA AUGMENTATION AND DMAAPX
127
+
128
+ Data augmentation2 pursues a similar goal as the proposed DMaaPx as both approaches aim to increase the quantity and diversity of training data. The primary distinction between them is in their accuracy in approximating $p _ { \mathrm { d a t a } } ( \pmb { x } )$ , as shown in Table 1. This can be attributed primarily to two key factors. Firstly, typical data augmentation techniques generate new training points by conditioning on a
129
+
130
+ Table 1: Training distributions for VAEs (see Figure 1), and whether they are (1) continuous and (2) an accurate approximation of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ .
131
+
132
+ $$
133
+ \begin{array} { r l } & { \frac { \mathrm { a p p r o x . ~ b y } } { ( 1 ) \mathrm { c o n t i n u o u s } } \frac { \mathcal { D } _ { \mathrm { t r a i n } } \mathrm { \quad } p _ { \mathrm { a u g } } ( { \pmb x } ^ { \prime } ) \mathrm { \quad } p _ { \mathrm { D M } } ( { \pmb x } ^ { \prime } ) } { \pmb \chi } } \\ & { ( 2 ) \mathrm { a c c u r a t e } } \end{array}
134
+ $$
135
+
136
+ single original data point. Thus, $p _ { \mathrm { a u g } } ( \pmb x ^ { \prime } ) = \mathbb { E } _ { \pmb { x } \sim \mathcal { D } _ { \mathrm { t r a i n } } } \bigl [ p _ { \mathrm { a u g } } ( \pmb x ^ { \prime } | \pmb x ) \bigr ]$ where $p _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } | \pmb { x } )$ generates a training point $\mathbf { x } ^ { \prime }$ by applying one or more random transformations (e.g., padding, cropping, flipping (He et al., 2016), translation or even learned rotation and cutout (Cubuk et al., 2019)) to a single original data point $_ { \textbf { \em x } }$ . By contrast, in the proposed DMaaPx, each training data point $\pmb { x } ^ { \prime } \sim p _ { \mathrm { D M } } ( \bar { \pmb { x } } ^ { \prime } )$ is drawn from a diffusion model that was trained on the entire dataset $\mathcal { D } _ { \mathrm { t r a i n } }$ . As a consequence, each training data point in DMaaPx is effectively conditioned on the full training set $\mathcal { D } _ { \mathrm { t r a i n } }$ .
137
+
138
+ Secondly, the random transformations used for $p _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } \mid \pmb { x } )$ in traditional data augmentation are drawn from a manually curated catalog. This catalog is heavily based on prior assumptions regarding invariances in the data type under consideration, which can introduce bias. In practice, one has to make assumptions and decide whether the (unknown) true data distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ is invariant under the considered transformations. For instance, with images, we assume invariance to minor translations, hue shifts, and zooms. This may result in problems of (i) not modeling the full extend of the distribution or (ii) modeling density outside the true data distribution. Figure 1 depicts both: problem (i) corresponds to “empty” space between areas of $p _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } )$ ; problem (ii) corresponds to density of $\bar { p } _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } )$ outside of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ . The proposed DMaaPx eliminates these explicit assumptions, which makes the method more resilient against human bias (but less interpretable).
139
+
140
+ In summary, while traditional data augmentation techniques introduce diversity based on invariances about the data generative process, the proposed DMaaPx uses an expressive generative model to extrapolate from the empirical diversity of the data.
141
+
142
+ # 4.3 A CROSS-MODEL-CLASS DISTILLATION PERSPECTIVE
143
+
144
+ The proposed DMaaPx can also be viewed from a distillation perspective (Hinton et al., 2015). Distillation describes the process of transferring knowledge from a large model to a small one. In practice, distillation is often used because a smaller model is less expensive to be deployed in production. Here we consider a more subtle usage of distillation, i.e., transferring knowledge between models designed with different modeling assumptions or structures. We refer to this as cross-modelclass distillation, and the conventional usage of distillation as within-model-class distillation. There are models that have been designed with useful structures which cannot be fully exploited if trained naively on $\mathcal { D } _ { \mathrm { t r a i n } }$ . Cross-model-class distillation creates auxiliary training data that helps us train such models to achieve the desired performance. For instance, in the diffusion model literature, numerous studies attempt to distill the multi-step diffusion process into a single-step generative model (Salimans & Ho, 2021; Luhman & Luhman, 2021; Liu et al., 2023; Song et al., 2023). While both types of distillation seek to transfer knowledge from a source to a target model, cross-model-class distillation emphasizes more on enhancing functionalities that are unique to the target model rather than mirroring the capabilities shared with the source model.
145
+
146
+ Our proposed DMaaPx belongs to cross-model-class distillation, i.e., it distills diffusion models to VAEs. The goal of DMaaPx is not to rival diffusion models in sample quality, but rather to improve the desirable functionalities of VAEs such as representation learning. From this viewpoint, DMaaPx fundamentally differs from approaches that train VAEs on samples produced by VAEs, or diffusion models on outputs of diffusion models (Alemohammad et al., 2023; Shumailov et al., 2023). Such approaches can be categorized as within-model-class distillation.
147
+
148
+ # 5 EXPERIMENTS
149
+
150
+ In this section, we introduce the experimental setup and evaluate the three performance gaps (see Section 2) of the proposed method. The exact gap values are provided in Appendix B. We further investigate whether we need infinite training data in the proposed method.
151
+
152
+ # 5.1 EXPERIMENTAL SETUP
153
+
154
+ Training data. We evaluate our method on three popular datasets: MNIST (LeCun et al., 1998), FashionMNIST (Xiao et al., 2017), and CIFAR-10 (Krizhevsky et al., 2009). As a preparation, we train a diffusion model $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ which will be used to generate training data for VAEs on each training set $\mathcal { D } _ { \mathrm { t r a i n } }$ . We use the implementation of diffusion models by Karras et al. (2022). Further details and samples from the three pre-trained diffusion models can be found in Appendix C.
155
+
156
+ VAE architectures. We assume fixed standard Gaussian priors $p ( z ) = \mathcal { N } ( \mathbf { 0 } , \mathbf { I } )$ for all datasets. For the conditional likelihood $p _ { \theta } ( \pmb { x } | \pmb { z } )$ , we use a Bernoulli distribution for binarized MNIST, a diagonal Gaussian distribution with a fixed variance for grayscale FashionMNIST, and a discretized mixture of logistics (MoL; Salimans et al. (2017)) for CIFAR-10. For the inference model $q _ { \phi } ( { \boldsymbol { z } } \mid { \boldsymbol { x } } )$ , we use diagonal Gaussian distributions with means and variances output from the inference network for all datasets. For more details on network architectures and hyperparameters see Appendix D.
157
+
158
+ Baselines. We compare VAEs trained with our proposed DMaaPx against three baseline models trained on: (i) repetitions of $\mathcal { D } _ { \mathrm { t r a i n } }$ (“Normal Training”); (ii) carefully tuned augmentation for $\mathcal { D } _ { \mathrm { t r a i n } }$ (“Aug.Tuned”); and (iii) plausible augmentation for images in general (“Aug.Naive”). Note that “Aug.Naive” is not tuned to a given $\mathcal { D } _ { \mathrm { t r a i n } }$ and can result in out-of-distribution data, e.g. a horizontally flipped digit “2” for MNIST. This mimics situations that arise in augmenting other data modalities, where the choice of transformation is not as obvious as for images. More details on the applied augmentation can be found in Appendix E. Generally, when documenting the training progress, the term “epoch” typically refers to one complete pass of $\mathcal { D } _ { \mathrm { t r a i n } }$ . For DMaaPx, this term is not applicable since it can sample unlimited data from $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ . Therefore, we measure training progress of DMaaPx in “effective epochs”. An “effective epoch” represents one pass through sampled training data of size $| \mathcal { D } _ { \mathrm { t r a i n } } |$ . We train all models for 1000 (effective) epochs.
159
+
160
+ # 5.2 GENERALIZATION GAP
161
+
162
+ Figure 2 shows both ELBOs evaluated on $\mathcal { D } _ { \mathrm { t r a i n } }$ (dashed) and $\mathcal { D } _ { \mathrm { t e s t } }$ (solid) for all three datasets. The difference between these two lines is the generalization gap $\mathcal { G } _ { \mathrm { g } }$ (Eq. (8)). We observe that our proposed DMaaPx (green) has the highest ELBO on $\mathcal { D } _ { \mathrm { t e s t } }$ , and the smallest generalization gap compared to both normal training and data augmentation. VAEs trained on the augmented data show less improvements on test ELBO and generalization gap than DMaaPx. This implies that VAEs trained with DMaaPx approximate the underlying distribution $p _ { \mathrm { d a t a } } ( \pmb { x } )$ better than those trained on $\mathcal { D } _ { \mathrm { t r a i n } }$ solely, or on augmented data. The small generalization gap of DMaaPx means that training ELBOs can be used as accurate predictions for final performance. Given that data from pre-trained diffusion models and augmentation is not an inherently more accurate representation of $p _ { \mathrm { d a t a } } ( \pmb { x } )$ than $\mathcal { D } _ { \mathrm { t r a i n } }$ , improvements in the test ELBOs suggest that overfitting in VAEs is more detrimental than using a somewhat distorted, but larger and more diverse, dataset.
163
+
164
+ # 5.3 AMORTIZATION GAP
165
+
166
+ The amortization gap, defined in Eq. (10), evaluates the encoder’s inference performance by comparing test ELBOs of the amortized variational parameters of $q _ { \phi } ( { \boldsymbol { z } } \mid { \boldsymbol { x } } )$ to those from individually optimized variational parameters of $q ^ { * } ( z \mid x )$ . Figure 3 shows test set ELBOs from $q _ { \phi } ( \pmb { z } | \pmb { x } )$ and $q ^ { * } ( z \mid x )$ for the three datasets with values reported every 100 effective epochs.
167
+
168
+ ![](images/c51bf71ed843433170465c35e361ea92ddec101e69bb857c5f94f0295ef02828.jpg)
169
+ Figure 2: Generalization performance: ELBOs of models trained with Eqs. (2)-(4), evaluated on $\mathcal { D } _ { \mathrm { t r a i n } }$ and $\mathcal { D } _ { \mathrm { t e s t } }$ . DMaaPx (proposed) consistently has the best test performance and smallest gap.
170
+
171
+ ![](images/d4b37024e43774cce699041aa4c4c964813f56b99f63ac30e2c0be3f1cb035d7.jpg)
172
+ Figure 3: Amortization gap: ELBOs with $q _ { \phi } ( \pmb { z } | \pmb { x } )$ from the inference network (solid) and with iteratively optimized $q ^ { * } ( z \mid x )$ (dashdot), evaluated on $\mathcal { D } _ { \mathrm { t e s t } }$ . Left and center: DMaaPx significantly reduces the amortization gap (Eq. (10)) compared to normal training and data augmentation. Among the dashdot lines, DMaaPx has the highest performance, indicating that it also helps learning a better decoder. Right: DMaaPx and augmentation are tied and outperform normal training.
173
+
174
+ The figure illustrates that the ELBOs for normal training using $q _ { \phi } ( \pmb { z } | \pmb { x } )$ (solid blue) decline with more training epochs, while those using $q ^ { * } ( z \mid x )$ (dashdot blue) remain stable or even increase. A decline in test set performance across epochs signals overfitting. By using $q ^ { * } ( z \mid x )$ and excluding the encoder, test performance stabilizes across epochs, indicating that the primary source of overfitting in VAEs is the encoder. This aligns with the findings of Cremer et al. (2018).
175
+
176
+ Figure 3 shows that DMaaPx outperforms normal training and data augmentation in both, the size of the amortization gap and the ELBO value for BinaryMNIST and FashionMNIST. Additionally, the increase of ELBOs with $q ^ { * } ( z \mid x )$ (dashdot) suggests that DMaaPx also improves the decoder. On CIFAR-10, DMaaPx and augmentation similarly outperform normal training.
177
+
178
+ # 5.4 ROBUSTNESS OF REPRESENTATIONS (ROBUSTNESS GAP)
179
+
180
+ The robustness gap, defined in Eq. (11), looks at similarities between real and the corresponding adversarial samples $( \mathbf { M S - S S I M } [ \pmb { x } ^ { r } , \pmb { x } ^ { a } ] )$ and between their respective reconstructions $( \mathbf { M } \bar { \mathbf { S } } \mathbf { - } \mathbf { S } \mathbf { S } \mathbf { I M } [ \tilde { \pmb { x } } ^ { r } , \tilde { \pmb { x } } ^ { a } ] )$ . A successful attack achieves low $\mathbf { M S - S S I M } [ \tilde { \pmb { x } } ^ { \bar { r } } , \tilde { \pmb { x } } ^ { a } ]$ despite high $\mathbf { M S - S S I M } [ \pmb { x } ^ { r } , \pmb { x } ^ { a } ]$ . See Appendix A for details on the attack construction in our experiments.
181
+
182
+ In Figure 4, we see that DMaaPx consistently matches or surpasses normal training across all three datasets. It also exceeds augmentation on BinaryMNIST and CIFAR-10. Meanwhile, VAEs trained with augmentation display inconsistent results: they outperform both DMaaPx and normal training on FashionMNIST, but fall behind on BinaryMNIST and CIFAR-10, demonstrating that augmentation is more difficult to tune than DMaaPx (training the diffusion model requires less manual effort).
183
+
184
+ ![](images/0ba831489a05cff1482269ba30d59259207d38b5cfbff24bc73cde0a7e5f3adf.jpg)
185
+ Figure 4: Adversarial robustness: similarities of reconstructions (solid) for similar but adversarially chosen inputs (see dashed line). DMaaPx is consistently either on par or better than normal training whereas augmentation is significantly worse than normal training for BinaryMNIST and CIFAR-10.
186
+
187
+ ![](images/9d6a670dfbf961c40f696fb4c0642ed588c72e2763a5879bbe5c29bb362bc37f.jpg)
188
+ Figure 5: Generalization performance as a function of the amount $k$ of training data sampled from the diffusion model. Horizontal blue lines show baseline performance (VAE trained directly on $\mathcal { D } _ { \mathrm { t r a i n } } ,$ ). All VAEs were trained for 1000 effective epochs. $k \approx 1 0$ seems to suffice.
189
+
190
+ ![](images/3093079f65457a5b9c51560e63303561da2f0ad88386cc38a488b2eeb0331d7d.jpg)
191
+ Figure 6: Generalization performance for FashionMINST with MoL likelihood. We observe similar behavior to center panel in Figure 2, which uses a Gaussian likelihood.
192
+
193
+ # 5.5 IS THE “UNLIMITED DATA PLAN” A RIPOFF?
194
+
195
+ With the pre-trained diffusion model in DMaaPx, we can train VAEs with unlimited samples from $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ , enhancing performance as demonstrated above. While generating a large amount of samples from diffusion models is feasible, it still requires substantial computation. Therefore, we further explore: “Do we really need infinite number of samples?” The answer, reassuringly, is “No”.
196
+
197
+ Figure 5 shows the generalization performance of DMaaPx on BinaryMNIST and CIFAR-10 where the training data for VAEs is restricted to $k \times | \mathcal { D } _ { \mathrm { t r a i n } } |$ , with $k$ ranging from 1 to 1000. After $k$ effective training epochs, samples start repeating. All models are trained on 1000 effective epochs. Horizontal blue lines represent the generalization gap of normal VAE training (on $\mathcal { D } _ { \mathrm { t r a i n } }$ and $k = 1$ ) at epoch 1000 from Figure 2. For $k = 1$ , DMaaPx slightly underperforms on BinaryMNIST but matches normal training on CIFAR-10. The ELBO plateaus for $k \geq 1 0$ , indicating samples roughly 10 times the size of $\mathcal { D } _ { \mathrm { t r a i n } }$ offer similar generalization to samples 1000 times larger.
198
+
199
+ # 5.6 ABLATION AND FURTHER DETAILS
200
+
201
+ In this section we present ablations on different conditional likelihoods, compare the two augmentation strategies considered, and discuss the difference between training ELBO and ELBO on $\mathcal { D } _ { \mathrm { t r a i n } }$
202
+
203
+ ![](images/5ffeb50429f9b43dae741df19918112ada7fb5637d3782a9bd9502bc34670604.jpg)
204
+ Figure 7: ELBO evaluted on the distribution that is actually used for training (dotted, see Eqs. (2)-(4)). For augmentations, the test ELBO (solid) is higher than the training ELBO (dotted) in the left two panels, which is an artifact of different entropies of the distributions, see Remark.
205
+
206
+ Different conditional likelihoods. VAEs’ modeling assumptions for the conditional likelihood $p _ { \theta } ( \pmb { x } | \pmb { z } )$ often differ based on data or use case. While a Gaussian likelihood is used for applications that focus on low reconstruction error (e.g., lossy data compression), an MoL likelihood is used if the density of the data matters (e.g., generative modeling or lossless data compression). Our experiments in Sections 5.2-5.4 cover three likelihoods: Bernoulli for BinaryMNIST, Gaussian for FashionMNIST, and MoL for CIFAR-10. Figure 6 also evaluates MoL for FashionMNIST, and we observe similar behaviour as in its Gaussian counterpart in Figure 2 (center). In summary, DMaaPx is less prone to overfitting than normal training and augmentation, for all investigated likelihoods.
207
+
208
+ Tuned and naive augmentation. To fairly assess DMaaPx against augmentation, we design two sets of augmentation: Aug.Tuned (tailored to each $\mathcal { D } _ { \mathrm { t r a i n } } .$ ) and Aug.Naive (general for images). They perform similarly overall in Figures 2-4. However, Aug.Naive outperforms Aug.Tuned in generalization on BinaryMNIST and FashionMNIST, and in robustness across all datasets. This is surprising as naive augmentation might produce out-of-distribution data, like a horizontally flipped digit “2”, potentially impairing performance. Thus, designing augmentation can be labor-intensive.
209
+
210
+ Training ELBO vs. ELBO on $\mathcal { D } _ { \mathrm { t r a i n } }$ . Figure 7 shows the ELBOs analogous to Figure 2, but the dotted lines plot the ELBO on the actual training distribution (e.g., on samples from $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ for DMaaPx). The point of this plot is to warn that comparisons between ELBOs under such different distributions are not meaningful, and should not be used to calculate the generalization gap. For example, note that the plot would suggest a negative generalization gap for data augmentation (purple) on BinaryMNIST. This is consistent with the remark on page 3: since the ELBO is bounded by the negative entropy of the distributions on which it is evaluated, evaluating it on two different distributions with different entropies exhibits differences unrelated to the generalization gap.
211
+
212
+ # 6 CONCLUSION
213
+
214
+ We investigate how overfitting of VAEs can be addressed by training them on samples from a diffusion model that was pre-trained on the training dataset. Our assumption is that, unlike in supervised learning, VAE training requires training data that accurately matches the data generative process. We therefore contrasted our approach to traditional data augmentation methods, which might not accurately model the data generative process. Our results show significant reduction in generalization gaps, improved test ELBOs, and enhanced adversarial robustness. Future work should challenge the above assumption and investigate whether one can further improve VAE performance by designing a generative model that specifically for cross-model-class distillation.
215
+
216
+ In a broader sense, our work explores ways of increasing the quantity and diversity of training data in situations where one cares about the underlying data distribution. Future work should also expand this research beyond VAEs, in particular as prior work found that recursive distillation within a diffusion model hurts performance (Alemohammad et al., 2023). Additional work should explore applying our method to other data types, such as structured data like molecules or time series.
217
+
218
+ Reproducibility Statement. All code necessary to reproduce the results in this paper is provided in the supplementary materials. We will also publish the samples generated by our pre-trained diffusion models for the DMaaPx experiments after the reviewing process.
219
+
220
+ REFERENCES Sina Alemohammad, Josue Casco-Rodriguez, Lorenzo Luzi, Ahmed Imtiaz Humayun, Hossein Babaei, Daniel LeJeune, Ali Siahkoohi, and Richard G Baraniuk. Self-consuming generative models go mad. arXiv preprint arXiv:2307.01850, 2023. 1, 4, 5, 6, 9 Shekoofeh Azizi, Simon Kornblith, Chitwan Saharia, Mohammad Norouzi, and David J Fleet. Synthetic data from diffusion models improves imagenet classification. arXiv preprint arXiv:2304.08466, 2023. 4 Johannes Balle, Valero Laparra, and Eero P Simoncelli. End-to-end optimized image compression. ´ In International Conference on Learning Representations, 2017. 16 David M Blei, Alp Kucukelbir, and Jon D McAuliffe. Variational inference: A review for statisticians. Journal of the American Statistical Association, 2017. 2 Bernhard E Boser, Isabelle M Guyon, and Vladimir N Vapnik. A training algorithm for optimal margin classifiers. In Fifth Annual Workshop on Computational Learning Theory, 1992. 16 Chris Cremer, Xuechen Li, and David Duvenaud. Inference suboptimality in variational autoencoders. In International Conference on Machine Learning, 2018. 1, 4, 7 Francesco Croce, Maksym Andriushchenko, Vikash Sehwag, Edoardo Debenedetti, Nicolas Flammarion, Mung Chiang, Prateek Mittal, and Matthias Hein. Robustbench: a standardized adversarial robustness benchmark. In Neural Information Processing Systems Datasets and Benchmarks Track (Round 2), 2021. 4 Ekin D Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, and Quoc V Le. Autoaugment: Learning augmentation strategies from data. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2019. 5 Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition,
221
+ 2016. 5, 14 Martin Heusel, Hubert Ramsauer, Thomas Unterthiner, Bernhard Nessler, and Sepp Hochreiter. Gans trained by a two time-scale update rule converge to a local nash equilibrium. In Advances in Neural Information Processing Systems, 2017. 16 Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. 5 Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffusion probabilistic models. In Advances in Neural Information Processing Systems, 2020. 1 Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. In International Conference on Machine Learning, 2015. 14 Tero Karras, Miika Aittala, Janne Hellsten, Samuli Laine, Jaakko Lehtinen, and Timo Aila. Training generative adversarial networks with limited data. In Advances in Neural Information Processing Systems, 2020. 15 Tero Karras, Miika Aittala, Timo Aila, and Samuli Laine. Elucidating the design space of diffusionbased generative models. In Advances in Neural Information Processing Systems, 2022. 6, 13,
222
+ 14 Diederik P Kingma and Max Welling. Auto-encoding variational bayes. In International Conference on Learning Representations, 2014. 1
223
+ Alex Krizhevsky, Geoffrey Hinton, et al. Learning multiple layers of features from tiny images. 2009. 6, 14
224
+ Solomon Kullback and Richard A Leibler. On information and sufficiency. The Annals of Mathematical Statistics, 22, 1951. 3, 13
225
+ Anna Kuzina, Max Welling, and Jakub Tomczak. Alleviating adversarial attacks on variational autoencoders with mcmc. In Advances in Neural Information Processing Systems, 2022. 1, 3, 4, 13
226
+ Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner. Gradient-based learning applied to ´ document recognition. In Proceedings of the IEEE, 1998. 6, 14
227
+ Xingchao Liu, Chengyue Gong, and qiang liu. Flow straight and fast: Learning to generate and transfer data with rectified flow. In International Conference on Learning Representations, 2023. 5
228
+ Eric Luhman and Troy Luhman. Knowledge distillation in iterative generative models for improved sampling speed. arXiv preprint arXiv:2101.02388, 2021. 5
229
+ Joe Marino, Yisong Yue, and Stephan Mandt. Iterative amortized inference. In International Conference on Machine Learning, 2018. 4
230
+ Eric Nalisnick, Akihiro Matsukawa, Yee Whye Teh, Dilan Gorur, and Balaji Lakshminarayanan. Do deep generative models know what they don’t know? In International Conference on Learning Representations, 2018. 3
231
+ Danilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In International Conference on Machine Learning, 2014. 1
232
+ Tim Salimans and Jonathan Ho. Progressive distillation for fast sampling of diffusion models. In International Conference on Learning Representations, 2021. 5
233
+ Tim Salimans, Andrej Karpathy, Xi Chen, and Diederik P. Kingma. PixelCNN $^ { + + }$ : Improving the pixelCNN with discretized logistic mixture likelihood and other modifications. In International Conference on Learning Representations, 2017. 6, 14
234
+ Tim Salimans, Han Zhang, Alec Radford, and Dimitris Metaxas. Improving gans using optimal transport. In International Conference on Learning Representations, 2018. 16
235
+ Rui Shu, Hung H Bui, Shengjia Zhao, Mykel J Kochenderfer, and Stefano Ermon. Amortized inference regularization. In Advances in Neural Information Processing Systems, 2018. 1, 4
236
+ Ilia Shumailov, Zakhar Shumaylov, Yiren Zhao, Yarin Gal, Nicolas Papernot, and Ross Anderson. The curse of recursion: Training on generated data makes models forget. arXiv preprint arxiv:2305.17493, 2023. 1, 5, 6
237
+ Jascha Sohl-Dickstein, Eric Weiss, Niru Maheswaranathan, and Surya Ganguli. Deep unsupervised learning using nonequilibrium thermodynamics. In International Conference on Machine Learning, 2015. 1
238
+ Yang Song, Jascha Sohl-Dickstein, Diederik P Kingma, Abhishek Kumar, Stefano Ermon, and Ben Poole. Score-based generative modeling through stochastic differential equations. In International Conference on Learning Representations, 2021. 1, 14
239
+ Yang Song, Prafulla Dhariwal, Mark Chen, and Ilya Sutskever. Consistency models. In International Conference on Machine Learning, 2023. 5
240
+ Lucas Theis, van den Oord Aaron, and Matthias Bethge. A note on the evaluation of generative ¨ models. In International Conference on Learning Representations, 2016. 16
241
+ Yonglong Tian, Lijie Fan, Phillip Isola, Huiwen Chang, and Dilip Krishnan. Stablerep: Synthetic images from text-to-image models make strong visual representation learners. arXiv preprint arXiv:2306.00984, 2023. 4
242
+ Aaron van den Oord, Oriol Vinyals, et al. Neural discrete representation learning. In Advances in Neural Information Processing Systems, 2017. 1
243
+ Zekai Wang, Tianyu Pang, Chao Du, Min Lin, Weiwei Liu, and Shuicheng Yan. Better diffusion models further improve adversarial training. In International Conference on Machine Learning, 2023. 4
244
+ Zhou Wang, Eero P Simoncelli, and Alan C Bovik. Multiscale structural similarity for image quality assessment. In The Thrity-Seventh Asilomar Conference on Signals, Systems & Computers, 2003, 2003. 3
245
+ Yuhuai Wu, Yuri Burda, Ruslan Salakhutdinov, and Roger Grosse. On the quantitative analysis of decoder-based generative models. In International Conference on Learning Representations, 2017. 1
246
+ Han Xiao, Kashif Rasul, and Roland Vollgraf. Fashion-mnist: a novel image dataset for benchmarking machine learning algorithms. arXiv preprint arXiv:1708.07747, 2017. 6, 14
247
+ Tim Z. Xiao and Robert Bamler. Trading information between latents in hierarchical variational autoencoders. In International Conference on Learning Representations, 2023. 16
248
+ Suorong Yang, Weikang Xiao, Mengcheng Zhang, Suhan Guo, Jian Zhao, and Furao Shen. Image data augmentation for deep learning: A survey. arXiv preprint arXiv:2204.08610, 2022. 5
249
+ Yibo Yang, Stephan Mandt, Lucas Theis, et al. An introduction to neural data compression. Foundations and Trends® in Computer Graphics and Vision, 2023. 1
250
+ Mingtian Zhang, Peter Hayes, and David Barber. Generalization gap in amortized inference. In Advances in Neural Information Processing Systems, 2022. 4
251
+ Shengjia Zhao, Jiaming Song, and Stefano Ermon. Infovae: Balancing learning and inference in variational autoencoders. In Proceedings of the AAAI Conference on Artificial Intelligence, 2019. 4
252
+
253
+ # A DETAILS ON ADVERSARIAL ATTACK
254
+
255
+ We follow Kuzina et al. (2022) and construct an unsupervised encoder attack that optimizes the pertubation $\epsilon$ to incur the largest possible change in $q _ { \phi } ( \bar { \cdot } | \pmb { x } )$ ,
256
+
257
+ $$
258
+ \epsilon = \underset { | | \epsilon | | _ { \infty } \le \delta } { \arg \operatorname* { m a x } } \mathrm { \mathrm { ~ S K L } } \left[ q _ { \phi } ( \cdot | \boldsymbol { x } ^ { \mathrm { r } } + \epsilon ) \mathrm { ~ } | | \mathrm { ~ } q _ { \phi } ( \cdot | \boldsymbol { x } ^ { \mathrm { r } } ) \right]
259
+ $$
260
+
261
+ where SKL denotes the symmetric Kullback-Leibler divergence (Kullback & Leibler, 1951). We optimize $\epsilon$ for $n ^ { \epsilon }$ iterations with projected gradient descent utilizing a learning rate of $\eta$ . The robustness gap (see Section 2) is computed over $n ^ { \mathrm { r } }$ real images and $n ^ { \mathrm { a } }$ random seeds. The exact hyperparameters can be found in Table 2.
262
+
263
+ Table 2: Hyperparameters for unsupervised encoder attack.
264
+
265
+ <table><tr><td colspan="2">BinaryMNIST</td><td>FashionMNIST</td><td>CIFAR-10</td></tr><tr><td>nr</td><td>50</td><td>50</td><td>20</td></tr><tr><td>na</td><td>10</td><td>10</td><td>10</td></tr><tr><td>ne</td><td>50</td><td>50</td><td>100</td></tr><tr><td></td><td>1.0</td><td>1.0</td><td>1.0</td></tr><tr><td>8</td><td>0.1</td><td>0.1</td><td>0.05</td></tr></table>
266
+
267
+ # B QUANTITATIVE RESULTS ON PERFORMANCE GAPS
268
+
269
+ Table 3 assigns quantitative values to the visual evidence in Figure 2 (generalization gap), Figure 3 (amortization gap), and Figure 4 (adversarial robustness gap).
270
+
271
+ Table 3: Quantitative values of the performance gaps visualized in the main text (generalization gap: Figure 2; amortization gap: Figure 3; robustness gap: Figure 4). Bold numbers indicate the smallest gap within a dataset.
272
+
273
+ <table><tr><td colspan="2"></td><td>generalization gap (9g,Eq.(8))</td><td>amorization gap (9a,Eq. (10))</td><td>robustness gap (9r, Eq. (11))</td></tr><tr><td rowspan="4">Binary MNIST</td><td>Normal Training</td><td>25.76</td><td>20.32</td><td>0.49</td></tr><tr><td> DMaaPx (ours)</td><td>0.78</td><td>7.01</td><td>0.50</td></tr><tr><td> Aug.Tuned</td><td>8.16</td><td>9.34</td><td>0.79</td></tr><tr><td>Aug.Naive</td><td>6.38</td><td>8.16</td><td>0.74</td></tr><tr><td rowspan="4">Fashion MNIST</td><td>Normal Training</td><td>1234.50</td><td>1135.89</td><td>0.39</td></tr><tr><td> DMaaPx (ours)</td><td>136.57</td><td> 593.39</td><td>0.31</td></tr><tr><td> Aug.Tuned</td><td>614.93</td><td>815.52</td><td>0.21</td></tr><tr><td>Aug.Naive</td><td>500.33</td><td>729.83</td><td>0.11</td></tr><tr><td rowspan="4">CIFAR-10</td><td>Normal Training</td><td>841.54</td><td>835.86</td><td>0.41</td></tr><tr><td> DMaaPx (ours)</td><td> 5.44</td><td>288.82</td><td>0.30</td></tr><tr><td> Aug.Tuned</td><td>94.28</td><td>328.08</td><td>0.35</td></tr><tr><td>Aug.Naive</td><td>228.05</td><td>390.25</td><td>0.35</td></tr></table>
274
+
275
+ # C DIFFUSION MODEL
276
+
277
+ We follow the setup of Karras et al. (2022) for the design and training of our diffusion model.
278
+ However, we do not use the proposed augmentation pipeline during training.
279
+
280
+ We train the diffusion model on 200, 000, 000 images that are sampled randomly (with replacement) from the training dataset. Each model is trained on 8 NVIDIA A100 40GB GPUs for approximately 2.5 days.
281
+
282
+ We utilized the deterministic second-order sampler as proposed by Karras et al. (2022) with 18 integration steps. Each sampled image utilizes a unique initial seed. We sample on a single NVIDIA A100 40GB GPU. Sampling 50, 000 images takes approximately 25 to 30 minutes.
283
+
284
+ Figure 8 shows samples from the diffusion models trained. On CIFAR-10 we report a FID score of 3.9537. Scores on BinaryMNIST and FashionMNIST are ommited as those are not widely reported and heavily depend on preprocessing (Song et al., 2021).
285
+
286
+ ![](images/ea3391c5772dc6ac48b10fc66b1e6b0c3fe5c90b4a66a15b9b93e05697e451ba.jpg)
287
+ Figure 8: Samples of the diffusion models trained on BinaryMNIST (LeCun et al., 1998), FashionMNIST (Xiao et al., 2017), and CIFAR-10 (Krizhevsky et al., 2009).
288
+
289
+ # D DETAILS ON VAE ARCHITECTURES
290
+
291
+ This section provides a detailed description of the VAE models utilized throughout the paper. We consider a fully-connected architecture and a residual architecture (He et al., 2016). Table 4 gives more details on the likelihood model and architecture. For BinaryMNIST and FashionMNIST, we chose the hyperparameters of the VAE models by consulting the literature. For CIFAR-10, we manually tried out a few hyperparameters, and chose an architecture where overfitting occurs, as we are investigating how to alleviate overfitting in VAEs only from the training data.
292
+
293
+ The fully-connected architecture maps from an input dimension of $3 2 ^ { 2 }$ to a hidden dimension of 512. After a hidden layer mapping from 512 to 512, the output is mapped to a latent variable of dimension 16. The decoder mirrors the encoder and maps the latent variable of dimension 16 via three layers to the original input size.
294
+
295
+ The residual architecture maps the input by two convolutional layers (kernel size: 4, stride: 2, padding: 1), two residual layers, and another convolutional layer to a latent dimension of 64. The residual connection is made up of two convolutional layers where the first one applies a kernel of size 3 (kernel size: 3, stride: 1, padding: 1) and the second one applies a kernel of size 1 (kernel size: 1, stride: 1, padding: 0) All convolutional layers do not use any biases and are followed by BatchNorm (Ioffe & Szegedy, 2015). The decoder mirrors the architecture of the encoder.
296
+
297
+ Table 4: Details on VAE architectures ordered by dataset. MoL refers to the discretized mixture of logistics likelihood model (Salimans et al., 2017).
298
+
299
+ <table><tr><td>dataset</td><td>likelihood</td><td>architecture</td></tr><tr><td>BinaryMNIST</td><td>Bernoulli</td><td>fully-connected</td></tr><tr><td>FashionMNIST</td><td>fixed-variance Gaussian</td><td>fully-connected</td></tr><tr><td>FashionMNIST</td><td>MoL</td><td>fully-connected</td></tr><tr><td>CIFAR-10</td><td>MoL</td><td>residual network</td></tr></table>
300
+
301
+ # E AUGMENTATION
302
+
303
+ We use the augmentation pipeline originally proposed for GAN training following Karras et al. (2020). Each specific augmentation is applied with a probability of $b \in \{ 0 . 1 , 0 . 1 2 \}$ . For each dataset we compare two sets of specific augmentations.
304
+
305
+ 1. The hyperparameters for each specific augmentation are tuned by hand with the goal of imitating the data generating distribution that produced the dataset. 2. We use a naive set of specific augmentations that is targeted to image datasets.
306
+
307
+ Table 5 lists naive augmentation for BinaryMNIST, FashionMNIST, and CIFAR-10. Table 6 lists augmentation tuned to the BinaryMNIST and the FashionMNIST dataset. Table 7 lists augmentation tuned to the CIFAR-10 datset.
308
+
309
+ Table 5: List of specific augmentations applied to BinaryMNIST, FashionMNIST and CIFAR-10. We refer to this set as “naive” augmentation as it is targeted towards images in general (and not towards specific datasets). Each specific augmentation is applied with probability $b$ .
310
+
311
+ <table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>horizontal flip translation</td><td>flip an image horizontally translate an image in x and y direction for t ∈ {O,1,2,3} pixels</td></tr><tr><td>scaling</td><td> scale an image by 2oscale with Oscale ∈ [0,0.2]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,10]</td></tr><tr><td>anisotropic scaling</td><td>do anisotropic scaling with scale 2aniso-scale (Oaniso-scale E [0,0.2])</td></tr><tr><td>anisotropic rotation</td><td>do anisotropic rotation with a probability of 0.5</td></tr><tr><td>brightness</td><td>change the brightness of an image by Obrightness ∈ [0,0.2]</td></tr><tr><td>contrast</td><td>change the contrast of an image by 2contrast where Tcontrast ∈ [0,0.25]</td></tr><tr><td>hue</td><td></td></tr><tr><td>saturation</td><td>change the hue by rotation of rhue with rhue ∈ [0,0.25 · π] change the saturation of an image by 2osaturation where Osaturation ∈ [0,0.5]</td></tr></table>
312
+
313
+ Table 6: List of specific augmentations applied to BinaryMNIST and FashionMNIST. The set is tuned towards BinaryMNIST and FashionMNIST. Each specific augmentation is applied with probability $b$ .
314
+
315
+ <table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>translation</td><td>translate an image in x and y direction for t ∈ {0,1,2,3} pixels</td></tr><tr><td>scaling</td><td>scale an image by 2σscale with σscale ∈ [0, 0.15]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,10]</td></tr><tr><td>anisotropic scaling anisotropic rotation</td><td>do anisotropic scaling with scale 2°aniso-scale (Oaniso-scale E [0, 0.15]) do anisotropic rotation with a probability of 0.4</td></tr></table>
316
+
317
+ Table 7: List of specific augmentations applied to CIFAR-10. The set is tuned towards CIFAR-10. Each specific augmentation is applied with probability $b$ .
318
+
319
+ <table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>horizontal flip</td><td>flip an image horizontally (applied with probability 1)</td></tr><tr><td>vertical flip</td><td>flip an image vertically</td></tr><tr><td>scaling</td><td> scale an image by 2σscale with Oscale ∈ [0,0.2]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,360]</td></tr><tr><td>anisotropic scaling</td><td>do anisotropic scaling with scale 2aniso-scale (Oaniso-scale ∈ [0,0.2])</td></tr><tr><td>anisotropic rotation</td><td>do anisotropic rotation with a probability of 0.5</td></tr></table>
320
+
321
+ # F PRACTICAL EVALUATION OF VAES ON THREE TASKS
322
+
323
+ The improvements of generalization performance, amortized inference and robustness of VAEs have direct impacts on their applications. In this section, we evaluate three popular tasks of VAEs based on whether a task involves only the encoder, the decoder, or both as in (Xiao & Bamler, 2023): (a) representation learning (i.e., using only the encoder); (b) data reconstruction (i.e., using both the encoder and the decoder); and (c) sample generation (i.e., using only the decoder).
324
+
325
+ Representation learning (with classification as the downstream task). We evaluate the representation learning performance by classification accuracies on the mean $\pmb { \mu }$ of $q _ { \phi } ( \pmb { z } | \pmb { x } )$ for each $_ { \textbf { \em x } }$ . First, we find the learned representations $\pmb { \mu }$ for all data points in the CIFAR-10 test set. Afterwards, we split them into two separate subsets. We use one subset to train the classifier, and test it on the other subset. Our experiments include four different classifiers: logistic regression, a support vector machine (Boser et al., 1992) with radial basis function kernel (SVM-RBF), a SVM with linear kernel (SVM-L), and $k$ -nearest neighbors (kNN) with $k = 5$ . Table 8 (representation learning; RL) shows the resulting test accuracies across all models considered. We find that VAEs trained with DMaaPx (in bold) outperform other models on average, which highlights that the task of representation learning benefits from the smaller gaps evaluated in Section 5.
326
+
327
+ Data reconstruction. Tasks such as lossy data compression (Balle et al. ´ , 2017) rely on the reconstruction performance of VAEs. We evaluate the reconstruction performance of VAEs trained on CIFAR-10 using the peak signal-to-noise ratio (PSNR; higher is better). Table 8 (reconstruction; RC) shows that DMaaPx outperforms others on average.
328
+
329
+ Sample generation. We evaluate the quality of samples generated by VAEs trained on CIFAR-10 with the methods explained in the main text (Normal Training, DMaaPx, Aug.Naive, Aug.Tuned). We report Frechet Inception Distance ( ´ Heusel et al., 2017) (FID; lower is better) and Inception Score (Salimans et al., 2018) (IS; higher is better). Table 8 (sample quality; SQ) shows that DMaaPx slightly outperforms the others when sample quality is measured in FID, but Normal Training performs better when sample quality is measured in IS.
330
+
331
+ Overall, VAEs trained with DMaaPx show improvements for representation learning and data reconstruction, and perform similarly to normal training on sample quality. At the same time, VAEs trained with both augmentations seem to have slightly worse performance for representation learning and sample generation, and perform similarly on the reconstruction task when compared to normal training. The results of DMaaPx in the table is consistent with our claim that the proposed method mainly fixes the encoder, which affects representation learning and reconstruction but not sample quality. Additionally, Theis et al. (2016) show that a generative model with good log-likelihood (i.e., high test ELBO in the case of a VAE) does not necessarily produce great samples.
332
+
333
+ Table 8: Evaluation of downstream applications of VAEs on CIFAR-10: representation learning with classification as the downstream task (RL), reconstruction (RC), and sample quality (SQ). Results are averaged over 3 random seeds. Note that most differences are smaller than the standard deviations. See Appendix F for a discussion of the results.
334
+
335
+ <table><tr><td colspan="2"></td><td>Normal Training</td><td> DMaaPx (ours)</td><td>Aug.Naive</td><td>Aug.Tuned</td></tr><tr><td rowspan="3">RL</td><td>log. reg. (↑)</td><td>0.370 ± 0.018</td><td>0.383 ± 0.018</td><td>0.359 ± 0.004</td><td>0.361 ± 0.014</td></tr><tr><td>SVM-RBF (↑)</td><td>0.427 ± 0.014</td><td>0.438 ± 0.015</td><td>0.421± 0.004</td><td>0.420 ± 0.016</td></tr><tr><td>SVM-L (↑) kNN (↑)</td><td>0.367 ± 0.015</td><td>0.380 ± 0.014</td><td>0.365± 0.005</td><td>0.366 ± 0.022</td></tr><tr><td colspan="2">RC</td><td>0.325 ± 0.006 16.087± 0.042</td><td>0.327 ± 0.035 16.370 ± 0.195</td><td>0.300 ± 0.004 16.105 ± 0.017</td><td>0.299 ±0.028 15.924± 0.205</td></tr><tr><td rowspan="2">SQ IS ()</td><td>PSNR (1) FID ()</td><td>219.256 ± 16.124</td><td>219.081 ± 14.894</td><td>237.238 ± 43.218</td><td>240.898 ± 11.072</td></tr><tr><td></td><td>1.818 ± 0.155</td><td>1.614 ± 0.076</td><td>1.656 ± 0.047</td><td>1.612 ± 0.083</td></tr></table>
336
+
337
+ ![](images/d8c20c43894f6ae1eb8cc769ad9cda3ccb31fed638c22914b88573f6bc1f525b.jpg)
338
+
339
+ (b) Distribution of the ELBO differences when compared to Normal Training, i.e., $\Delta \mathrm { E L B O : = }$ $\mathrm { E L B O } _ { p } [ { \pmb x } ] - \mathrm { E L B O } _ { \mathcal { D } _ { \mathrm { t r a i n } } } [ { \pmb x } ] ,$ , where $p$ is $p _ { \mathrm { D M } } ( \pmb { x } ^ { \prime } )$ if evaluated on the VAE trained with DMaaPx or the corresponding $p _ { \mathrm { a u g } } ( \pmb { x } ^ { \prime } )$ if evaluated on the VAE trained with Aug.Tuned and Aug.Naive.
340
+
341
+ Figure 9: Individual ELBO evaluated on CIFAR-10 test set. Left: histograms for ELBO and ELBO differences ( $\Delta$ ELBO) on individual image. Right: ELBO and $\Delta$ ELBO values for individual image. Data are ordered by ELBO values of Normal Training from high (index 1) to low (index 10000).
342
+
343
+ # G ELBOS ON INDIVIDUAL TEST IMAGES
344
+
345
+ In this section, we investigate the distribution of the ELBO values on individual data points of the CIFAR-10 test set (that has a size of 10, 000), as one might be curious whether DMaaPx or augmentations only improve VAEs on a subset of the training data.
346
+
347
+ Figure 9 (a, left) shows a histogram of ELBO values for all methods. We find that the distribution of ELBO values shifts to the right (i.e., ELBOs are larger) when comparing Normal Training to other methods. We do not see any significant differences between DMaaPx, Aug.Tuned, and Aug.Naive. Figure 9 (a, right) shows the ELBO evaluated on individual test images. The test images are ordered and indexed based on their ELBO values with Normal Training from high (index 1) to low (index 10000). Both DMaaPx, Aug.Tuned, and Aug.Naive perform similarly better compared to the model with Normal Training across all test images. We can verify the same finding when plotting the differences between DMaaPx, Aug.Tuned, Aug.Naive and Normal Training. Figure 9 (b) shows the distribution of differences in a histogram (left) and for individual test images (right). We find that our method improves the ELBO on almost all $( 9 9 . 9 \%$ ) of the test points (see Figure 9 (b, right)).
348
+
349
+ Overall, the ELBO improvement by both DMaaPx and augmentations is observed across all test images, and we could not identify a subset of test data points where the improvement is particularly small or large when compared to Normal Training.
parse/test/pyW37euNXb/pyW37euNXb_content_list.json ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "type": "text",
4
+ "text": "UPGRADING VAE TRAINING WITH UNLIMITED DATA PLANS PROVIDED BY DIFFUSION MODELS ",
5
+ "text_level": 1,
6
+ "page_idx": 0
7
+ },
8
+ {
9
+ "type": "text",
10
+ "text": "Anonymous authors Paper under double-blind review ",
11
+ "page_idx": 0
12
+ },
13
+ {
14
+ "type": "text",
15
+ "text": "ABSTRACT ",
16
+ "text_level": 1,
17
+ "page_idx": 0
18
+ },
19
+ {
20
+ "type": "text",
21
+ "text": "Variational autoencoders (VAEs) are popular models for representation learning but their encoders are susceptible to overfitting (Cremer et al., 2018) because they are trained on a finite training set instead of the true (continuous) data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . Diffusion models, on the other hand, avoid this issue by keeping the encoder fixed. This makes their representations less interpretable, but it simplifies training, enabling accurate and continuous approximations of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . In this paper, we show that overfitting encoders in VAEs can be effectively mitigated by training on samples from a pre-trained diffusion model. These results are somewhat unexpected as recent findings (Alemohammad et al., 2023; Shumailov et al., 2023) observe a decay in generative performance when models are trained on data generated by another generative model. We analyze generalization performance, amortization gap, and robustness of VAEs trained with our proposed method on three different data sets. We find improvements in all metrics compared to both normal training and conventional data augmentation methods, and we show that a modest amount of samples from the diffusion model suffices to obtain these gains. ",
22
+ "page_idx": 0
23
+ },
24
+ {
25
+ "type": "text",
26
+ "text": "1 INTRODUCTION ",
27
+ "text_level": 1,
28
+ "page_idx": 0
29
+ },
30
+ {
31
+ "type": "text",
32
+ "text": "Variational autoencoders (VAEs, Kingma & Welling (2014); Rezende et al. (2014)) are a class of deep probabilistic models. They model the underlying data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ from which a given training set ${ \\mathcal { D } } _ { \\mathrm { t r a i n } } = \\{ { \\pmb x } _ { i } \\} _ { i = 1 } ^ { N }$ was drawn. Beyond their generative modeling capabilities, VAEs have many other favorable properties by design which lead to applications such as representation learning (van den Oord et al., 2017) and compression (Yang et al., 2023). However, these properties can be compromised if the VAE is overfitted. Specifically, the encoder $f _ { \\phi } ( \\pmb { x } )$ is more susceptible to overfitting (Wu et al., 2017; Cremer et al., 2018; Shu et al., 2018) than the decoder since a finite training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ is repeatedly fed into the encoder. By contrast, the decoder is trained on unique samples from the approximate posterior distribution inferred by the encoder. ",
33
+ "page_idx": 0
34
+ },
35
+ {
36
+ "type": "text",
37
+ "text": "Overfitting in the encoder implies that the learned mapping $f _ { \\phi } ( \\pmb { x } )$ does not generalize well to unseen data, which can negatively impact the performance of generative modeling, amortized inference, and adversarial robustness. For generative modeling, as the number of training epochs increases, an overfitted VAE will have a higher evidence lower bound (ELBO) on the training set but a lower ELBO on the test set. For amortized inference, an overfitted encoder is more likely to map unseen data to a suboptimal set of variational parameters. This results in a lower ELBO when compared to the ELBO obtained by directly optimizing these parameters. For robustness, an overfitted encoder often learns a less smooth $f _ { \\phi } ( \\pmb { x } )$ , such that a small change in the input $_ { \\textbf { \\em x } }$ can result in a large difference in the latent space. This makes VAEs vulnerable to adversarial attacks, causing realistic and hardly distinguishable inputs to yield semantically different outputs (Kuzina et al., 2022). ",
38
+ "page_idx": 0
39
+ },
40
+ {
41
+ "type": "text",
42
+ "text": "One major cause of overfitting in VAEs is the multiple iterations over the insufficient amount of training data (more details in Section 5). Ideally, we aim to train VAEs with unique samples drawn from $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . But in practice, we only have access to the finite training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . Hence, we ask the question: “Can we have infinite training samples drawn from $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ ?” The answer is likely to be “No”, unless we have access to the true data generating process. However, we do have a class of models, known as diffusion models (Sohl-Dickstein et al., 2015; Ho et al., 2020; Song et al., 2021), that can estimate $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ very well, and that can generate as many sample as we want. Diffusion models achieve the state of the art performance at data generation, but they lack the ",
43
+ "page_idx": 0
44
+ },
45
+ {
46
+ "type": "text",
47
+ "text": "Ideal: ",
48
+ "page_idx": 1
49
+ },
50
+ {
51
+ "type": "equation",
52
+ "img_path": "images/0b929f049eb167f9af774f2d8407288d2c2f7366fb267e1d97f59acecb2e945a.jpg",
53
+ "text": "$$\n\\mathcal { L } = \\mathbb { E } _ { { \\pmb x } \\sim p _ { \\mathrm { d a t a } } ( \\pmb x ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { \\pmb x } ) \\right]\n$$",
54
+ "text_format": "latex",
55
+ "page_idx": 1
56
+ },
57
+ {
58
+ "type": "equation",
59
+ "img_path": "images/86c8f3e8a1433134cc344158ee2764b810a9fa3f7de8186adf99e9eb277d6b37.jpg",
60
+ "text": "$$\n\\mathcal { L } = \\mathbb { E } _ { \\boldsymbol { x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } } \\left[ \\mathrm { E L B O } _ { \\Theta } ( \\pmb { x } ) \\right]\n$$",
61
+ "text_format": "latex",
62
+ "page_idx": 1
63
+ },
64
+ {
65
+ "type": "equation",
66
+ "img_path": "images/cb1be3a1b880aa786238dd22fddeff03a633afcbb7a5ee5fdf5790c0ffd540a2.jpg",
67
+ "text": "$$\n\\mathcal { L } = \\mathbb { E } _ { { x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } } \\left[ \\mathbb { E } _ { p _ { \\mathrm { a u g } } ( { x ^ { \\prime } } \\mid x ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { x ^ { \\prime } } ) \\right] \\right]\n$$",
68
+ "text_format": "latex",
69
+ "page_idx": 1
70
+ },
71
+ {
72
+ "type": "image",
73
+ "img_path": "images/90ae5c6fbb210892ebec22ee07f3be2145a770bfcb4915059fb3499853f29470.jpg",
74
+ "image_caption": [
75
+ "Figure 1: Left: training distributions for the VAE. Note that $p _ { \\mathrm { a u g } } ( { \\pmb x } ^ { \\prime } ) = \\mathbb { E } _ { { \\pmb x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } } [ p _ { \\mathrm { a u g } } ( { \\pmb x } ^ { \\prime } \\mid { \\pmb x } ) ]$ only extrapolates from individual data points $x \\sim \\mathcal { D } _ { \\mathrm { t r a i n } }$ and has density outside the support of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ (e.g., when flipping the digit $^ { 6 6 } 2 ^ { , 5 }$ ). By contrast, the pre-trained diffusion model $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ can interpolate between data ${ \\mathbf { \\boldsymbol { x } } } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } }$ . Right: corresponding VAE training objectives. "
76
+ ],
77
+ "image_footnote": [],
78
+ "page_idx": 1
79
+ },
80
+ {
81
+ "type": "text",
82
+ "text": "DMaaPx (proposed): ",
83
+ "page_idx": 1
84
+ },
85
+ {
86
+ "type": "equation",
87
+ "img_path": "images/9efb5fe33f833237447483e4256436273387a53b327be1d397bbc0bea9e647fe.jpg",
88
+ "text": "$$\n\\mathcal { L } = \\mathbb { E } _ { x ^ { \\prime } \\sim p _ { \\mathrm { D M } } ( x ^ { \\prime } ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( x ^ { \\prime } ) \\right]\n$$",
89
+ "text_format": "latex",
90
+ "page_idx": 1
91
+ },
92
+ {
93
+ "type": "text",
94
+ "text": "nice properties we want from VAEs, such as semantically meaningful representations. If diffusion models are indeed close estimates for $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , we should be able to alleviate the overfitting problem in VAEs using samples from pre-trained diffusion models. In this work, we investigate the effect of modifying the normal training procedure of VAEs by replacing the finite training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ with unlimited samples generated by a pre-trained diffusion model $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ . This idea can be considered as cross-model-class distillation, i.e., distilling from a diffusion model to a VAE. ",
95
+ "page_idx": 1
96
+ },
97
+ {
98
+ "type": "text",
99
+ "text": "Data augmentation is another method that can generate unlimited data, and it is used to reduce overfitting. However, selecting appropriate augmentations requires human expertise, and the augmented data might inaccurately represent $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . Hence, augmentation might lead to training a wrong probabilistic model, even though it can reduce overfitting. Figure 1, discussed further in Section 4, illustrates the relation between the underlying data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , the training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ , the augmented training data distribution $p _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } )$ , and the pre-trained diffusion model $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ . ",
100
+ "page_idx": 1
101
+ },
102
+ {
103
+ "type": "text",
104
+ "text": "We empirically show that the new method can indeed alleviate the overfitting issue in VAEs. Specifically, VAEs trained with the new method have better test set performance on estimating the density, on doing approximate inference, and on robustness against adversarial attacks. We also show that we do not need infinite data to gain such generalization performance. As an additional contribution, we publish all the samples we used to train our VAEs, so others do not need to spend compute to train and sample from diffusion models again. ",
105
+ "page_idx": 1
106
+ },
107
+ {
108
+ "type": "text",
109
+ "text": "2 PERFORMANCE GAPS IN VAES ",
110
+ "text_level": 1,
111
+ "page_idx": 1
112
+ },
113
+ {
114
+ "type": "text",
115
+ "text": "VAEs model the data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ by assuming that its generative process first draws a latent variable $_ z$ from $p ( z )$ and then draws $_ { \\textbf { \\em x } }$ from $p _ { \\theta } ( \\pmb { x } | \\pmb { z } )$ with model parameters $\\theta$ . Given a training data distribution $p ( { \\pmb x } )$ that approximates $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , naive maximum likelihood learning would maximize ",
116
+ "page_idx": 1
117
+ },
118
+ {
119
+ "type": "equation",
120
+ "img_path": "images/839454b0555b0f9a23c77526713d91650ba10a3cc7f491b7b2062f8b9e480050.jpg",
121
+ "text": "$$\n\\operatorname* { m a x } _ { \\theta } \\mathbb { E } _ { \\mathbf { x } \\sim p ( \\mathbf { x } ) } \\big [ \\log p _ { \\theta } ( \\mathbf { x } ) \\big ] = \\operatorname* { m a x } _ { \\theta } \\mathbb { E } _ { \\mathbf { x } \\sim p ( \\mathbf { x } ) } \\bigg [ \\log \\int p _ { \\theta } ( \\mathbf { x } \\mid z ) p ( z ) \\mathrm { d } z \\bigg ] .\n$$",
122
+ "text_format": "latex",
123
+ "page_idx": 1
124
+ },
125
+ {
126
+ "type": "text",
127
+ "text": "Generally, maximizing this likelihood is difficult since we need to integrate over the latent variable $_ { z }$ . Hence, VAEs turn to an approximate inference method, called variational inference. This method introduces an approximate posterior $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ within a tractable variational family, and maximizes a lower bound of Eq. (5), known as the evidence lower bound (ELBO; Blei et al. (2017)) ",
128
+ "page_idx": 1
129
+ },
130
+ {
131
+ "type": "equation",
132
+ "img_path": "images/04998e20e87b6eb43f5c23755d3decb830ce170fd7027cd506931fc8c6965a59.jpg",
133
+ "text": "$$\n\\begin{array} { r } { \\log p _ { \\theta } ( \\pmb { x } ) \\geq \\mathbb { E } _ { z \\sim q _ { \\phi } ( z \\mid \\pmb { x } ) } \\big [ \\log p _ { \\theta } ( \\pmb { x } \\mid z ) + \\log p ( z ) - \\log q _ { \\phi } ( z \\mid \\pmb { x } ) \\big ] = : \\mathrm { E L B O } _ { \\Theta } ( \\pmb { x } ) , } \\end{array}\n$$",
134
+ "text_format": "latex",
135
+ "page_idx": 1
136
+ },
137
+ {
138
+ "type": "text",
139
+ "text": "where $\\Theta = \\{ \\theta , \\phi \\}$ . In VAEs, the approximate posterior $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ is usually a Gaussian distribution parameterized by the output of a neural network $f _ { \\phi } ( \\pmb { x } )$ with weights $\\phi$ . We call $p _ { \\theta } ( \\pmb { x } | \\pmb { z } )$ the conditional likelihood to distinguish it from the likelihood $p _ { \\theta } ( { \\pmb x } )$ . The distribution of $p _ { \\theta } ( \\pmb { x } | \\pmb { z } )$ is also parameterized by the output of a network $g _ { \\boldsymbol { \\theta } } ( z )$ with weights $\\theta$ . We often refer to $f _ { \\phi } ( \\pmb { x } )$ as the inference network (or the encoder) and $g _ { \\boldsymbol { \\theta } } ( z )$ as the generative network (or the decoder). ",
140
+ "page_idx": 1
141
+ },
142
+ {
143
+ "type": "text",
144
+ "text": "Combining Eq. (5) and Eq. (6), we have the training objective of VAEs, i.e., to maximize ",
145
+ "page_idx": 2
146
+ },
147
+ {
148
+ "type": "equation",
149
+ "img_path": "images/32c70aac199c8fff801316bdb557a0827a2fa6e93bb0510d46ac2d5dd838e0c4.jpg",
150
+ "text": "$$\n\\begin{array} { r } { \\mathcal { L } = \\mathbb { E } _ { { \\pmb { x } } \\sim p ( { \\pmb x } ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { \\pmb x } ) \\right] . } \\end{array}\n$$",
151
+ "text_format": "latex",
152
+ "page_idx": 2
153
+ },
154
+ {
155
+ "type": "text",
156
+ "text": "Ideally, we would like to use $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ for $p ( { \\pmb x } )$ , but in reality we only have access to $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . We now discuss three performance metrics for VAEs to evaluate the degree and the impact of overfitting. These metrics are defined in term of gaps, and will be used in the experiment section below. ",
157
+ "page_idx": 2
158
+ },
159
+ {
160
+ "type": "text",
161
+ "text": "Generalization gap. One signal for overfitting is that a model performs better on the training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ than on the test set $\\mathcal { D } _ { \\mathrm { t e s t } }$ , and the test set performance decreases over training epochs. For VAEs, we refer to the difference between training and test set ELBO as the generalization gap ",
162
+ "page_idx": 2
163
+ },
164
+ {
165
+ "type": "equation",
166
+ "img_path": "images/e03dad700ddf0dac239b4340ff549c282ea0ca6c0a51f8f3b2cc0beddfcdbd60.jpg",
167
+ "text": "$$\n\\begin{array} { r } { \\mathcal { G } _ { \\mathrm { g } } \\ = \\ \\mathbb { E } _ { \\pmb { x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } } \\left[ \\mathrm { E L B O } _ { \\Theta } ( \\pmb { x } ) \\right] \\ - \\ \\mathbb { E } _ { \\pmb { x } \\sim \\mathcal { D } _ { \\mathrm { t e s t } } } \\left[ \\mathrm { E L B O } _ { \\Theta } ( \\pmb { x } ) \\right] . } \\end{array}\n$$",
168
+ "text_format": "latex",
169
+ "page_idx": 2
170
+ },
171
+ {
172
+ "type": "text",
173
+ "text": "Since $\\mathcal { D } _ { \\mathrm { t r a i n } }$ and $\\mathcal { D } _ { \\mathrm { t e s t } }$ both consist of samples from the same distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , and training maximizes the ELBO on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ , the ELBO on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ is greater than or equal to the ELBO on $\\mathcal { D } _ { \\mathrm { t e s t } }$ . Therefore, $\\mathcal { G } _ { \\mathrm { g } } \\geq 0$ . A smaller $\\mathcal { G } _ { \\mathrm { g } }$ corresponds to a better generalization performance of a VAE. ",
174
+ "page_idx": 2
175
+ },
176
+ {
177
+ "type": "text",
178
+ "text": "Remark (Test data entropy can also affect the ELBO value). Note that from Eqs. (6) and (7), we have ",
179
+ "page_idx": 2
180
+ },
181
+ {
182
+ "type": "equation",
183
+ "img_path": "images/05ee41c657bc53004514ce8e96c6d20685a99d8cd277eb77c33d49330ca8aa21.jpg",
184
+ "text": "$$\n\\mathbb { E } _ { { \\mathbf Z } \\sim p ( { \\mathbf x } ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { \\mathbf x } ) \\right] \\le \\mathbb { E } _ { { \\mathbf x } \\sim p ( { \\mathbf x } ) } \\left[ \\log p _ { \\theta } ( { \\mathbf x } ) \\right] = - H [ p ( { \\mathbf x } ) , p _ { \\theta } ( { \\mathbf x } ) ] \\le - H [ p ( { \\mathbf x } ) ] ,\n$$",
185
+ "text_format": "latex",
186
+ "page_idx": 2
187
+ },
188
+ {
189
+ "type": "text",
190
+ "text": "where $H$ denotes the (cross) entropy. Therefore, the ELBO on $\\mathcal { D } _ { \\mathrm { t e s t } }$ can be higher than the ELBO on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ , if $\\mathcal { D } _ { \\mathrm { t r a i n } }$ and $\\mathcal { D } _ { \\mathrm { t e s t } }$ are not drawn from the same distribution, and $\\mathcal { D } _ { \\mathrm { t e s t } }$ has a lower entropy than $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . Indeed, this phenomenon has been observed in the out-of-distribution setting when testing on a low-entropy data set (Nalisnick et al., 2018). We will refer back to this in Section 5.6. ",
191
+ "page_idx": 2
192
+ },
193
+ {
194
+ "type": "text",
195
+ "text": "Amortization gap. VAEs use amortized inference, i.e., they set the variational parameters of $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ to the output of the encoder $f _ { \\phi } ( \\pmb { x } )$ for all given $_ { \\textbf { \\em x } }$ . At test time, we can further maximize the ELBO over the individual variational parameters for each $_ { \\textbf { \\em x } }$ , which is more expensive but typically results in a better variational distribution $q ^ { * } ( z \\mid x )$ . We then study the amortization gap, ",
196
+ "page_idx": 2
197
+ },
198
+ {
199
+ "type": "equation",
200
+ "img_path": "images/a053e64aee90ed44c5a4f0e8425fdf22a98f987ba5ef1fb87bdd5e8e0bd84322.jpg",
201
+ "text": "$$\n\\mathcal { G } _ { \\mathrm { a } } = \\mathbb { E } _ { \\mathbf { x } \\sim \\mathcal { D } _ { \\mathrm { t e s t } } } [ \\mathrm { E L B O } _ { \\theta } ^ { * } ( \\mathbf { x } ) ] - \\mathbb { E } _ { \\mathbf { x } \\sim \\mathcal { D } _ { \\mathrm { t e s t } } } [ \\mathrm { E L B O } _ { \\Theta } ( \\mathbf { x } ) ]\n$$",
202
+ "text_format": "latex",
203
+ "page_idx": 2
204
+ },
205
+ {
206
+ "type": "text",
207
+ "text": "where $\\begin{array} { r } { \\operatorname { E L B O } _ { \\theta } ^ { * } ( \\pmb { x } ) = \\operatorname { \\mathbb { E } } _ { z \\sim q ^ { * } ( z \\mid \\pmb { x } ) } \\left[ \\log p _ { \\theta } ( \\pmb { x } \\mid z ) + \\log p ( z ) - \\log q ^ { * } ( z \\mid \\pmb { x } ) \\right] . } \\end{array}$ . As mentioned before, the encoder $f _ { \\phi } ( \\pmb { x } )$ is more susceptible to overfitting than the decoder in VAEs. When the encoder overfits, its inference ability might not generalize to test data, which results in lower ELBO value and larger amortization gap. The amortization gap $\\mathcal { G } _ { \\mathrm { a } }$ is non-negative and a smaller $\\mathcal { G } _ { \\mathrm { a } }$ corresponds to better generalization performance of the inference model (or encoder). ",
208
+ "page_idx": 2
209
+ },
210
+ {
211
+ "type": "text",
212
+ "text": "Robustness gap. An overfitted encoder $f _ { \\phi } ( \\pmb { x } )$ often learns a less smooth function such that a small change in the input space can lead to a huge difference in the output space. Hence, it is easier to construct an adversarial sample ${ \\pmb x } ^ { \\mathrm { a } } = { \\pmb x } ^ { \\mathrm { r } } + { \\pmb \\epsilon }$ (s.t. $\\| \\epsilon \\| \\le \\delta )$ from a real data point ${ \\pmb x } ^ { \\mathrm { r } } \\in \\mathcal { D } _ { \\mathrm { t e s t } }$ . This is done by maximizing the symmetrized KL-divergence (Kullback & Leibler, 1951) between $q _ { \\phi } ( z | \\boldsymbol { x } ^ { \\mathrm { r } } )$ and $q _ { \\phi } ( z | x ^ { \\mathrm { a } } )$ within a given attack radius $\\delta$ (Kuzina et al., 2022). A successful attack means that the attack reconstruction $\\tilde { \\pmb { x } } ^ { \\mathrm { a } } = g _ { \\theta } ( z ^ { \\mathrm { a } } )$ , $z ^ { \\mathrm { a } } \\sim q _ { \\phi } ( z | x ^ { \\mathrm { a } } )$ , is very different from the real data reconstruction $\\tilde { \\pmb { x } } ^ { \\mathrm { r } } = g _ { \\theta } ( z ^ { \\mathrm { r } } )$ , ${ \\boldsymbol { z } } ^ { \\mathrm { { r } } } \\sim q _ { \\phi } ( { \\boldsymbol { z } } | { \\boldsymbol { x } } ^ { \\mathrm { { r } } } )$ , even though the inputs $\\pmb { x } ^ { \\mathrm { a } }$ and ${ \\pmb x } ^ { \\mathrm { r } }$ are similar. Using the image similarity metric MS-SSIM (Wang et al., 2003), we define the robustness gap as ",
213
+ "page_idx": 2
214
+ },
215
+ {
216
+ "type": "equation",
217
+ "img_path": "images/34931dce0302626df3c352afac219989a3dfd6d48ca174e512d0097f5796059c.jpg",
218
+ "text": "$$\n\\mathcal { G } _ { \\mathrm { r } } = \\mathbb { E } _ { { \\mathbf { x } } ^ { \\mathrm { a } } \\sim p ( { \\mathbf { x } } ^ { \\mathrm { a } } \\mid { \\mathbf { x } } ^ { \\mathrm { r } } ) } \\mathbb { E } _ { { \\mathbf { x } } ^ { \\mathrm { r } } \\sim \\mathcal { D } _ { \\mathrm { t e s t } } } \\big [ \\mathbf { M S } \\mathrm { - S S I M } \\left[ { \\mathbf { x } } ^ { \\mathrm { r } } , { \\mathbf { x } } ^ { \\mathrm { a } } \\right] - \\mathbf { M S } \\mathrm { - S S I M } \\left[ { \\tilde { \\mathbf { x } } } ^ { \\mathrm { r } } , { \\tilde { \\mathbf { x } } } ^ { \\mathrm { a } } \\right] \\big ] .\n$$",
219
+ "text_format": "latex",
220
+ "page_idx": 2
221
+ },
222
+ {
223
+ "type": "text",
224
+ "text": "Note that a higher MS-SSIM corresponds to a more similar data pair. Hence, MS-SSIM $[ { \\pmb x } ^ { \\mathrm { r } } , { \\pmb x } ^ { \\mathrm { a } } ]$ is greater than or equal to $\\mathbf { M S - S S I M } [ \\tilde { { \\boldsymbol { x } } } ^ { \\mathrm { r } } , \\tilde { { \\boldsymbol { x } } } ^ { \\mathrm { a } } ]$ , and the gap $\\mathcal { G } _ { \\mathrm { r } }$ is a non-negative value. A more robust VAE has a higher $\\mathbf { M S - S S I M } [ \\tilde { { \\pmb x } } ^ { \\mathrm { r } } , \\tilde { { \\pmb x } } ^ { \\mathrm { a } } ]$ than the less robust one. Therefore, a smaller $\\mathcal { G } _ { \\mathrm { r } }$ corresponds to a more robust VAE. For more details on the attack see Appendix A. ",
225
+ "page_idx": 2
226
+ },
227
+ {
228
+ "type": "text",
229
+ "text": "3 RELATED WORK ",
230
+ "text_level": 1,
231
+ "page_idx": 2
232
+ },
233
+ {
234
+ "type": "text",
235
+ "text": "We group related work into using diffusion models as data sources and attempts to closing the three performance gaps. Work related to data augmentation and distillation is discussed in Section 4. ",
236
+ "page_idx": 2
237
+ },
238
+ {
239
+ "type": "text",
240
+ "text": "Use samples from pre-trained diffusion models. There are many recent attempts to solve various tasks with data generated by diffusion models. Azizi et al. (2023) fine-tuned a text-to-image diffusion model on ImageNet, generated state-of-the-art samples with class labels, and trained a classifier on the samples. Their result shows that the classifier trained on generated data does not outperform the classifier trained on real data. In the adversarial training setting, using generated data by diffusion models shows significant improvements on classification robustness (Croce et al., 2021; Wang et al., 2023). Tian et al. (2023) found that the visual representations learned from samples generated by text-to-image diffusion models outperform the representations learned by SimCLR and CLIP. Alemohammad et al. (2023) trained new diffusion models with samples from previously trained diffusion models, and they found that their sample quality and diversity progressively decrease. In this work, we find that using diffusion models as data sources improves the performance of VAEs. ",
241
+ "page_idx": 3
242
+ },
243
+ {
244
+ "type": "text",
245
+ "text": "Improve generalization, amortized inference, and robustness in VAEs. Cremer et al. (2018) study the amortization gap in VAEs, and they notice that overfitting in the encoder is one of the contributing factors of the gap, and it hurts the generalization of VAEs. Many subsequent works try to close the amortization gap by introducing new inference techniques or procedures (Marino et al., 2018; Shu et al., 2018; Zhao et al., 2019). To close the generalization gap and reduce encoder overfitting, Zhang et al. (2022) propose to freeze the decoder after a certain amount of training steps, but further train the encoder by using reconstruction samples as part of the training data. As for adversarial robustness in VAEs, Kuzina et al. (2022) propose to defend a pre-trained VAE by running MCMC during inference to move $_ z$ towards “safer” regions in the latent space. Our proposed method can be used on top of these existing methods, since it does not require changing the original inference procedure. It also takes into account all three gaps at the same time. ",
246
+ "page_idx": 3
247
+ },
248
+ {
249
+ "type": "text",
250
+ "text": "4 DIFFUSION MODEL AS A $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ ",
251
+ "text_level": 1,
252
+ "page_idx": 3
253
+ },
254
+ {
255
+ "type": "text",
256
+ "text": "In this section, we introduce a new method for reducing overfitting in VAEs (Section 4.1). We also discuss how the new method is fundamentally different from naive data augmentation (Section 4.2), and how it can be understood from a cross-model-class distillation perspective (Section 4.3). ",
257
+ "page_idx": 3
258
+ },
259
+ {
260
+ "type": "text",
261
+ "text": "4.1 PROPOSED METHOD ",
262
+ "text_level": 1,
263
+ "page_idx": 3
264
+ },
265
+ {
266
+ "type": "text",
267
+ "text": "The ideal training objective for VAEs is to maximize $\\mathbb { E } _ { { \\pmb x } \\sim p _ { \\mathrm { d a t a } } ( { \\pmb x } ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { \\pmb x } ) \\right]$ (see Eq. (1) in Figure 1). However, in practice, we only have $\\mathcal { D } _ { \\mathrm { t r a i n } }$ as a finite approximation of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . Hence, we normally maximize $\\mathbb { E } _ { \\pmb { x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } }$ $[ \\mathrm { E L B O } _ { \\Theta } ( { \\pmb x } ) ]$ (see Eq. (2)) to train a VAE, which can lead to overfitting. Rather than focusing on model architectures or training techniques as in prior works, we aim to mitigate overfitting by seeking a better approximation for $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ than $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . Here, we make two assumptions: first, the training data distribution should fulfill two criteria; it should be ",
268
+ "page_idx": 3
269
+ },
270
+ {
271
+ "type": "text",
272
+ "text": "(1) a continuous distribution, i.e., we can sample unlimited data to avoid overfitting; and (2) an accurate approximation of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , i.e., we are indeed modeling $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ rather than some different distribution (in practice, it needs to be an accurate model of $\\mathcal { D } _ { \\mathrm { t r a i n } } ,$ ). ",
273
+ "page_idx": 3
274
+ },
275
+ {
276
+ "type": "text",
277
+ "text": "Our second assumption is that a good diffusion model1 that has been pre-trained on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ satisfies these two criteria: (1) we can generate unlimited samples from it, and (2) its training objective is designed to model $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , allowing us to generate samples with state-of-the-art quality across various data types. Therefore, we investigate training VAEs using a pre-trained diffusion model $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ instead of $\\mathcal { D } _ { \\mathrm { t r a i n } }$ as an approximation of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , i.e., to maximize $\\mathbb { E } _ { { \\pmb x } \\sim p _ { \\mathrm { D M } } ( { \\pmb x } ^ { \\prime } ) } \\left[ \\mathrm { E L B O } _ { \\Theta } ( { \\pmb x } ^ { \\prime } ) \\right]$ (see Eq. (4)). We denote this method DMaaPx, short for “Diffusion Model as a $p _ { \\mathrm { d a t a } } ( { \\pmb x } ) ^ { \\prime }$ . ",
278
+ "page_idx": 3
279
+ },
280
+ {
281
+ "type": "text",
282
+ "text": "Figure 1 illustrates the intuition behind this idea. The blue dots represent the finite data set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . They are i.i.d. samples from the underlying data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ (shown by the dark-edged region). The green regions represent the distribution learned by $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ . We use areas, not dots, to highlight that $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ models a continuous distribution that can generate infinitely many samples. ",
283
+ "page_idx": 3
284
+ },
285
+ {
286
+ "type": "text",
287
+ "text": "Note that diffusion models for data types other than images are less explored and might not accurately approximate $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . Hence, diffusion models might not satisfy criterion (2). Moreover, due to the data processing inequality, information on $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ captured by a diffusion model that was trained on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ cannot exceed the information contained in $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . In reality, state-of-the-art diffusion models are not able to fit $\\mathcal { D } _ { \\mathrm { t r a i n } }$ perfectly. Indeed, many recent works observe that in both image and text settings, training generative models from generated data leads to worse performance overall (Alemohammad et al., 2023; Shumailov et al., 2023). Hence, the continuity we gain by replacing $\\mathcal { D } _ { \\mathrm { t r a i n } }$ with $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ is not for free, we lose a small amount of information about $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . ",
288
+ "page_idx": 3
289
+ },
290
+ {
291
+ "type": "text",
292
+ "text": "",
293
+ "page_idx": 4
294
+ },
295
+ {
296
+ "type": "text",
297
+ "text": "4.2 DIFFERENCE BETWEEN DATA AUGMENTATION AND DMAAPX ",
298
+ "text_level": 1,
299
+ "page_idx": 4
300
+ },
301
+ {
302
+ "type": "text",
303
+ "text": "Data augmentation2 pursues a similar goal as the proposed DMaaPx as both approaches aim to increase the quantity and diversity of training data. The primary distinction between them is in their accuracy in approximating $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ , as shown in Table 1. This can be attributed primarily to two key factors. Firstly, typical data augmentation techniques generate new training points by conditioning on a ",
304
+ "page_idx": 4
305
+ },
306
+ {
307
+ "type": "table",
308
+ "img_path": "",
309
+ "table_caption": [
310
+ "Table 1: Training distributions for VAEs (see Figure 1), and whether they are (1) continuous and (2) an accurate approximation of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . "
311
+ ],
312
+ "table_footnote": [],
313
+ "page_idx": 4
314
+ },
315
+ {
316
+ "type": "equation",
317
+ "img_path": "images/fc8016dd0e4812031291f93d5c01f4f8fbc857e240b2b87f190ce84d5bc0db53.jpg",
318
+ "text": "$$\n\\begin{array} { r l } & { \\frac { \\mathrm { a p p r o x . ~ b y } } { ( 1 ) \\mathrm { c o n t i n u o u s } } \\frac { \\mathcal { D } _ { \\mathrm { t r a i n } } \\mathrm { \\quad } p _ { \\mathrm { a u g } } ( { \\pmb x } ^ { \\prime } ) \\mathrm { \\quad } p _ { \\mathrm { D M } } ( { \\pmb x } ^ { \\prime } ) } { \\pmb \\chi } } \\\\ & { ( 2 ) \\mathrm { a c c u r a t e } } \\end{array}\n$$",
319
+ "text_format": "latex",
320
+ "page_idx": 4
321
+ },
322
+ {
323
+ "type": "text",
324
+ "text": "single original data point. Thus, $p _ { \\mathrm { a u g } } ( \\pmb x ^ { \\prime } ) = \\mathbb { E } _ { \\pmb { x } \\sim \\mathcal { D } _ { \\mathrm { t r a i n } } } \\bigl [ p _ { \\mathrm { a u g } } ( \\pmb x ^ { \\prime } | \\pmb x ) \\bigr ]$ where $p _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } | \\pmb { x } )$ generates a training point $\\mathbf { x } ^ { \\prime }$ by applying one or more random transformations (e.g., padding, cropping, flipping (He et al., 2016), translation or even learned rotation and cutout (Cubuk et al., 2019)) to a single original data point $_ { \\textbf { \\em x } }$ . By contrast, in the proposed DMaaPx, each training data point $\\pmb { x } ^ { \\prime } \\sim p _ { \\mathrm { D M } } ( \\bar { \\pmb { x } } ^ { \\prime } )$ is drawn from a diffusion model that was trained on the entire dataset $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . As a consequence, each training data point in DMaaPx is effectively conditioned on the full training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . ",
325
+ "page_idx": 4
326
+ },
327
+ {
328
+ "type": "text",
329
+ "text": "Secondly, the random transformations used for $p _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } \\mid \\pmb { x } )$ in traditional data augmentation are drawn from a manually curated catalog. This catalog is heavily based on prior assumptions regarding invariances in the data type under consideration, which can introduce bias. In practice, one has to make assumptions and decide whether the (unknown) true data distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ is invariant under the considered transformations. For instance, with images, we assume invariance to minor translations, hue shifts, and zooms. This may result in problems of (i) not modeling the full extend of the distribution or (ii) modeling density outside the true data distribution. Figure 1 depicts both: problem (i) corresponds to “empty” space between areas of $p _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } )$ ; problem (ii) corresponds to density of $\\bar { p } _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } )$ outside of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ . The proposed DMaaPx eliminates these explicit assumptions, which makes the method more resilient against human bias (but less interpretable). ",
330
+ "page_idx": 4
331
+ },
332
+ {
333
+ "type": "text",
334
+ "text": "In summary, while traditional data augmentation techniques introduce diversity based on invariances about the data generative process, the proposed DMaaPx uses an expressive generative model to extrapolate from the empirical diversity of the data. ",
335
+ "page_idx": 4
336
+ },
337
+ {
338
+ "type": "text",
339
+ "text": "4.3 A CROSS-MODEL-CLASS DISTILLATION PERSPECTIVE ",
340
+ "text_level": 1,
341
+ "page_idx": 4
342
+ },
343
+ {
344
+ "type": "text",
345
+ "text": "The proposed DMaaPx can also be viewed from a distillation perspective (Hinton et al., 2015). Distillation describes the process of transferring knowledge from a large model to a small one. In practice, distillation is often used because a smaller model is less expensive to be deployed in production. Here we consider a more subtle usage of distillation, i.e., transferring knowledge between models designed with different modeling assumptions or structures. We refer to this as cross-modelclass distillation, and the conventional usage of distillation as within-model-class distillation. There are models that have been designed with useful structures which cannot be fully exploited if trained naively on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . Cross-model-class distillation creates auxiliary training data that helps us train such models to achieve the desired performance. For instance, in the diffusion model literature, numerous studies attempt to distill the multi-step diffusion process into a single-step generative model (Salimans & Ho, 2021; Luhman & Luhman, 2021; Liu et al., 2023; Song et al., 2023). While both types of distillation seek to transfer knowledge from a source to a target model, cross-model-class distillation emphasizes more on enhancing functionalities that are unique to the target model rather than mirroring the capabilities shared with the source model. ",
346
+ "page_idx": 4
347
+ },
348
+ {
349
+ "type": "text",
350
+ "text": "Our proposed DMaaPx belongs to cross-model-class distillation, i.e., it distills diffusion models to VAEs. The goal of DMaaPx is not to rival diffusion models in sample quality, but rather to improve the desirable functionalities of VAEs such as representation learning. From this viewpoint, DMaaPx fundamentally differs from approaches that train VAEs on samples produced by VAEs, or diffusion models on outputs of diffusion models (Alemohammad et al., 2023; Shumailov et al., 2023). Such approaches can be categorized as within-model-class distillation. ",
351
+ "page_idx": 5
352
+ },
353
+ {
354
+ "type": "text",
355
+ "text": "5 EXPERIMENTS ",
356
+ "text_level": 1,
357
+ "page_idx": 5
358
+ },
359
+ {
360
+ "type": "text",
361
+ "text": "In this section, we introduce the experimental setup and evaluate the three performance gaps (see Section 2) of the proposed method. The exact gap values are provided in Appendix B. We further investigate whether we need infinite training data in the proposed method. ",
362
+ "page_idx": 5
363
+ },
364
+ {
365
+ "type": "text",
366
+ "text": "5.1 EXPERIMENTAL SETUP ",
367
+ "text_level": 1,
368
+ "page_idx": 5
369
+ },
370
+ {
371
+ "type": "text",
372
+ "text": "Training data. We evaluate our method on three popular datasets: MNIST (LeCun et al., 1998), FashionMNIST (Xiao et al., 2017), and CIFAR-10 (Krizhevsky et al., 2009). As a preparation, we train a diffusion model $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ which will be used to generate training data for VAEs on each training set $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . We use the implementation of diffusion models by Karras et al. (2022). Further details and samples from the three pre-trained diffusion models can be found in Appendix C. ",
373
+ "page_idx": 5
374
+ },
375
+ {
376
+ "type": "text",
377
+ "text": "VAE architectures. We assume fixed standard Gaussian priors $p ( z ) = \\mathcal { N } ( \\mathbf { 0 } , \\mathbf { I } )$ for all datasets. For the conditional likelihood $p _ { \\theta } ( \\pmb { x } | \\pmb { z } )$ , we use a Bernoulli distribution for binarized MNIST, a diagonal Gaussian distribution with a fixed variance for grayscale FashionMNIST, and a discretized mixture of logistics (MoL; Salimans et al. (2017)) for CIFAR-10. For the inference model $q _ { \\phi } ( { \\boldsymbol { z } } \\mid { \\boldsymbol { x } } )$ , we use diagonal Gaussian distributions with means and variances output from the inference network for all datasets. For more details on network architectures and hyperparameters see Appendix D. ",
378
+ "page_idx": 5
379
+ },
380
+ {
381
+ "type": "text",
382
+ "text": "Baselines. We compare VAEs trained with our proposed DMaaPx against three baseline models trained on: (i) repetitions of $\\mathcal { D } _ { \\mathrm { t r a i n } }$ (“Normal Training”); (ii) carefully tuned augmentation for $\\mathcal { D } _ { \\mathrm { t r a i n } }$ (“Aug.Tuned”); and (iii) plausible augmentation for images in general (“Aug.Naive”). Note that “Aug.Naive” is not tuned to a given $\\mathcal { D } _ { \\mathrm { t r a i n } }$ and can result in out-of-distribution data, e.g. a horizontally flipped digit “2” for MNIST. This mimics situations that arise in augmenting other data modalities, where the choice of transformation is not as obvious as for images. More details on the applied augmentation can be found in Appendix E. Generally, when documenting the training progress, the term “epoch” typically refers to one complete pass of $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . For DMaaPx, this term is not applicable since it can sample unlimited data from $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ . Therefore, we measure training progress of DMaaPx in “effective epochs”. An “effective epoch” represents one pass through sampled training data of size $| \\mathcal { D } _ { \\mathrm { t r a i n } } |$ . We train all models for 1000 (effective) epochs. ",
383
+ "page_idx": 5
384
+ },
385
+ {
386
+ "type": "text",
387
+ "text": "5.2 GENERALIZATION GAP ",
388
+ "text_level": 1,
389
+ "page_idx": 5
390
+ },
391
+ {
392
+ "type": "text",
393
+ "text": "Figure 2 shows both ELBOs evaluated on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ (dashed) and $\\mathcal { D } _ { \\mathrm { t e s t } }$ (solid) for all three datasets. The difference between these two lines is the generalization gap $\\mathcal { G } _ { \\mathrm { g } }$ (Eq. (8)). We observe that our proposed DMaaPx (green) has the highest ELBO on $\\mathcal { D } _ { \\mathrm { t e s t } }$ , and the smallest generalization gap compared to both normal training and data augmentation. VAEs trained on the augmented data show less improvements on test ELBO and generalization gap than DMaaPx. This implies that VAEs trained with DMaaPx approximate the underlying distribution $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ better than those trained on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ solely, or on augmented data. The small generalization gap of DMaaPx means that training ELBOs can be used as accurate predictions for final performance. Given that data from pre-trained diffusion models and augmentation is not an inherently more accurate representation of $p _ { \\mathrm { d a t a } } ( \\pmb { x } )$ than $\\mathcal { D } _ { \\mathrm { t r a i n } }$ , improvements in the test ELBOs suggest that overfitting in VAEs is more detrimental than using a somewhat distorted, but larger and more diverse, dataset. ",
394
+ "page_idx": 5
395
+ },
396
+ {
397
+ "type": "text",
398
+ "text": "5.3 AMORTIZATION GAP ",
399
+ "text_level": 1,
400
+ "page_idx": 5
401
+ },
402
+ {
403
+ "type": "text",
404
+ "text": "The amortization gap, defined in Eq. (10), evaluates the encoder’s inference performance by comparing test ELBOs of the amortized variational parameters of $q _ { \\phi } ( { \\boldsymbol { z } } \\mid { \\boldsymbol { x } } )$ to those from individually optimized variational parameters of $q ^ { * } ( z \\mid x )$ . Figure 3 shows test set ELBOs from $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ and $q ^ { * } ( z \\mid x )$ for the three datasets with values reported every 100 effective epochs. ",
405
+ "page_idx": 5
406
+ },
407
+ {
408
+ "type": "image",
409
+ "img_path": "images/c51bf71ed843433170465c35e361ea92ddec101e69bb857c5f94f0295ef02828.jpg",
410
+ "image_caption": [
411
+ "Figure 2: Generalization performance: ELBOs of models trained with Eqs. (2)-(4), evaluated on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ and $\\mathcal { D } _ { \\mathrm { t e s t } }$ . DMaaPx (proposed) consistently has the best test performance and smallest gap. "
412
+ ],
413
+ "image_footnote": [],
414
+ "page_idx": 6
415
+ },
416
+ {
417
+ "type": "image",
418
+ "img_path": "images/d4b37024e43774cce699041aa4c4c964813f56b99f63ac30e2c0be3f1cb035d7.jpg",
419
+ "image_caption": [
420
+ "Figure 3: Amortization gap: ELBOs with $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ from the inference network (solid) and with iteratively optimized $q ^ { * } ( z \\mid x )$ (dashdot), evaluated on $\\mathcal { D } _ { \\mathrm { t e s t } }$ . Left and center: DMaaPx significantly reduces the amortization gap (Eq. (10)) compared to normal training and data augmentation. Among the dashdot lines, DMaaPx has the highest performance, indicating that it also helps learning a better decoder. Right: DMaaPx and augmentation are tied and outperform normal training. "
421
+ ],
422
+ "image_footnote": [],
423
+ "page_idx": 6
424
+ },
425
+ {
426
+ "type": "text",
427
+ "text": "",
428
+ "page_idx": 6
429
+ },
430
+ {
431
+ "type": "text",
432
+ "text": "The figure illustrates that the ELBOs for normal training using $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ (solid blue) decline with more training epochs, while those using $q ^ { * } ( z \\mid x )$ (dashdot blue) remain stable or even increase. A decline in test set performance across epochs signals overfitting. By using $q ^ { * } ( z \\mid x )$ and excluding the encoder, test performance stabilizes across epochs, indicating that the primary source of overfitting in VAEs is the encoder. This aligns with the findings of Cremer et al. (2018). ",
433
+ "page_idx": 6
434
+ },
435
+ {
436
+ "type": "text",
437
+ "text": "Figure 3 shows that DMaaPx outperforms normal training and data augmentation in both, the size of the amortization gap and the ELBO value for BinaryMNIST and FashionMNIST. Additionally, the increase of ELBOs with $q ^ { * } ( z \\mid x )$ (dashdot) suggests that DMaaPx also improves the decoder. On CIFAR-10, DMaaPx and augmentation similarly outperform normal training. ",
438
+ "page_idx": 6
439
+ },
440
+ {
441
+ "type": "text",
442
+ "text": "5.4 ROBUSTNESS OF REPRESENTATIONS (ROBUSTNESS GAP) ",
443
+ "text_level": 1,
444
+ "page_idx": 6
445
+ },
446
+ {
447
+ "type": "text",
448
+ "text": "The robustness gap, defined in Eq. (11), looks at similarities between real and the corresponding adversarial samples $( \\mathbf { M S - S S I M } [ \\pmb { x } ^ { r } , \\pmb { x } ^ { a } ] )$ and between their respective reconstructions $( \\mathbf { M } \\bar { \\mathbf { S } } \\mathbf { - } \\mathbf { S } \\mathbf { S } \\mathbf { I M } [ \\tilde { \\pmb { x } } ^ { r } , \\tilde { \\pmb { x } } ^ { a } ] )$ . A successful attack achieves low $\\mathbf { M S - S S I M } [ \\tilde { \\pmb { x } } ^ { \\bar { r } } , \\tilde { \\pmb { x } } ^ { a } ]$ despite high $\\mathbf { M S - S S I M } [ \\pmb { x } ^ { r } , \\pmb { x } ^ { a } ]$ . See Appendix A for details on the attack construction in our experiments. ",
449
+ "page_idx": 6
450
+ },
451
+ {
452
+ "type": "text",
453
+ "text": "In Figure 4, we see that DMaaPx consistently matches or surpasses normal training across all three datasets. It also exceeds augmentation on BinaryMNIST and CIFAR-10. Meanwhile, VAEs trained with augmentation display inconsistent results: they outperform both DMaaPx and normal training on FashionMNIST, but fall behind on BinaryMNIST and CIFAR-10, demonstrating that augmentation is more difficult to tune than DMaaPx (training the diffusion model requires less manual effort). ",
454
+ "page_idx": 6
455
+ },
456
+ {
457
+ "type": "image",
458
+ "img_path": "images/0ba831489a05cff1482269ba30d59259207d38b5cfbff24bc73cde0a7e5f3adf.jpg",
459
+ "image_caption": [
460
+ "Figure 4: Adversarial robustness: similarities of reconstructions (solid) for similar but adversarially chosen inputs (see dashed line). DMaaPx is consistently either on par or better than normal training whereas augmentation is significantly worse than normal training for BinaryMNIST and CIFAR-10. "
461
+ ],
462
+ "image_footnote": [],
463
+ "page_idx": 7
464
+ },
465
+ {
466
+ "type": "image",
467
+ "img_path": "images/9d6a670dfbf961c40f696fb4c0642ed588c72e2763a5879bbe5c29bb362bc37f.jpg",
468
+ "image_caption": [
469
+ "Figure 5: Generalization performance as a function of the amount $k$ of training data sampled from the diffusion model. Horizontal blue lines show baseline performance (VAE trained directly on $\\mathcal { D } _ { \\mathrm { t r a i n } } ,$ ). All VAEs were trained for 1000 effective epochs. $k \\approx 1 0$ seems to suffice. "
470
+ ],
471
+ "image_footnote": [],
472
+ "page_idx": 7
473
+ },
474
+ {
475
+ "type": "image",
476
+ "img_path": "images/3093079f65457a5b9c51560e63303561da2f0ad88386cc38a488b2eeb0331d7d.jpg",
477
+ "image_caption": [
478
+ "Figure 6: Generalization performance for FashionMINST with MoL likelihood. We observe similar behavior to center panel in Figure 2, which uses a Gaussian likelihood. "
479
+ ],
480
+ "image_footnote": [],
481
+ "page_idx": 7
482
+ },
483
+ {
484
+ "type": "text",
485
+ "text": "5.5 IS THE “UNLIMITED DATA PLAN” A RIPOFF? ",
486
+ "text_level": 1,
487
+ "page_idx": 7
488
+ },
489
+ {
490
+ "type": "text",
491
+ "text": "With the pre-trained diffusion model in DMaaPx, we can train VAEs with unlimited samples from $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ , enhancing performance as demonstrated above. While generating a large amount of samples from diffusion models is feasible, it still requires substantial computation. Therefore, we further explore: “Do we really need infinite number of samples?” The answer, reassuringly, is “No”. ",
492
+ "page_idx": 7
493
+ },
494
+ {
495
+ "type": "text",
496
+ "text": "Figure 5 shows the generalization performance of DMaaPx on BinaryMNIST and CIFAR-10 where the training data for VAEs is restricted to $k \\times | \\mathcal { D } _ { \\mathrm { t r a i n } } |$ , with $k$ ranging from 1 to 1000. After $k$ effective training epochs, samples start repeating. All models are trained on 1000 effective epochs. Horizontal blue lines represent the generalization gap of normal VAE training (on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ and $k = 1$ ) at epoch 1000 from Figure 2. For $k = 1$ , DMaaPx slightly underperforms on BinaryMNIST but matches normal training on CIFAR-10. The ELBO plateaus for $k \\geq 1 0$ , indicating samples roughly 10 times the size of $\\mathcal { D } _ { \\mathrm { t r a i n } }$ offer similar generalization to samples 1000 times larger. ",
497
+ "page_idx": 7
498
+ },
499
+ {
500
+ "type": "text",
501
+ "text": "5.6 ABLATION AND FURTHER DETAILS ",
502
+ "text_level": 1,
503
+ "page_idx": 7
504
+ },
505
+ {
506
+ "type": "text",
507
+ "text": "In this section we present ablations on different conditional likelihoods, compare the two augmentation strategies considered, and discuss the difference between training ELBO and ELBO on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ ",
508
+ "page_idx": 7
509
+ },
510
+ {
511
+ "type": "image",
512
+ "img_path": "images/5ffeb50429f9b43dae741df19918112ada7fb5637d3782a9bd9502bc34670604.jpg",
513
+ "image_caption": [
514
+ "Figure 7: ELBO evaluted on the distribution that is actually used for training (dotted, see Eqs. (2)-(4)). For augmentations, the test ELBO (solid) is higher than the training ELBO (dotted) in the left two panels, which is an artifact of different entropies of the distributions, see Remark. "
515
+ ],
516
+ "image_footnote": [],
517
+ "page_idx": 8
518
+ },
519
+ {
520
+ "type": "text",
521
+ "text": "Different conditional likelihoods. VAEs’ modeling assumptions for the conditional likelihood $p _ { \\theta } ( \\pmb { x } | \\pmb { z } )$ often differ based on data or use case. While a Gaussian likelihood is used for applications that focus on low reconstruction error (e.g., lossy data compression), an MoL likelihood is used if the density of the data matters (e.g., generative modeling or lossless data compression). Our experiments in Sections 5.2-5.4 cover three likelihoods: Bernoulli for BinaryMNIST, Gaussian for FashionMNIST, and MoL for CIFAR-10. Figure 6 also evaluates MoL for FashionMNIST, and we observe similar behaviour as in its Gaussian counterpart in Figure 2 (center). In summary, DMaaPx is less prone to overfitting than normal training and augmentation, for all investigated likelihoods. ",
522
+ "page_idx": 8
523
+ },
524
+ {
525
+ "type": "text",
526
+ "text": "Tuned and naive augmentation. To fairly assess DMaaPx against augmentation, we design two sets of augmentation: Aug.Tuned (tailored to each $\\mathcal { D } _ { \\mathrm { t r a i n } } .$ ) and Aug.Naive (general for images). They perform similarly overall in Figures 2-4. However, Aug.Naive outperforms Aug.Tuned in generalization on BinaryMNIST and FashionMNIST, and in robustness across all datasets. This is surprising as naive augmentation might produce out-of-distribution data, like a horizontally flipped digit “2”, potentially impairing performance. Thus, designing augmentation can be labor-intensive. ",
527
+ "page_idx": 8
528
+ },
529
+ {
530
+ "type": "text",
531
+ "text": "Training ELBO vs. ELBO on $\\mathcal { D } _ { \\mathrm { t r a i n } }$ . Figure 7 shows the ELBOs analogous to Figure 2, but the dotted lines plot the ELBO on the actual training distribution (e.g., on samples from $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ for DMaaPx). The point of this plot is to warn that comparisons between ELBOs under such different distributions are not meaningful, and should not be used to calculate the generalization gap. For example, note that the plot would suggest a negative generalization gap for data augmentation (purple) on BinaryMNIST. This is consistent with the remark on page 3: since the ELBO is bounded by the negative entropy of the distributions on which it is evaluated, evaluating it on two different distributions with different entropies exhibits differences unrelated to the generalization gap. ",
532
+ "page_idx": 8
533
+ },
534
+ {
535
+ "type": "text",
536
+ "text": "6 CONCLUSION ",
537
+ "text_level": 1,
538
+ "page_idx": 8
539
+ },
540
+ {
541
+ "type": "text",
542
+ "text": "We investigate how overfitting of VAEs can be addressed by training them on samples from a diffusion model that was pre-trained on the training dataset. Our assumption is that, unlike in supervised learning, VAE training requires training data that accurately matches the data generative process. We therefore contrasted our approach to traditional data augmentation methods, which might not accurately model the data generative process. Our results show significant reduction in generalization gaps, improved test ELBOs, and enhanced adversarial robustness. Future work should challenge the above assumption and investigate whether one can further improve VAE performance by designing a generative model that specifically for cross-model-class distillation. ",
543
+ "page_idx": 8
544
+ },
545
+ {
546
+ "type": "text",
547
+ "text": "In a broader sense, our work explores ways of increasing the quantity and diversity of training data in situations where one cares about the underlying data distribution. Future work should also expand this research beyond VAEs, in particular as prior work found that recursive distillation within a diffusion model hurts performance (Alemohammad et al., 2023). Additional work should explore applying our method to other data types, such as structured data like molecules or time series. ",
548
+ "page_idx": 8
549
+ },
550
+ {
551
+ "type": "text",
552
+ "text": "Reproducibility Statement. All code necessary to reproduce the results in this paper is provided in the supplementary materials. We will also publish the samples generated by our pre-trained diffusion models for the DMaaPx experiments after the reviewing process. ",
553
+ "page_idx": 9
554
+ },
555
+ {
556
+ "type": "text",
557
+ "text": "REFERENCES Sina Alemohammad, Josue Casco-Rodriguez, Lorenzo Luzi, Ahmed Imtiaz Humayun, Hossein Babaei, Daniel LeJeune, Ali Siahkoohi, and Richard G Baraniuk. Self-consuming generative models go mad. arXiv preprint arXiv:2307.01850, 2023. 1, 4, 5, 6, 9 Shekoofeh Azizi, Simon Kornblith, Chitwan Saharia, Mohammad Norouzi, and David J Fleet. Synthetic data from diffusion models improves imagenet classification. arXiv preprint arXiv:2304.08466, 2023. 4 Johannes Balle, Valero Laparra, and Eero P Simoncelli. End-to-end optimized image compression. ´ In International Conference on Learning Representations, 2017. 16 David M Blei, Alp Kucukelbir, and Jon D McAuliffe. Variational inference: A review for statisticians. Journal of the American Statistical Association, 2017. 2 Bernhard E Boser, Isabelle M Guyon, and Vladimir N Vapnik. A training algorithm for optimal margin classifiers. In Fifth Annual Workshop on Computational Learning Theory, 1992. 16 Chris Cremer, Xuechen Li, and David Duvenaud. Inference suboptimality in variational autoencoders. In International Conference on Machine Learning, 2018. 1, 4, 7 Francesco Croce, Maksym Andriushchenko, Vikash Sehwag, Edoardo Debenedetti, Nicolas Flammarion, Mung Chiang, Prateek Mittal, and Matthias Hein. Robustbench: a standardized adversarial robustness benchmark. In Neural Information Processing Systems Datasets and Benchmarks Track (Round 2), 2021. 4 Ekin D Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, and Quoc V Le. Autoaugment: Learning augmentation strategies from data. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2019. 5 Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, \n2016. 5, 14 Martin Heusel, Hubert Ramsauer, Thomas Unterthiner, Bernhard Nessler, and Sepp Hochreiter. Gans trained by a two time-scale update rule converge to a local nash equilibrium. In Advances in Neural Information Processing Systems, 2017. 16 Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. 5 Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffusion probabilistic models. In Advances in Neural Information Processing Systems, 2020. 1 Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. In International Conference on Machine Learning, 2015. 14 Tero Karras, Miika Aittala, Janne Hellsten, Samuli Laine, Jaakko Lehtinen, and Timo Aila. Training generative adversarial networks with limited data. In Advances in Neural Information Processing Systems, 2020. 15 Tero Karras, Miika Aittala, Timo Aila, and Samuli Laine. Elucidating the design space of diffusionbased generative models. In Advances in Neural Information Processing Systems, 2022. 6, 13, \n14 Diederik P Kingma and Max Welling. Auto-encoding variational bayes. In International Conference on Learning Representations, 2014. 1 \nAlex Krizhevsky, Geoffrey Hinton, et al. Learning multiple layers of features from tiny images. 2009. 6, 14 \nSolomon Kullback and Richard A Leibler. On information and sufficiency. The Annals of Mathematical Statistics, 22, 1951. 3, 13 \nAnna Kuzina, Max Welling, and Jakub Tomczak. Alleviating adversarial attacks on variational autoencoders with mcmc. In Advances in Neural Information Processing Systems, 2022. 1, 3, 4, 13 \nYann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner. Gradient-based learning applied to ´ document recognition. In Proceedings of the IEEE, 1998. 6, 14 \nXingchao Liu, Chengyue Gong, and qiang liu. Flow straight and fast: Learning to generate and transfer data with rectified flow. In International Conference on Learning Representations, 2023. 5 \nEric Luhman and Troy Luhman. Knowledge distillation in iterative generative models for improved sampling speed. arXiv preprint arXiv:2101.02388, 2021. 5 \nJoe Marino, Yisong Yue, and Stephan Mandt. Iterative amortized inference. In International Conference on Machine Learning, 2018. 4 \nEric Nalisnick, Akihiro Matsukawa, Yee Whye Teh, Dilan Gorur, and Balaji Lakshminarayanan. Do deep generative models know what they don’t know? In International Conference on Learning Representations, 2018. 3 \nDanilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In International Conference on Machine Learning, 2014. 1 \nTim Salimans and Jonathan Ho. Progressive distillation for fast sampling of diffusion models. In International Conference on Learning Representations, 2021. 5 \nTim Salimans, Andrej Karpathy, Xi Chen, and Diederik P. Kingma. PixelCNN $^ { + + }$ : Improving the pixelCNN with discretized logistic mixture likelihood and other modifications. In International Conference on Learning Representations, 2017. 6, 14 \nTim Salimans, Han Zhang, Alec Radford, and Dimitris Metaxas. Improving gans using optimal transport. In International Conference on Learning Representations, 2018. 16 \nRui Shu, Hung H Bui, Shengjia Zhao, Mykel J Kochenderfer, and Stefano Ermon. Amortized inference regularization. In Advances in Neural Information Processing Systems, 2018. 1, 4 \nIlia Shumailov, Zakhar Shumaylov, Yiren Zhao, Yarin Gal, Nicolas Papernot, and Ross Anderson. The curse of recursion: Training on generated data makes models forget. arXiv preprint arxiv:2305.17493, 2023. 1, 5, 6 \nJascha Sohl-Dickstein, Eric Weiss, Niru Maheswaranathan, and Surya Ganguli. Deep unsupervised learning using nonequilibrium thermodynamics. In International Conference on Machine Learning, 2015. 1 \nYang Song, Jascha Sohl-Dickstein, Diederik P Kingma, Abhishek Kumar, Stefano Ermon, and Ben Poole. Score-based generative modeling through stochastic differential equations. In International Conference on Learning Representations, 2021. 1, 14 \nYang Song, Prafulla Dhariwal, Mark Chen, and Ilya Sutskever. Consistency models. In International Conference on Machine Learning, 2023. 5 \nLucas Theis, van den Oord Aaron, and Matthias Bethge. A note on the evaluation of generative ¨ models. In International Conference on Learning Representations, 2016. 16 \nYonglong Tian, Lijie Fan, Phillip Isola, Huiwen Chang, and Dilip Krishnan. Stablerep: Synthetic images from text-to-image models make strong visual representation learners. arXiv preprint arXiv:2306.00984, 2023. 4 \nAaron van den Oord, Oriol Vinyals, et al. Neural discrete representation learning. In Advances in Neural Information Processing Systems, 2017. 1 \nZekai Wang, Tianyu Pang, Chao Du, Min Lin, Weiwei Liu, and Shuicheng Yan. Better diffusion models further improve adversarial training. In International Conference on Machine Learning, 2023. 4 \nZhou Wang, Eero P Simoncelli, and Alan C Bovik. Multiscale structural similarity for image quality assessment. In The Thrity-Seventh Asilomar Conference on Signals, Systems & Computers, 2003, 2003. 3 \nYuhuai Wu, Yuri Burda, Ruslan Salakhutdinov, and Roger Grosse. On the quantitative analysis of decoder-based generative models. In International Conference on Learning Representations, 2017. 1 \nHan Xiao, Kashif Rasul, and Roland Vollgraf. Fashion-mnist: a novel image dataset for benchmarking machine learning algorithms. arXiv preprint arXiv:1708.07747, 2017. 6, 14 \nTim Z. Xiao and Robert Bamler. Trading information between latents in hierarchical variational autoencoders. In International Conference on Learning Representations, 2023. 16 \nSuorong Yang, Weikang Xiao, Mengcheng Zhang, Suhan Guo, Jian Zhao, and Furao Shen. Image data augmentation for deep learning: A survey. arXiv preprint arXiv:2204.08610, 2022. 5 \nYibo Yang, Stephan Mandt, Lucas Theis, et al. An introduction to neural data compression. Foundations and Trends® in Computer Graphics and Vision, 2023. 1 \nMingtian Zhang, Peter Hayes, and David Barber. Generalization gap in amortized inference. In Advances in Neural Information Processing Systems, 2022. 4 \nShengjia Zhao, Jiaming Song, and Stefano Ermon. Infovae: Balancing learning and inference in variational autoencoders. In Proceedings of the AAAI Conference on Artificial Intelligence, 2019. 4 ",
558
+ "page_idx": 9
559
+ },
560
+ {
561
+ "type": "text",
562
+ "text": "",
563
+ "page_idx": 10
564
+ },
565
+ {
566
+ "type": "text",
567
+ "text": "",
568
+ "page_idx": 11
569
+ },
570
+ {
571
+ "type": "text",
572
+ "text": "A DETAILS ON ADVERSARIAL ATTACK ",
573
+ "text_level": 1,
574
+ "page_idx": 12
575
+ },
576
+ {
577
+ "type": "text",
578
+ "text": "We follow Kuzina et al. (2022) and construct an unsupervised encoder attack that optimizes the pertubation $\\epsilon$ to incur the largest possible change in $q _ { \\phi } ( \\bar { \\cdot } | \\pmb { x } )$ , ",
579
+ "page_idx": 12
580
+ },
581
+ {
582
+ "type": "equation",
583
+ "img_path": "images/d703bb8bfa8eb1e132fa8374f79ddb3a1f14005789120a87e02cee33ffb3b1f6.jpg",
584
+ "text": "$$\n\\epsilon = \\underset { | | \\epsilon | | _ { \\infty } \\le \\delta } { \\arg \\operatorname* { m a x } } \\mathrm { \\mathrm { ~ S K L } } \\left[ q _ { \\phi } ( \\cdot | \\boldsymbol { x } ^ { \\mathrm { r } } + \\epsilon ) \\mathrm { ~ } | | \\mathrm { ~ } q _ { \\phi } ( \\cdot | \\boldsymbol { x } ^ { \\mathrm { r } } ) \\right]\n$$",
585
+ "text_format": "latex",
586
+ "page_idx": 12
587
+ },
588
+ {
589
+ "type": "text",
590
+ "text": "where SKL denotes the symmetric Kullback-Leibler divergence (Kullback & Leibler, 1951). We optimize $\\epsilon$ for $n ^ { \\epsilon }$ iterations with projected gradient descent utilizing a learning rate of $\\eta$ . The robustness gap (see Section 2) is computed over $n ^ { \\mathrm { r } }$ real images and $n ^ { \\mathrm { a } }$ random seeds. The exact hyperparameters can be found in Table 2. ",
591
+ "page_idx": 12
592
+ },
593
+ {
594
+ "type": "table",
595
+ "img_path": "images/cb588286a046d884935ab15f7e6b500845ac461eca72889ae88404b798ffd122.jpg",
596
+ "table_caption": [
597
+ "Table 2: Hyperparameters for unsupervised encoder attack. "
598
+ ],
599
+ "table_footnote": [],
600
+ "table_body": "<table><tr><td colspan=\"2\">BinaryMNIST</td><td>FashionMNIST</td><td>CIFAR-10</td></tr><tr><td>nr</td><td>50</td><td>50</td><td>20</td></tr><tr><td>na</td><td>10</td><td>10</td><td>10</td></tr><tr><td>ne</td><td>50</td><td>50</td><td>100</td></tr><tr><td></td><td>1.0</td><td>1.0</td><td>1.0</td></tr><tr><td>8</td><td>0.1</td><td>0.1</td><td>0.05</td></tr></table>",
601
+ "page_idx": 12
602
+ },
603
+ {
604
+ "type": "text",
605
+ "text": "B QUANTITATIVE RESULTS ON PERFORMANCE GAPS ",
606
+ "text_level": 1,
607
+ "page_idx": 12
608
+ },
609
+ {
610
+ "type": "text",
611
+ "text": "Table 3 assigns quantitative values to the visual evidence in Figure 2 (generalization gap), Figure 3 (amortization gap), and Figure 4 (adversarial robustness gap). ",
612
+ "page_idx": 12
613
+ },
614
+ {
615
+ "type": "table",
616
+ "img_path": "images/ca624b0e05dfcdf8396a5cea93305e601311b64871649e0307722530b60cb05b.jpg",
617
+ "table_caption": [
618
+ "Table 3: Quantitative values of the performance gaps visualized in the main text (generalization gap: Figure 2; amortization gap: Figure 3; robustness gap: Figure 4). Bold numbers indicate the smallest gap within a dataset. "
619
+ ],
620
+ "table_footnote": [],
621
+ "table_body": "<table><tr><td colspan=\"2\"></td><td>generalization gap (9g,Eq.(8))</td><td>amorization gap (9a,Eq. (10))</td><td>robustness gap (9r, Eq. (11))</td></tr><tr><td rowspan=\"4\">Binary MNIST</td><td>Normal Training</td><td>25.76</td><td>20.32</td><td>0.49</td></tr><tr><td> DMaaPx (ours)</td><td>0.78</td><td>7.01</td><td>0.50</td></tr><tr><td> Aug.Tuned</td><td>8.16</td><td>9.34</td><td>0.79</td></tr><tr><td>Aug.Naive</td><td>6.38</td><td>8.16</td><td>0.74</td></tr><tr><td rowspan=\"4\">Fashion MNIST</td><td>Normal Training</td><td>1234.50</td><td>1135.89</td><td>0.39</td></tr><tr><td> DMaaPx (ours)</td><td>136.57</td><td> 593.39</td><td>0.31</td></tr><tr><td> Aug.Tuned</td><td>614.93</td><td>815.52</td><td>0.21</td></tr><tr><td>Aug.Naive</td><td>500.33</td><td>729.83</td><td>0.11</td></tr><tr><td rowspan=\"4\">CIFAR-10</td><td>Normal Training</td><td>841.54</td><td>835.86</td><td>0.41</td></tr><tr><td> DMaaPx (ours)</td><td> 5.44</td><td>288.82</td><td>0.30</td></tr><tr><td> Aug.Tuned</td><td>94.28</td><td>328.08</td><td>0.35</td></tr><tr><td>Aug.Naive</td><td>228.05</td><td>390.25</td><td>0.35</td></tr></table>",
622
+ "page_idx": 12
623
+ },
624
+ {
625
+ "type": "text",
626
+ "text": "C DIFFUSION MODEL ",
627
+ "text_level": 1,
628
+ "page_idx": 12
629
+ },
630
+ {
631
+ "type": "text",
632
+ "text": "We follow the setup of Karras et al. (2022) for the design and training of our diffusion model. \nHowever, we do not use the proposed augmentation pipeline during training. ",
633
+ "page_idx": 12
634
+ },
635
+ {
636
+ "type": "text",
637
+ "text": "We train the diffusion model on 200, 000, 000 images that are sampled randomly (with replacement) from the training dataset. Each model is trained on 8 NVIDIA A100 40GB GPUs for approximately 2.5 days. ",
638
+ "page_idx": 13
639
+ },
640
+ {
641
+ "type": "text",
642
+ "text": "We utilized the deterministic second-order sampler as proposed by Karras et al. (2022) with 18 integration steps. Each sampled image utilizes a unique initial seed. We sample on a single NVIDIA A100 40GB GPU. Sampling 50, 000 images takes approximately 25 to 30 minutes. ",
643
+ "page_idx": 13
644
+ },
645
+ {
646
+ "type": "text",
647
+ "text": "Figure 8 shows samples from the diffusion models trained. On CIFAR-10 we report a FID score of 3.9537. Scores on BinaryMNIST and FashionMNIST are ommited as those are not widely reported and heavily depend on preprocessing (Song et al., 2021). ",
648
+ "page_idx": 13
649
+ },
650
+ {
651
+ "type": "image",
652
+ "img_path": "images/ea3391c5772dc6ac48b10fc66b1e6b0c3fe5c90b4a66a15b9b93e05697e451ba.jpg",
653
+ "image_caption": [
654
+ "Figure 8: Samples of the diffusion models trained on BinaryMNIST (LeCun et al., 1998), FashionMNIST (Xiao et al., 2017), and CIFAR-10 (Krizhevsky et al., 2009). "
655
+ ],
656
+ "image_footnote": [],
657
+ "page_idx": 13
658
+ },
659
+ {
660
+ "type": "text",
661
+ "text": "D DETAILS ON VAE ARCHITECTURES ",
662
+ "text_level": 1,
663
+ "page_idx": 13
664
+ },
665
+ {
666
+ "type": "text",
667
+ "text": "This section provides a detailed description of the VAE models utilized throughout the paper. We consider a fully-connected architecture and a residual architecture (He et al., 2016). Table 4 gives more details on the likelihood model and architecture. For BinaryMNIST and FashionMNIST, we chose the hyperparameters of the VAE models by consulting the literature. For CIFAR-10, we manually tried out a few hyperparameters, and chose an architecture where overfitting occurs, as we are investigating how to alleviate overfitting in VAEs only from the training data. ",
668
+ "page_idx": 13
669
+ },
670
+ {
671
+ "type": "text",
672
+ "text": "The fully-connected architecture maps from an input dimension of $3 2 ^ { 2 }$ to a hidden dimension of 512. After a hidden layer mapping from 512 to 512, the output is mapped to a latent variable of dimension 16. The decoder mirrors the encoder and maps the latent variable of dimension 16 via three layers to the original input size. ",
673
+ "page_idx": 13
674
+ },
675
+ {
676
+ "type": "text",
677
+ "text": "The residual architecture maps the input by two convolutional layers (kernel size: 4, stride: 2, padding: 1), two residual layers, and another convolutional layer to a latent dimension of 64. The residual connection is made up of two convolutional layers where the first one applies a kernel of size 3 (kernel size: 3, stride: 1, padding: 1) and the second one applies a kernel of size 1 (kernel size: 1, stride: 1, padding: 0) All convolutional layers do not use any biases and are followed by BatchNorm (Ioffe & Szegedy, 2015). The decoder mirrors the architecture of the encoder. ",
678
+ "page_idx": 13
679
+ },
680
+ {
681
+ "type": "table",
682
+ "img_path": "images/b86a539226d964a4a2e0402722fc50cee8c3dfd09635333aeab6b324c0cb2bf9.jpg",
683
+ "table_caption": [
684
+ "Table 4: Details on VAE architectures ordered by dataset. MoL refers to the discretized mixture of logistics likelihood model (Salimans et al., 2017). "
685
+ ],
686
+ "table_footnote": [],
687
+ "table_body": "<table><tr><td>dataset</td><td>likelihood</td><td>architecture</td></tr><tr><td>BinaryMNIST</td><td>Bernoulli</td><td>fully-connected</td></tr><tr><td>FashionMNIST</td><td>fixed-variance Gaussian</td><td>fully-connected</td></tr><tr><td>FashionMNIST</td><td>MoL</td><td>fully-connected</td></tr><tr><td>CIFAR-10</td><td>MoL</td><td>residual network</td></tr></table>",
688
+ "page_idx": 13
689
+ },
690
+ {
691
+ "type": "text",
692
+ "text": "E AUGMENTATION ",
693
+ "text_level": 1,
694
+ "page_idx": 14
695
+ },
696
+ {
697
+ "type": "text",
698
+ "text": "We use the augmentation pipeline originally proposed for GAN training following Karras et al. (2020). Each specific augmentation is applied with a probability of $b \\in \\{ 0 . 1 , 0 . 1 2 \\}$ . For each dataset we compare two sets of specific augmentations. ",
699
+ "page_idx": 14
700
+ },
701
+ {
702
+ "type": "text",
703
+ "text": "1. The hyperparameters for each specific augmentation are tuned by hand with the goal of imitating the data generating distribution that produced the dataset. 2. We use a naive set of specific augmentations that is targeted to image datasets. ",
704
+ "page_idx": 14
705
+ },
706
+ {
707
+ "type": "text",
708
+ "text": "Table 5 lists naive augmentation for BinaryMNIST, FashionMNIST, and CIFAR-10. Table 6 lists augmentation tuned to the BinaryMNIST and the FashionMNIST dataset. Table 7 lists augmentation tuned to the CIFAR-10 datset. ",
709
+ "page_idx": 14
710
+ },
711
+ {
712
+ "type": "table",
713
+ "img_path": "images/9aa5edac7c9014c1a359e162ba9001ea5912f8875a5258bc4b6c92dea1c1112d.jpg",
714
+ "table_caption": [
715
+ "Table 5: List of specific augmentations applied to BinaryMNIST, FashionMNIST and CIFAR-10. We refer to this set as “naive” augmentation as it is targeted towards images in general (and not towards specific datasets). Each specific augmentation is applied with probability $b$ . "
716
+ ],
717
+ "table_footnote": [],
718
+ "table_body": "<table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>horizontal flip translation</td><td>flip an image horizontally translate an image in x and y direction for t ∈ {O,1,2,3} pixels</td></tr><tr><td>scaling</td><td> scale an image by 2oscale with Oscale ∈ [0,0.2]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,10]</td></tr><tr><td>anisotropic scaling</td><td>do anisotropic scaling with scale 2aniso-scale (Oaniso-scale E [0,0.2])</td></tr><tr><td>anisotropic rotation</td><td>do anisotropic rotation with a probability of 0.5</td></tr><tr><td>brightness</td><td>change the brightness of an image by Obrightness ∈ [0,0.2]</td></tr><tr><td>contrast</td><td>change the contrast of an image by 2contrast where Tcontrast ∈ [0,0.25]</td></tr><tr><td>hue</td><td></td></tr><tr><td>saturation</td><td>change the hue by rotation of rhue with rhue ∈ [0,0.25 · π] change the saturation of an image by 2osaturation where Osaturation ∈ [0,0.5]</td></tr></table>",
719
+ "page_idx": 14
720
+ },
721
+ {
722
+ "type": "table",
723
+ "img_path": "images/5bfb8b454577b6df7c8877bc3f63a0e78054685face61380eff7cb18516ec050.jpg",
724
+ "table_caption": [
725
+ "Table 6: List of specific augmentations applied to BinaryMNIST and FashionMNIST. The set is tuned towards BinaryMNIST and FashionMNIST. Each specific augmentation is applied with probability $b$ . "
726
+ ],
727
+ "table_footnote": [],
728
+ "table_body": "<table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>translation</td><td>translate an image in x and y direction for t ∈ {0,1,2,3} pixels</td></tr><tr><td>scaling</td><td>scale an image by 2σscale with σscale ∈ [0, 0.15]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,10]</td></tr><tr><td>anisotropic scaling anisotropic rotation</td><td>do anisotropic scaling with scale 2°aniso-scale (Oaniso-scale E [0, 0.15]) do anisotropic rotation with a probability of 0.4</td></tr></table>",
729
+ "page_idx": 14
730
+ },
731
+ {
732
+ "type": "table",
733
+ "img_path": "images/1ffdbc335bb1331a32b00aa4fa94e98302d2ff4f08be7ced01e3176ab4a8e71a.jpg",
734
+ "table_caption": [
735
+ "Table 7: List of specific augmentations applied to CIFAR-10. The set is tuned towards CIFAR-10. Each specific augmentation is applied with probability $b$ . "
736
+ ],
737
+ "table_footnote": [],
738
+ "table_body": "<table><tr><td>augmentation</td><td>description and hyperparameters</td></tr><tr><td>horizontal flip</td><td>flip an image horizontally (applied with probability 1)</td></tr><tr><td>vertical flip</td><td>flip an image vertically</td></tr><tr><td>scaling</td><td> scale an image by 2σscale with Oscale ∈ [0,0.2]</td></tr><tr><td>rotation</td><td>rotate an image by d degrees with d ∈ [0,360]</td></tr><tr><td>anisotropic scaling</td><td>do anisotropic scaling with scale 2aniso-scale (Oaniso-scale ∈ [0,0.2])</td></tr><tr><td>anisotropic rotation</td><td>do anisotropic rotation with a probability of 0.5</td></tr></table>",
739
+ "page_idx": 14
740
+ },
741
+ {
742
+ "type": "text",
743
+ "text": "F PRACTICAL EVALUATION OF VAES ON THREE TASKS ",
744
+ "text_level": 1,
745
+ "page_idx": 15
746
+ },
747
+ {
748
+ "type": "text",
749
+ "text": "The improvements of generalization performance, amortized inference and robustness of VAEs have direct impacts on their applications. In this section, we evaluate three popular tasks of VAEs based on whether a task involves only the encoder, the decoder, or both as in (Xiao & Bamler, 2023): (a) representation learning (i.e., using only the encoder); (b) data reconstruction (i.e., using both the encoder and the decoder); and (c) sample generation (i.e., using only the decoder). ",
750
+ "page_idx": 15
751
+ },
752
+ {
753
+ "type": "text",
754
+ "text": "Representation learning (with classification as the downstream task). We evaluate the representation learning performance by classification accuracies on the mean $\\pmb { \\mu }$ of $q _ { \\phi } ( \\pmb { z } | \\pmb { x } )$ for each $_ { \\textbf { \\em x } }$ . First, we find the learned representations $\\pmb { \\mu }$ for all data points in the CIFAR-10 test set. Afterwards, we split them into two separate subsets. We use one subset to train the classifier, and test it on the other subset. Our experiments include four different classifiers: logistic regression, a support vector machine (Boser et al., 1992) with radial basis function kernel (SVM-RBF), a SVM with linear kernel (SVM-L), and $k$ -nearest neighbors (kNN) with $k = 5$ . Table 8 (representation learning; RL) shows the resulting test accuracies across all models considered. We find that VAEs trained with DMaaPx (in bold) outperform other models on average, which highlights that the task of representation learning benefits from the smaller gaps evaluated in Section 5. ",
755
+ "page_idx": 15
756
+ },
757
+ {
758
+ "type": "text",
759
+ "text": "Data reconstruction. Tasks such as lossy data compression (Balle et al. ´ , 2017) rely on the reconstruction performance of VAEs. We evaluate the reconstruction performance of VAEs trained on CIFAR-10 using the peak signal-to-noise ratio (PSNR; higher is better). Table 8 (reconstruction; RC) shows that DMaaPx outperforms others on average. ",
760
+ "page_idx": 15
761
+ },
762
+ {
763
+ "type": "text",
764
+ "text": "Sample generation. We evaluate the quality of samples generated by VAEs trained on CIFAR-10 with the methods explained in the main text (Normal Training, DMaaPx, Aug.Naive, Aug.Tuned). We report Frechet Inception Distance ( ´ Heusel et al., 2017) (FID; lower is better) and Inception Score (Salimans et al., 2018) (IS; higher is better). Table 8 (sample quality; SQ) shows that DMaaPx slightly outperforms the others when sample quality is measured in FID, but Normal Training performs better when sample quality is measured in IS. ",
765
+ "page_idx": 15
766
+ },
767
+ {
768
+ "type": "text",
769
+ "text": "Overall, VAEs trained with DMaaPx show improvements for representation learning and data reconstruction, and perform similarly to normal training on sample quality. At the same time, VAEs trained with both augmentations seem to have slightly worse performance for representation learning and sample generation, and perform similarly on the reconstruction task when compared to normal training. The results of DMaaPx in the table is consistent with our claim that the proposed method mainly fixes the encoder, which affects representation learning and reconstruction but not sample quality. Additionally, Theis et al. (2016) show that a generative model with good log-likelihood (i.e., high test ELBO in the case of a VAE) does not necessarily produce great samples. ",
770
+ "page_idx": 15
771
+ },
772
+ {
773
+ "type": "table",
774
+ "img_path": "images/c1f837d9f1dc5089681c6d8e20808d813445e73be08f4028d7ff228ade4d87c9.jpg",
775
+ "table_caption": [
776
+ "Table 8: Evaluation of downstream applications of VAEs on CIFAR-10: representation learning with classification as the downstream task (RL), reconstruction (RC), and sample quality (SQ). Results are averaged over 3 random seeds. Note that most differences are smaller than the standard deviations. See Appendix F for a discussion of the results. "
777
+ ],
778
+ "table_footnote": [],
779
+ "table_body": "<table><tr><td colspan=\"2\"></td><td>Normal Training</td><td> DMaaPx (ours)</td><td>Aug.Naive</td><td>Aug.Tuned</td></tr><tr><td rowspan=\"3\">RL</td><td>log. reg. (↑)</td><td>0.370 ± 0.018</td><td>0.383 ± 0.018</td><td>0.359 ± 0.004</td><td>0.361 ± 0.014</td></tr><tr><td>SVM-RBF (↑)</td><td>0.427 ± 0.014</td><td>0.438 ± 0.015</td><td>0.421± 0.004</td><td>0.420 ± 0.016</td></tr><tr><td>SVM-L (↑) kNN (↑)</td><td>0.367 ± 0.015</td><td>0.380 ± 0.014</td><td>0.365± 0.005</td><td>0.366 ± 0.022</td></tr><tr><td colspan=\"2\">RC</td><td>0.325 ± 0.006 16.087± 0.042</td><td>0.327 ± 0.035 16.370 ± 0.195</td><td>0.300 ± 0.004 16.105 ± 0.017</td><td>0.299 ±0.028 15.924± 0.205</td></tr><tr><td rowspan=\"2\">SQ IS ()</td><td>PSNR (1) FID ()</td><td>219.256 ± 16.124</td><td>219.081 ± 14.894</td><td>237.238 ± 43.218</td><td>240.898 ± 11.072</td></tr><tr><td></td><td>1.818 ± 0.155</td><td>1.614 ± 0.076</td><td>1.656 ± 0.047</td><td>1.612 ± 0.083</td></tr></table>",
780
+ "page_idx": 15
781
+ },
782
+ {
783
+ "type": "image",
784
+ "img_path": "images/d8c20c43894f6ae1eb8cc769ad9cda3ccb31fed638c22914b88573f6bc1f525b.jpg",
785
+ "image_caption": [],
786
+ "image_footnote": [],
787
+ "page_idx": 16
788
+ },
789
+ {
790
+ "type": "text",
791
+ "text": "(b) Distribution of the ELBO differences when compared to Normal Training, i.e., $\\Delta \\mathrm { E L B O : = }$ $\\mathrm { E L B O } _ { p } [ { \\pmb x } ] - \\mathrm { E L B O } _ { \\mathcal { D } _ { \\mathrm { t r a i n } } } [ { \\pmb x } ] ,$ , where $p$ is $p _ { \\mathrm { D M } } ( \\pmb { x } ^ { \\prime } )$ if evaluated on the VAE trained with DMaaPx or the corresponding $p _ { \\mathrm { a u g } } ( \\pmb { x } ^ { \\prime } )$ if evaluated on the VAE trained with Aug.Tuned and Aug.Naive. ",
792
+ "page_idx": 16
793
+ },
794
+ {
795
+ "type": "text",
796
+ "text": "Figure 9: Individual ELBO evaluated on CIFAR-10 test set. Left: histograms for ELBO and ELBO differences ( $\\Delta$ ELBO) on individual image. Right: ELBO and $\\Delta$ ELBO values for individual image. Data are ordered by ELBO values of Normal Training from high (index 1) to low (index 10000). ",
797
+ "page_idx": 16
798
+ },
799
+ {
800
+ "type": "text",
801
+ "text": "G ELBOS ON INDIVIDUAL TEST IMAGES ",
802
+ "text_level": 1,
803
+ "page_idx": 16
804
+ },
805
+ {
806
+ "type": "text",
807
+ "text": "In this section, we investigate the distribution of the ELBO values on individual data points of the CIFAR-10 test set (that has a size of 10, 000), as one might be curious whether DMaaPx or augmentations only improve VAEs on a subset of the training data. ",
808
+ "page_idx": 16
809
+ },
810
+ {
811
+ "type": "text",
812
+ "text": "Figure 9 (a, left) shows a histogram of ELBO values for all methods. We find that the distribution of ELBO values shifts to the right (i.e., ELBOs are larger) when comparing Normal Training to other methods. We do not see any significant differences between DMaaPx, Aug.Tuned, and Aug.Naive. Figure 9 (a, right) shows the ELBO evaluated on individual test images. The test images are ordered and indexed based on their ELBO values with Normal Training from high (index 1) to low (index 10000). Both DMaaPx, Aug.Tuned, and Aug.Naive perform similarly better compared to the model with Normal Training across all test images. We can verify the same finding when plotting the differences between DMaaPx, Aug.Tuned, Aug.Naive and Normal Training. Figure 9 (b) shows the distribution of differences in a histogram (left) and for individual test images (right). We find that our method improves the ELBO on almost all $( 9 9 . 9 \\%$ ) of the test points (see Figure 9 (b, right)). ",
813
+ "page_idx": 16
814
+ },
815
+ {
816
+ "type": "text",
817
+ "text": "Overall, the ELBO improvement by both DMaaPx and augmentations is observed across all test images, and we could not identify a subset of test data points where the improvement is particularly small or large when compared to Normal Training. ",
818
+ "page_idx": 16
819
+ }
820
+ ]
parse/test/pyW37euNXb/pyW37euNXb_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/pyW37euNXb/pyW37euNXb_model.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/xbjSwwrQOe/xbjSwwrQOe.md ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # STATISTICAL REJECTION SAMPLING IMPROVES PREFERENCE OPTIMIZATION
2
+
3
+ Tianqi Liu∗, Yao Zhao†, Rishabh Joshi†, Misha Khalman†, Mohammad Saleh†,
4
+ Peter J. Liu†, Jialu Liu∗
5
+ {tianqiliu,yaozhaoyz,rishabhjoshi,khalman,msaleh,
6
+ peterjliu,jialu}@google.com
7
+ Google Research∗, Google DeepMind†
8
+
9
+ # ABSTRACT
10
+
11
+ Improving the alignment of language models with human preferences remains an active research challenge. Previous approaches have primarily utilized online Reinforcement Learning from Human Feedback (RLHF). Recently, offline methods such as Sequence Likelihood Calibration (SLiC) and Direct Preference Optimization (DPO) have emerged as attractive alternatives, offering improvements in stability and scalability while maintaining competitive performance. SLiC refines its loss function using sequence pairs sampled from a supervised fine-tuned (SFT) policy, while DPO directly optimizes language models based on preference data, foregoing the need for a separate reward model. However, the maximum likelihood estimator (MLE) of the target optimal policy requires labeled preference pairs sampled from that policy. The absence of a reward model in DPO constrains its ability to sample preference pairs from the optimal policy. Meanwhile, SLiC can only sample preference pairs from the SFT policy. To address these limitations, we introduce a novel offline approach called Statistical Rejection Sampling Optimization (RSO) designed to source preference data from the estimated target optimal policy using rejection sampling, enabling a more accurate estimation of the optimal policy. We also propose a unified framework that enhances the loss functions used in both SLiC and DPO from a preference modeling standpoint. Through extensive experiments across diverse tasks, we demonstrate that RSO consistently outperforms both SLiC and DPO as evaluated by gold reward, Large Language Models (LLMs) and human raters.
12
+
13
+ # 1 INTRODUCTION
14
+
15
+ Recent advancements in Large Language Models (LLMs) (Brown et al., 2020; Touvron et al., 2023; Anil et al., 2023; OpenAI, 2023) have unlocked unprecedented capabilities in diverse tasks, such as programming and creative writing. Models are pre-trained on large unlabeled corpora and supervised fine-tuned (SFT) on various tasks (Wei et al., 2021; Chung et al., 2022). Subsequently, RLHF (Stiennon et al., 2020) enhances the alignment of large language models with human preferences. RLHF introduces notable complexities into the training process, including a reward model, a policy model, a reference policy, and a value model. It limits the maximum feasible size of a model due to memory constraints. Additionally, it is not stable during training. Recognizing these challenges, recent research has pioneered alternatives to RLHF. Notable among these are RRHF (Yuan et al., 2023), SLiC (Zhao et al., 2022; 2023) and DPO (Rafailov et al., 2023). These methodologies aim to more effectively align LLMs with human preferences while avoiding the complexities of reinforcement learning. Given supervised finetuning data $\mathcal { D } _ { \mathrm { s f t } } = \{ ( x , y _ { \mathrm { r e f } } ) \}$ and preference data $\mathcal { D } _ { \mathrm { h f } } = \{ ( x , y _ { w } , y _ { l } ) \}$ where output text $y _ { w }$ is preferred over $y _ { l }$ on the same input text $x$ , they directly fit the policy model on preference data in various ways. RRHF uses a trained reward model or human raters to compute rewards for multiple sequences generated from difference sources on the same prompt $x$ , and then apply a ranking loss plus supervised fine-tuning loss. SLiC uses a contrastive ranking calibration loss plus a regularization loss
16
+
17
+ $$
18
+ \begin{array} { r } { \mathcal { L } ( \theta ) = \operatorname* { m a x } \big ( 0 , \delta - \log \pi _ { \theta } ( y _ { w } | x ) + \log \pi _ { \theta } ( y _ { l } | x ) \big ) - \lambda \log \pi _ { \theta } ( y _ { \mathrm { r e f } } | x ) , } \end{array}
19
+ $$
20
+
21
+ ![](images/455b66d4e7761044e9007e652b72ed6e5fd21333ef0a6a2393f01f6e943e99ce.jpg)
22
+ Figure 1: RSO first fits a pairwise reward-ranking model from human preference data. This model is later applied to generate preference pairs with candidates sampled from the optimal policy, followed by a preference optimization step to align sequence likelihood towards preferences.
23
+
24
+ where $\delta$ is a positive margin and $\pi _ { \theta }$ is the learnable conditional probability function by a language model. SLiC either fits directly on human preference data or on preference data sampled from the SFT policy. DPO analyzes RLHF’s objective function in the form of KL-regularized reward maximization, and analytically solves the optimal policy induced by a reward function. Based on the Bradley-Terry (BT) model (Bradley & Terry, 1952), DPO proposes an MLE to fit on human preference data directly and expresses the human preference probability in terms of only the optimal policy $\pi ^ { * }$ and reference policy $\pi _ { \mathrm { s f t } }$ :
25
+
26
+ $$
27
+ p ^ { * } ( y _ { 1 } \succ y _ { 2 } | x ) = \frac { 1 } { 1 + \exp \left( \beta \log \frac { \pi ^ { * } ( y _ { 2 } | x ) } { \pi _ { \mathrm { s f t } } ( y _ { 2 } | x ) } - \beta \log \frac { \pi ^ { * } ( y _ { 1 } | x ) } { \pi _ { \mathrm { s f t } } ( y _ { 1 } | x ) } \right) }
28
+ $$
29
+
30
+ where $\pi ^ { * }$ is the function to be estimated and $\beta$ is a hyparameter in RLHF objective.
31
+
32
+ Empirically, one can leverage observed preference pairs to approximate $p ^ { * } ( y _ { 1 } \succ y _ { 2 } | x )$ . To estimate $\pi ^ { * }$ as a density estimation problem, the optimal way is to fit a policy model on collected preference pairs sampled from $\pi ^ { * }$ . However, DPO uses the collected human preference data from other policies directly in all the experiments and lacks a study on the effect of sampling. Although they propose to sample pairs from the SFT policy and get them labeled by human, it is still not strictly MLE for the preference model due to the mismatch between the sampling distribution and $\pi ^ { * }$ . In reality, it is very challenging to obtain human preference pairs directly sampled from $\pi ^ { * }$ .
33
+
34
+ In this work, we address the above issues by constructing preference pairs from the approximated $\pi ^ { * }$ (Figure 1). Starting with a human preference dataset ${ \mathcal { D } } _ { \mathrm { h f } }$ collected from other policies, we first train a pairwise reward-ranking model, then apply a statistical rejection sampling algorithm to generate response pairs sampled from optimal policy by using SFT policy and the pairwise reward-ranking model. After that, we label the sampled response pairs by the reward model. Then we fit the model on labeled pairs via classification loss. DPO claims that the language model is secretly a reward model, we show that the language model learns better from an explicit reward model because comparing between two responses (reward) is easier to learn than generating high quality responses (policy). Our statistical rejection sampling refers to the one in the statistical field (Neal, 2003). In RLHF works (Bai et al., 2022; Stiennon et al., 2020; Touvron et al., 2023), they usually refer to rejection sampling as best-of-N or top-k-over-N algorithm, where they sample a batch of $\mathbf { N }$ completions from a language model policy and then evaluate them across a reward model, returning the best one or the top k. This algorithm has the issue of reward hacking because it trusts the reward model too much without any regularization. In this paper we show that top- $\mathbf { \nabla } \cdot \mathbf { k }$ -over-N is a special case of our statistical rejection sampling and it is critical to balance between the reward exploitation and regularization towards the SFT policy. To summarize, our contributions of this work are three-fold.
35
+
36
+ • we propose a scalable and easy-to-implement framework to learn from human preference data. We provide a comprehensive recipe among different choices of loss functions and preference pairs generation. We show the importance of the reward model instead of directly optimizing the model on the preference data.
37
+
38
+ • we unify DPO and SLiC statistically by showing that they vary by loss functions to fit on human preference data: DPO is a logistic regression on human preference data and SLiC is almost equivalent to a support vector machine (SVM) with hinge loss. We improve SLiC as the SVM counter part of DPO. • we design a statistical rejection sampling algorithm to sample pairs from the estimated optimal policy and get them labeled by a pairwise reward-ranking model. The proposed sampling strategy is shown to be effective on several generative tasks.
39
+
40
+ # 2 PRELIMINARIES
41
+
42
+ Learning from Human Feedback Several works (Ziegler et al., 2019; Zhao et al., 2023; Rafailov et al., 2023) show the significant improvement of conditional language generation by learning from human feedback data. All algorithms take two inputs:
43
+
44
+ • $\pi _ { \mathrm { s f t } } ( y | x )$ : a supervised fine-tuned policy (SFT), where $x$ is the prompt and $y$ is the response. • $\mathcal { D } _ { \mathrm { h f } } = \{ x ^ { ( i ) } , y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } \} _ { i = 1 } ^ { N }$ : a human preference dataset that distinguishes the better response from the worse given the same prompt.
45
+
46
+ KL-Constrained Reward Maximization Objective Starting with a reward function $r ( x , y )$ and input prompt distribution $\mathcal { P }$ , the DPO and RLHF optimizes for the following objective:
47
+
48
+ $$
49
+ \displaystyle { \operatorname* { m a x } _ { \pi } } \mathbb { E } _ { { x } \sim \mathcal { P } , { y } \sim \pi } \left[ r ( { x } , { y } ) \right] - \beta \mathbb { D } _ { K L } \left[ \pi ( { y } | { x } ) | | \pi _ { \mathsf { s f t } ( { y } | { x } ) } \right]
50
+ $$
51
+
52
+ Optimal Policy DPO solves the optimal policy $\pi _ { r } ( y | x )$ that maximizes the above objective:
53
+
54
+ $$
55
+ \pi _ { r } ( y | x ) = \frac { 1 } { Z ( x ) } \pi _ { \mathrm { s f t } } ( y | x ) \exp \left( \frac { 1 } { \beta } r ( x , y ) \right)
56
+ $$
57
+
58
+ for all $x \in \mathcal { P }$ , where $\begin{array} { r } { Z ( x ) = \sum _ { y } \pi _ { \mathrm { s f t } } ( y | x ) \exp \Big ( \frac { 1 } { \beta } r ( x , y ) \Big ) } \end{array}$ is the partition function. $\beta$ controls the balance between exploitation and exploration. When $\beta 0$ , all probability mass will concentrate on the max reward with full exploitation. When $\beta \infty$ , optimal policy will be the same as $\pi _ { \mathrm { s f t } }$ with full exploration. Rearrange the Equation (4) we get
59
+
60
+ $$
61
+ \boldsymbol { r } ( x , y ) = \beta \log \frac { \pi _ { r } ( y | x ) } { \pi _ { \mathrm { s f t } } ( y | x ) } + \beta \log Z ( x ) .
62
+ $$
63
+
64
+ The Equation (4) and (5) establish the relation between optimal policy and the reward function. In reality, the final goal is to have a good policy for response generation and $\pi _ { r } ( y | x )$ is usually of more interest. The key is to effectively estimate the $\pi _ { r } ( y | x )$ from the human preference data.
65
+
66
+ Preference Model Let the ground-truth reward function be $r ^ { * }$ , then the optimal policy $\pi ^ { * }$ associated with $r ^ { * }$ can be represented by Equation (4). For two responses $( y _ { 1 } , y _ { 2 } )$ from the same input $x$ , Bradley-Terry (BT) model (Bradley & Terry, 1952) assumes that
67
+
68
+ $$
69
+ \mathbb { P } ( y _ { 1 } \succ y _ { 2 } | x ) = \sigma ( r ^ { * } ( x , y _ { 1 } ) - r ^ { * } ( x , y _ { 2 } ) ) ,
70
+ $$
71
+
72
+ where $\mathbb { P } ( y _ { 1 } \sim y _ { 2 } | x )$ represents the probability that response $y _ { 1 }$ is preferred over $y _ { 2 }$ give prompt $x$ . Reusing Equation (5), we obtain Equation (2). If we leverage the human preference data to represent $\mathbb { P } ( y _ { 1 } \sim y _ { 2 } | x )$ , the estimation of $\pi ^ { * }$ can be viewed as a density estimation problem from the preference data. We will discuss different ways of estimating $\pi ^ { * }$ in Section 3.1.
73
+
74
+ Reward Model We train a pairwise T5-XXL (Raffel et al., 2020) text-to-text reward-ranking model1 $\rho _ { \psi } ( x , y _ { 1 } , y _ { 2 } )$ on ${ \mathcal { D } } _ { \mathrm { h f } }$ to approximate $\mathbb { P } ( y _ { 1 } \sim y _ { 2 } | x )$ . $\rho _ { \psi } ( x , y _ { 1 } , y _ { 2 } )$ takes the text input as:
75
+
76
+ # • “[CONTEXT] $\{ x \}$ [RESPONSE A] $\{ y _ { 1 } \}$ [RESPONSE B] $\{ y _ { 2 } \} ^ { \flat }$ for AI assistant task
77
+
78
+ $\rho _ { \psi } ( x , y _ { 1 } , y _ { 2 } )$ outputs “A” or “B” as preferred one. We use the probability of decoding “A” as estimation of the preference probability ${ \hat { \mathbb { P } } } ( y _ { 1 } \sim y _ { 2 } | x ) ^ { 2 }$ . Suppose we have a baseline sequence $y _ { b }$ with reward score 0, we can induce the reward score of any sequence $y$ as
79
+
80
+ $$
81
+ r _ { \psi } ( x , y ) = \mathrm { l o g i t } ( \rho _ { \psi } ( x , y , y _ { b } ) ) ,
82
+ $$
83
+
84
+ where $\begin{array} { r } { \mathrm { l o g i t } ( x ) = \log ( \frac { x } { 1 - x } ) } \end{array}$ . This is a result of setting $y _ { 1 } = y$ , $y _ { 2 } ~ = ~ y _ { b }$ , and $r ^ { * } ( x , y _ { 2 } ) = 0$ in Equation (6), where we replace the win rate with the estimated one $\rho _ { \psi } ( x , y , y _ { b } )$ . Thus, “pointwise” reward score can be derived from a “pairwise” reward-ranking model with a baseline sequence3.
85
+
86
+ # 3 RSO APPROACH
87
+
88
+ # 3.1 STATISTICAL ESTIMATION OF THE OPTIMAL POLICY $\pi ^ { * }$
89
+
90
+ Our proposed approach (Figure 1) takes inputs of SFT policy, reward-ranking model, and prompts. First we sample responses from the optimal policy through rejection sampling approach, then we fit a classification model on labeled preference pairs. To study the effectiveness of our approach, we consider a few options on loss and preference dataset construction. Given a preference dataset $\mathcal { D } _ { p } = \{ ( x ^ { ( i ) } , y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } ) \}$ y(i)l )}, we can estimate π∗ according to Equation (2). There are two aspects we∗ need to consider for estimating
91
+
92
+ • Choice of loss function: To fit Equation (2) as a binary classifier using $( r ^ { * } ( x , y _ { 1 } ) \textrm { -- }$ $r ^ { * } ( x , y _ { 2 } ) )$ as logit with fixed slope and zero bias, we consider logistic loss used in logistic
93
+ regression and hinge loss used in support vector machine (SVM).
94
+ • Choice of $\mathcal { D } _ { p }$ : Equation (2) does not depend on the distribution of $y _ { 1 } , y _ { 2 }$ given $x$ . Thus we
95
+ need to decide how to obtain $( x , y _ { 1 } , y _ { 2 } )$ triplets.
96
+
97
+ Choice of loss function Given a preference dataset $\mathcal { D } _ { p } = \{ ( x ^ { ( i ) } , y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } ) \}$ , we can fit a binary classifier according to Equation (2). DPO (Rafailov et al., 2023) uses sigmoid loss on normalized likelihood (sigmoid-norm) to fit a logitistic regression:
98
+
99
+ $$
100
+ \mathcal { L } _ { \mathrm { s i g m o i d - n o r m } } \left( \pi _ { \theta } | \pi _ { \mathrm { s f t } } , \mathcal { D } _ { p } \right) = - \mathbb { E } _ { ( x , y _ { w } , y _ { l } ) \sim \mathcal { D } _ { p } } \left[ \log \sigma \left( \gamma \log \frac { \pi _ { \theta } \left( y _ { w } | x \right) } { \pi _ { \mathrm { s f t } } \left( y _ { w } | x \right) } - \gamma \log \frac { \pi _ { \theta } \left( y _ { l } | x \right) } { \pi _ { \mathrm { s f t } } \left( y _ { l } | x \right) } \right) \right]
101
+ $$
102
+
103
+ where DPO sets $\gamma = \beta$ . In this work, we decouple $\gamma$ from $\beta$ and treat $\gamma$ as an equivalent temperature hyper-parameter. The larger the $\gamma$ , the more we penalize the mis-classified examples at the decision boundaries by trusting more on the preference labels.
104
+
105
+ SLiC (Zhao et al., 2023) proposed to use a hinge calibration $\mathrm { l o s s ^ { 4 } }$ as
106
+
107
+ $$
108
+ \begin{array} { r } { \mathcal { L } _ { \mathrm { h i n g e } } \left( \pi _ { \theta } | \mathcal { D } _ { p } \right) = \mathbb { E } _ { ( x , y _ { w } , y _ { l } ) \sim \mathcal { D } _ { p } } \left[ \operatorname* { m a x } \left( 0 , 1 - \left[ \gamma \log \pi _ { \theta } \left( y _ { w } | x \right) - \gamma \log \pi _ { \theta } \left( y _ { l } | x \right) \right] \right) \right] } \end{array}
109
+ $$
110
+
111
+ Note that we use $1 / \gamma$ as the margin $\delta$ used in SLiC loss (Equation (1)). This is equivalent to a hinge loss with logit $( \gamma \log \pi _ { \theta } \left( y _ { w } | x \right) - \gamma \log \pi _ { \theta } \left( y _ { l } | x \right) )$ . If we normalize the policy probabilities, we get the SVM variation of DPO as the hinge loss on normalized likelihood (hinge-norm):
112
+
113
+ $$
114
+ \mathcal { L } _ { \mathrm { h i n g e - n o m } } \left( \pi _ { \theta } | \pi _ { s \mathrm { f l } } , \mathcal { D } _ { p } \right) = \mathbb { E } _ { ( x , y _ { w } , y _ { l } ) \sim \mathcal { D } _ { p } } \left[ \operatorname* { m a x } \left( 0 , 1 - \left[ \gamma \log \frac { \pi _ { \theta } \left( y _ { w } | x \right) } { \pi _ { s \mathrm { f l } } \left( y _ { w } | x \right) } - \gamma \log \frac { \pi _ { \theta } \left( y _ { l } | x \right) } { \pi _ { s \mathrm { f l } } \left( y _ { l } | x \right) } \right] \right) \right]
115
+ $$
116
+
117
+ Choice of preference data distribution Suppose we have access to the oracle preference data $\mathcal { D } ^ { * } = \{ ( x ^ { ( i ) } , y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } ) ~ | ~ y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } \sim \pi ^ { * } ( y | x ^ { ( i ) } ) \} _ { i = 1 } ^ { N ^ { * } }$ , we can directly fit an MLE on the dataset. In reality, we may not have access to such data, and we have access to $\mathcal { D } _ { \mathrm { h f } } = \{ ( x ^ { ( i ) } , y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } ) \ |$ $y _ { w } ^ { ( i ) } , y _ { l } ^ { ( i ) } \sim \pi _ { \mathrm { u n k } } ( y | x ^ { ( i ) } ) \} _ { i = 1 } ^ { N _ { \mathrm { u n k } } }$ , where $\pi _ { \mathrm { u n k } }$ denotes some mixed unknown policies. The mixed unknown policies can include SFT policy, previous or current RLHF policy, or policies from other agents (Touvron et al., 2023). Given ${ \mathcal { D } } _ { \mathrm { h f } }$ , we consider the following three choices:
118
+
119
+ • direct: directly fit the policy on ${ \mathcal { D } } _ { \mathrm { h f } }$ according to Equation (2) as DPO without $\rho _ { \psi }$ . • sft-sample-rank: use $\pi _ { \mathrm { s f t } } ( y | x )$ to sample response pairs given prompts from the SFT training set and label them by $\rho _ { \psi }$ . rso-sample-rank: use $\pi _ { r _ { \psi } } ( y | x )$ induced by $r _ { \psi } ( x , y ) ^ { 5 }$ according to Equation (4) to sample response pairs labelled by $\rho _ { \psi }$ given prompts from the SFT training set.
120
+
121
+ Statistically speaking, since we are estimating $\pi ^ { * } ( y | x )$ , it is desired to draw samples from $\pi ^ { * } ( y | x )$ . “rso-sample-rank” is the best solution towards this direction with samples from $\pi _ { r _ { \psi } } ( y | x )$ , which is closer to $\pi ^ { * } ( y | x )$ than other two choices.
122
+
123
+ # 3.2 STATISTICAL REJECTION SAMPLING ALGORITHM
124
+
125
+ Statistical rejection sampling (Neal, 2003) is an efficient statistical technique to generate observations from a distribution. If we want to generate a distribution of density $\pi _ { r _ { \psi } }$ , we can use $\pi _ { \mathrm { s f t } }$ as the proposal distribution and follow the steps:
126
+
127
+ 1. Start with empty $\mathcal { V } = \{ \}$ .
128
+ 2. Generate $y \sim \pi _ { \mathrm { s f t } } ( y | x )$ that is not in $\mathcal { V }$ and $u \sim U [ 0 , 1 ]$ .
129
+ 3. Let $M = \operatorname* { m i n } \{ m \ | \ m \pi _ { \mathrm { s f t } } ( y | x ) \geq \pi _ { r _ { \psi } } ( y | x )$ for all $y \notin \mathcal { V } \} ^ { 6 }$ . If $\begin{array} { r } { u < \frac { \pi _ { r _ { \psi } } ( y | x ) } { M \pi _ { \mathrm { s f t } } ( y | x ) } } \end{array}$ , then we
130
+ accept $y$ and add it to $\mathcal { V }$ . Otherwise, we reject $y$ .
131
+ 4. Repeat step 2 and 3 until we get enough $\mathcal { V }$ .
132
+
133
+ ![](images/b7b84e956af4d4bced3837f42bd6153a97a0d3f14ff4d7029f7d5ffb46dd0239.jpg)
134
+ Figure 2: Statistical rejection sampling illustration. There are three curves in the figure: $M$ times SFT policy, reward, optimal policy. The sample is first generated by SFT policy, then gets accepted or rejected depending on whether a uniform random variable locates in acceptance or rejection region. If the sample has high SFT policy probability but low optimal policy probability and reward score, it has a higher chance of being rejected.
135
+
136
+ Figure 2 is an illustration7 of the statistical rejection sampling approach. A Python implementation (Algorithm 1) with derivation is shown in Appendix A.1. The computation efficiency is discussed in Appendix A.10 Regarding the algorithm, we have:
137
+
138
+ Theorem 1. Let $r _ { m a x }$ be the maximum rewards among the response candidates not yet accepted. As the number of response candidates goes to infinity, Algorithm $I$ can generate num samples distinct samples from $\pi _ { r _ { \psi } }$ with expected acceptance rate $\begin{array} { r } { \mathbb { E } _ { y \sim \pi _ { s f t } ( y | x ) } \left[ \exp \left( \frac { 1 } { \beta } \cdot \left( r _ { \psi } ( x , y ) - r _ { m a x } \right) \right) \right] } \end{array}$ .
139
+
140
+ If $\beta \to \infty$ , each sample generated from the SFT policy will be accepted with probability 1. If $\beta 0$ , only the highest reward response will be accepted and all other responses will be rejected. This is the rejection sampling (top-k-over-N) referred by AnthropicHH (Bai et al., 2022) and Llama2 (Touvron et al., 2023). $\beta$ indicates how much we trust the reward model. If the reward model is very accurate and robust, we should set a small $\beta$ . Otherwise, we should set a larger $\beta$ . In practice, we treat $\beta$ as a hyper-parameter and pick one according to validation metrics.
141
+
142
+ # 4 RELATED WORK
143
+
144
+ Preference Optimization RLHF has been a popular approach in learning from human preference (Touvron et al., 2023; Stiennon et al., 2020). Recent works have proposed alternative solutions to reinforcement learning (Zhao et al., 2023; Yuan et al., 2023; Rafailov et al., 2023; Dong et al., 2023; Wang et al., 2023; Song et al., 2023). By optimizing the model’s compatibility with preference datasets under models such as the BT model, these methods fit on human or model ranked data pairs. SLiC (Zhao et al., 2023) proposes a contrastive loss to fit on response pairs sampled from the SFT policy. Similarly, RRHF (Yuan et al., 2023) uses a zero-margin likelihood contrastive loss on ranked list of responses. DPO (Rafailov et al., 2023) fits a model directly on human preference data using the BT model. SLiC and RRHF lack theoretical understanding, and DPO does not optimally estimate the policy density proposed. Our work unifies the losses of SLiC and DPO, and proposes an improved estimation of the optimal policy. We sample preference pairs from the estimated optimal policy, which is closer to on-policy online RLHF.
145
+
146
+ Rejection Sampling Statistical rejection sampling (Neal, 2003) is a statistical approach used to generate samples from a target distribution. AnthropicHH (Bai et al., 2022) and ReST (Gulcehre et al., 2023) refer to “rejection sampling” as selecting top $k$ sampled candidates for further tuning. Llama2 (Touvron et al., 2023) propose to use the same approach with PPO (Schulman et al., 2017) to improve RLHF. Our work shows the existing approach is a special case of the proposed algorithm.
147
+
148
+ # 5 EXPERIMENTS
149
+
150
+ Tasks We study RSO on Reddit TL;DR summarization (Stiennon et al., 2020) and AnthropicHH dialogue (Bai et al., 2022) datasets. The Reddit TL;DR summarization dataset contains both finetune data Dtldr and human feedback data $\mathcal { D } _ { \mathrm { h f } } ^ { \mathrm { t l d r } }$ . $\mathcal { D } _ { \mathrm { s f t } } ^ { \mathrm { t l d r } }$ contains $1 1 7 \mathrm { k } / 6 \mathrm { k } / 6 \mathrm { k }$ examples in train, validation and test splits. $\mathcal { D } _ { \mathrm { h f } } ^ { \mathrm { t l d r } }$ consists of 93k human preferences on decodes from multiple models. The AnthropicHH is a dialogue dassistant. We use the helpful slice with fro $x$ ersation between a human query and an AI examples in train and test splits. We use the $\mathcal { D } _ { \mathrm { h f } } ^ { \mathrm { h e l p f u l } }$ $1 6 1 \mathrm { k } / 9 \mathrm { k }$ positive responses as SFT targets. Besides, we study CNN/DailyMail datasets and show that RSO works well on cross-task generalization from Reddit TL;DR (Appendix A.7).
151
+
152
+ Method Starting from a T5-large (770M) SFT policy and a T5-XXL (11B) pairwise rewardranking model, we consider nine settings as discussed in Section 3.1. The settings are all the combinations between loss functions and preference data distribution. DPO approach is the same as sigmoid-norm-direct. SLiC is almost the same as hinge-sft-sample-rank in our setting with two tiny differences. The first difference is that we drop the regularization loss (second term in Equation (1)) due to lack of significantly improvement the final metrics (Appendix A.6). The second difference is that SLiC uses a tournament-style procedure to rank candidates in a list. Unless specifically mentioned, we set $\beta = 0 . 5$ and $\gamma = 0 . 0 5$ . To construct preference pairs, we first sample 64 response candidates from the SFT policy using temperature sampling with temperature $= 0 . 7$ and $t o p . k = 4 0$ . Then we sub-sample 8 samples. We use batch size 32 and learning rate 1e-5 with Adafactor optimizer (Shazeer & Stern, 2018). For each run, we pick the checkpoint with the highest reward-ranking model win rate against the SFT target.
153
+
154
+ Evaluation Our experiments use four different approaches to evaluate: Proxy Reward Model, Gold Reward Model, AutoSxS, and Human Evaluation. Proxy Reward Model computes win rate of generated response against SFT target on the trained T5-XXL pairwise reward-ranking model. Follow the recipe in Gao et al. (2023), we train a PaLM 2-S (Anil et al., 2023) on the same data as Gold Reward Model8. AutoSxS uses PaLM 2-L few-shot in-context learning with details covered in Appendix A.4. Human Evaluation asks human raters to assign a quality score on each response and determine the best one among three systems (details in Section 5.3).
155
+
156
+ # 5.1 PERFORMANCE COMPARISON ON TWO TASKS
157
+
158
+ We include two additional baselines related to rejection sampling, RAFT (Dong et al., 2023) and ReST (Gulcehre et al., 2023). For RAFT, we pick the best decoded sequence as new SFT target. For ReST, we first normalize the reward scores to [0, 1], then pick the decoded sequences that are greater than 0.7 as new sft targets. This is one round of grow and improve with normalized reward threshold $0 . 7 ^ { 9 }$ . The comparison results are shown in Table 1. RSO variants show significant gains over RAFT, ReST, DPO, and SLiC variants on two tasks. Regarding preference pairs construction, “rso-samplerank” brings gains on top of “direct” and “sft-sample-rank” with a clear margin. Regarding the loss function, sigmoid-norm and hinge-norm perform similarly. The improved hinge-norm loss is better than hinge loss used in SLiC on AutoSxS. Hinge loss shows reward hacking in Reddit TL;DR dataset with higher Proxy Reward win rates but lower AutoSxS than other losses. To compare different methods qualitatively, we showcase an example with responses from different policies on Reddit TL;DR and AnthropicHH tasks in Figure 4 and Figure 5 in Appendix A.3, respectively.
159
+
160
+ Table 1: Compare different methods with T5-large policy to leverage human feedback data. Proxy reward, golden reward and few-shot PaLM 2-L win rate against SFT target text are reported.
161
+
162
+ <table><tr><td rowspan="2">Approach</td><td colspan="2">Ablation</td><td colspan="3">Metrics</td></tr><tr><td>Loss</td><td>Preference Pair</td><td>Proxy Reward (%)</td><td>Gold Reward (%)</td><td>AutoSxS (%)</td></tr><tr><td colspan="6">Reddit TL;DR</td></tr><tr><td>RAFT</td><td>cross-entropy</td><td></td><td>74.84</td><td>68.51</td><td>53.77</td></tr><tr><td>ReST</td><td>cross-entropy</td><td>-</td><td>49.03</td><td>46.17</td><td>34.36</td></tr><tr><td>DPO</td><td>sigmoid-norm</td><td>direct</td><td>84.35</td><td>76.09</td><td>67.72</td></tr><tr><td rowspan="3">RSOsigmoid-norm</td><td>sigmoid-norm</td><td> sft-sample-rank</td><td>88.63</td><td>78.14</td><td>69.02</td></tr><tr><td>sigmoid-norm</td><td>rso-sample-rank</td><td>92.37</td><td>82.22</td><td>71.86</td></tr><tr><td>hinge</td><td>direct</td><td>86.92</td><td>79.76</td><td>60.54</td></tr><tr><td rowspan="4">SLiCdirect SLiCsample-rank</td><td>hinge</td><td>sft-sample-rank</td><td>90.15</td><td>80.19</td><td>67.34</td></tr><tr><td>hinge</td><td>rso-sample-rank</td><td>93.36</td><td>84.40</td><td>69.26</td></tr><tr><td>hinge-norm</td><td>direct</td><td>83.93</td><td>76.43</td><td>66.63</td></tr><tr><td>hinge-norm</td><td>sft-sample-rank</td><td>88.04</td><td>76.57 83.45</td><td>68.46</td></tr><tr><td colspan="6">hinge-norm rso-sample-rank 92.80 RSOhinge-norm</td></tr><tr><td>RAFT</td><td>cross-entropy</td><td>AnthropicHH</td><td>58.21</td><td></td><td></td></tr><tr><td>ReST</td><td>cross-entropy</td><td></td><td>43.48</td><td>40.00 30.33</td><td>24.99 15.58</td></tr><tr><td>DPO</td><td>sigmoid-norm</td><td>direct</td><td>51.63</td><td>36.13</td><td>24.01</td></tr><tr><td rowspan="2"></td><td>sigmoid-norm</td><td>sft-sample-rank</td><td>85.09</td><td>58.65</td><td>39.56</td></tr><tr><td>sigmoid-norm</td><td>rso-sample-rank</td><td>86.94</td><td>59.15</td><td>40.98</td></tr><tr><td rowspan="4">SLiCdirect RSOsigmoid-norm SLiCsample-rank</td><td>hinge</td><td>direct</td><td>35.95</td><td></td><td></td></tr><tr><td>hinge</td><td>sft-sample-rank</td><td>80.82</td><td>27.56 54.55</td><td>15.69</td></tr><tr><td></td><td>rso-sample-rank</td><td>82.21</td><td></td><td>30.66</td></tr><tr><td>hinge</td><td></td><td></td><td>55.22</td><td>32.56</td></tr><tr><td rowspan="3">RSOhinge-norm</td><td>hinge-norm</td><td>direct</td><td>49.55</td><td>37.23</td><td>22.89</td></tr><tr><td>hinge-norm</td><td> sft-sample-rank</td><td>82.40</td><td>56.55</td><td>35.96</td></tr><tr><td>hinge-norm</td><td>rso-sample-rank</td><td>84.44</td><td>57.75</td><td>38.58</td></tr></table>
163
+
164
+ # 5.2 RSO ABLATION
165
+
166
+ Effect of $\gamma$ and $\beta$ in RSO To study the effect of $\gamma$ , we fix the statistical rejection sampling $\beta = 0 . 5$ , and vary $\gamma = 0 . 0 0 5 , 0 . 0 5 , 0 . 5$ in the loss function on Reddit TL;DR dataset. Figure 3a shows that $\gamma = 0 . 0 5$ provides the optimal win rate. To study the effect of $\beta$ for rejection sampling, we fix the $\gamma = 0 . 0 5$ in the loss function and vary $\beta = 0 , 0 . 0 5 , 0 . 5 , 5$ on Reddit TL;DR dataset. Figure 3b shows that $\beta = 0 . 5$ provides the optimal win rate.
167
+
168
+ ![](images/d7ca54e9a6bacf553e1c62ea0ec58224dd366974c841fd92f05f293545d342b1.jpg)
169
+
170
+ (a) Proxy reward win rate of various $\gamma$ in loss functions (Equation (8), (9), (10)). $\beta$ is fixed at 0.5. Shaded areas are $9 5 \%$ confidence intervals.
171
+
172
+ ![](images/4e24b138112aa184e4b902909b324ab633653d438a913562fb4bdcd30b840c8f.jpg)
173
+ (b) Proxy reward win rate of various $\beta$ in statistical rejection sampling (Algorithm 1). $\gamma$ is fixed at 0.05. The horizontal lines are from the sft-samplerank preference pairs. Shaded areas are $9 \hat { 5 } \%$ confidence intervals.
174
+
175
+ Figure 3: Effect of hyper-parameters in loss functions and statistical rejection sampling algorithm.
176
+
177
+ Preference pairs sampling and ranking To better understand the effect of tournament ranking and statistical rejection sampling, we compare among different sampling strategies. Since we first sample 64 responses from the SFT policy and followed by 8 responses by statistical rejection sampling, it is natural to ask: “why not use all of the 64 samples in the calibration?” SLiC uses tournament ranking, which introduces bias towards higher reward sequences. Starting with $n$ responses, we can construct $n / 2$ pairs and get them labeled. We call this approach “first-round-rank”. We can keep the tournament until the winner is decided with a total of $n - 1$ pairs (each game eliminates one response). We call this approach “tournament-rank”. We use sigmoid-norm loss and conduct ablation study on six settings (Table 2). We observe that tournament ranking can bring consistent gains across settings on reward model, but it cannot improve the AutoSxS win rate on rso-8-sample case. Rso-8-sample-first-round-rank shows to be the optimal choice based on AutoSxS metric, which means it is not always good to sample more responses or conduct the tournament ranking.
178
+
179
+ <table><tr><td>Preference Pair</td><td>Proxy Reward (%)</td><td>AutoSxS (%)</td></tr><tr><td>sft-8-sample-first-round-rank</td><td>88.63</td><td>68.51</td></tr><tr><td>sft-8-sample-tournament-rank</td><td>90.69</td><td>68.57</td></tr><tr><td>rso-8-sample-first-round-rank</td><td>92.37</td><td>71.86</td></tr><tr><td>rso-8-sample-tournament-rank</td><td>93.35</td><td>71.69</td></tr><tr><td>sft-64-sample-first-round-rank</td><td>88.91</td><td>68.84</td></tr><tr><td>sft-64-sample-tournament-rank</td><td>91.14</td><td>71.08</td></tr></table>
180
+
181
+ Table 2: Comparison among different preference pairs sampling and ranking approaches on the Reddit TL;DR dataset. “k-sample” means sampling $k$ response candidates.
182
+
183
+ Scale up the policy model To understand how well the RSO can be scaled up to larger policy models, we train a T5-XXL policy model and fix the loss as sigmoid-norm. Table 3 shows that RSO scales up well and improves AutoSxS upon DPO by $1 . 1 \%$ and $3 3 . 1 \%$ on two tasks, respectively.
184
+
185
+ Table 3: Comparing sampling strategies to leverage human feedback data on T5-XXL policy model.
186
+
187
+ <table><tr><td>Approach</td><td>Preference Pair</td><td>Proxy Reward (%)</td><td>AutoSxS (%)</td></tr><tr><td colspan="4">Reddit TL;DR</td></tr><tr><td>DPO</td><td>direct</td><td>94.04</td><td>85.03</td></tr><tr><td></td><td>sft-sample-rank</td><td>97.50</td><td>85.66</td></tr><tr><td>RSOsigmoid-orm</td><td>rso-sample-rank</td><td>98.29</td><td>86.01</td></tr><tr><td colspan="4">AnthropicHH</td></tr><tr><td>DPO</td><td>direct</td><td>76.84</td><td>52.80</td></tr><tr><td></td><td>sft-sample-rank</td><td>94.91</td><td>66.79</td></tr><tr><td>RSOsigmoid-norm</td><td>rso-sample-rank</td><td>97.54</td><td>70.26</td></tr></table>
188
+
189
+ # 5.3 HUMAN EVALUATION RESULTS
190
+
191
+ To further verify the improvements of RSO over others, we conduct human evaluation side-by-side using Amazon Mechanical Turk. Given a document and three responses generated from “direct”, “sft-sample-rank” and “rso-sample-rank”, raters are asked to assign a pointwise overall quality (1-5) to each response, and choose the best one. Each task is replicated 3 times and therefore judged by 3 different raters. To eliminate bias, we anonymize all the models and randomly shuffle order of responses for each task. We aggregate pointwise metrics by averaging the ratings across all replicas, and we aggregate the choice metric using majority vote. The rating tasks are shown in Appendix A.5. In total 47 different raters participated in the human evaluation study with a median of 16 tasks per rater. The human evaluation results are shown in Table 4. “rso-sample-rank” shows to be better than “direct” and “sft-sample-rank” in all loss functions and tasks evaluated with clear improvement margins. $\mathrm { R S O } _ { \mathrm { s i g m o i d - n o r m } }$ is chosen to be preferred more than $2 \mathbf { x }$ as DPO in both tasks. Comparing between two losses, there is no clear conclusion on which one has higher quality when applying “rso-sample-rank”. Thus improved loss on SLiC and original loss DPO perform similarly.
192
+
193
+ Table 4: Human evaluation on ways of constructing preference pairs.
194
+
195
+ <table><tr><td>Approach</td><td>Loss</td><td>Preference Pair</td><td>Chosenas Preferredl0</td><td>Quality</td></tr><tr><td colspan="5">Reddit TL;DR</td></tr><tr><td rowspan="2">DPO</td><td>sigmoid-norm</td><td>direct</td><td>21%</td><td>3.84</td></tr><tr><td>sigmoid-norm</td><td>sft-sample-rank</td><td>10%</td><td>3.74</td></tr><tr><td rowspan="2">RSOsigmoid-norm</td><td>sigmoid-norm</td><td>rso-sample-rank</td><td>48%</td><td>4.02</td></tr><tr><td>hinge-norm</td><td>direct</td><td>21%</td><td>3.80</td></tr><tr><td rowspan="2">RSOhinge-norm</td><td>hinge-norm</td><td>sft-sample-rank</td><td>11%</td><td>3.68</td></tr><tr><td>hinge-norm</td><td>rso-sample-rank</td><td>46%</td><td>3.97</td></tr><tr><td colspan="5">AnthropicHH</td></tr><tr><td rowspan="2">DPO</td><td>sigmoid-norm</td><td>direct</td><td>15%</td><td>3.04</td></tr><tr><td>sigmoid-norm</td><td>sft-sample-rank</td><td>22%</td><td>3.21</td></tr><tr><td rowspan="2">RSOsigmoid-norm</td><td>sigmoid-norm</td><td>rso-sample-rank</td><td>31%</td><td>3.37</td></tr><tr><td>hinge-norm</td><td>direct</td><td>13%</td><td>3.33</td></tr><tr><td rowspan="2">RSOhinge-norm</td><td>hinge-norm</td><td>sft-sample-rank</td><td>22%</td><td>3.56</td></tr><tr><td>hinge-norm</td><td>rso-sample-rank</td><td>33%</td><td>3.60</td></tr></table>
196
+
197
+ # 6 CONCLUSION
198
+
199
+ In this paper, we propose RSO recipe to train large language models from human feedback as an alternative to RLHF. Our recipe is simple and effective with a better sampling strategy than DPO and SLiC. We unify loss functions used in DPO and SLiC from the preference optimization perspective with the first as logistic regression and the other as support vector machine. We demonstrate our approach to be powerful on multiple tasks with comprehensive numerical experiments and analysis. Future work may include studying RSO on larger scale decoding samples, other loss functions, other language generation tasks, online variants, and non-human feedback.
200
+
201
+ # REFERENCES
202
+
203
+ Rohan Anil, Andrew M Dai, Orhan Firat, Melvin Johnson, Dmitry Lepikhin, Alexandre Passos, Siamak Shakeri, Emanuel Taropa, Paige Bailey, Zhifeng Chen, et al. Palm 2 technical report. arXiv preprint arXiv:2305.10403, 2023.
204
+ Yuntao Bai, Andy Jones, Kamal Ndousse, Amanda Askell, Anna Chen, Nova DasSarma, Dawn Drain, Stanislav Fort, Deep Ganguli, Tom Henighan, et al. Training a helpful and harmless assistant with reinforcement learning from human feedback. arXiv preprint arXiv:2204.05862, 2022.
205
+ Ralph Allan Bradley and Milton E Terry. Rank analysis of incomplete block designs: I. the method of paired comparisons. Biometrika, 39(3/4):324–345, 1952.
206
+ Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901, 2020.
207
+ Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, et al. Scaling instruction-finetuned language models. arXiv preprint arXiv:2210.11416, 2022.
208
+ Hanze Dong, Wei Xiong, Deepanshu Goyal, Rui Pan, Shizhe Diao, Jipeng Zhang, Kashun Shum, and Tong Zhang. Raft: Reward ranked finetuning for generative foundation model alignment. arXiv preprint arXiv:2304.06767, 2023.
209
+ Leo Gao, John Schulman, and Jacob Hilton. Scaling laws for reward model overoptimization. In International Conference on Machine Learning, pp. 10835–10866. PMLR, 2023.
210
+ Caglar Gulcehre, Tom Le Paine, Srivatsan Srinivasan, Ksenia Konyushkova, Lotte Weerts, Abhishek Sharma, Aditya Siddhant, Alex Ahern, Miaosen Wang, Chenjie Gu, et al. Reinforced self-training (rest) for language modeling. arXiv preprint arXiv:2308.08998, 2023.
211
+ Karl Moritz Hermann, Tomas Kocisky, Edward Grefenstette, Lasse Espeholt, Will Kay, Mustafa Suleyman, and Phil Blunsom. Teaching machines to read and comprehend. Advances in neural information processing systems, 28, 2015.
212
+ Harrison Lee, Samrat Phatale, Hassan Mansoor, Kellie Lu, Thomas Mesnard, Colton Bishop, Victor Carbune, and Abhinav Rastogi. Rlaif: Scaling reinforcement learning from human feedback with ai feedback. arXiv preprint arXiv:2309.00267, 2023.
213
+ Radford M Neal. Slice sampling. The annals of statistics, 31(3):705–767, 2003.
214
+ R OpenAI. Gpt-4 technical report. arXiv, pp. 2303–08774, 2023.
215
+ Reiner Pope, Sholto Douglas, Aakanksha Chowdhery, Jacob Devlin, James Bradbury, Jonathan Heek, Kefan Xiao, Shivani Agrawal, and Jeff Dean. Efficiently scaling transformer inference. Proceedings of Machine Learning and Systems, 5, 2023.
216
+ Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D Manning, and Chelsea Finn. Direct preference optimization: Your language model is secretly a reward model. arXiv preprint arXiv:2305.18290, 2023.
217
+ 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. The Journal of Machine Learning Research, 21(1):5485–5551, 2020.
218
+ John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. Proximal policy optimization algorithms. arXiv preprint arXiv:1707.06347, 2017.
219
+ Noam Shazeer and Mitchell Stern. Adafactor: Adaptive learning rates with sublinear memory cost. In International Conference on Machine Learning, pp. 4596–4604. PMLR, 2018.
220
+ Lei Shu, Liangchen Luo, Jayakumar Hoskere, Yun Zhu, Canoee Liu, Simon Tong, Jindong Chen, and Lei Meng. Rewritelm: An instruction-tuned large language model for text rewriting. arXiv preprint arXiv:2305.15685, 2023.
221
+ Feifan Song, Bowen Yu, Minghao Li, Haiyang Yu, Fei Huang, Yongbin Li, and Houfeng Wang. Preference ranking optimization for human alignment. arXiv preprint arXiv:2306.17492, 2023.
222
+ Nisan Stiennon, Long Ouyang, Jeffrey Wu, Daniel Ziegler, Ryan Lowe, Chelsea Voss, Alec Radford, Dario Amodei, and Paul F Christiano. Learning to summarize with human feedback. Advances in Neural Information Processing Systems, 33:3008–3021, 2020.
223
+ Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, 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, Anthony 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, Diana Liskovich, Yinghai Lu, Yuning Mao, Xavier Martinet, Todor Mihaylov, Pushkar Mishra, Igor Molybog, Yixin Nie, Andrew Poulton, Jeremy Reizenstein, Rashi Rungta, Kalyan Saladi, Alan Schelten, Ruan Silva, Eric Michael Smith, Ranjan Subramanian, Xiaoqing Ellen Tan, Binh Tang, Ross Taylor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, Melanie Kambadur, Sharan Narang, Aurelien Rodriguez, Robert Stojnic, Sergey Edunov, and Thomas Scialom. Llama 2: Open foundation and fine-tuned chat models. arXiv preprint arXiv:2307.09288, 2023.
224
+ Peiyi Wang, Lei Li, Liang Chen, Feifan Song, Binghuai Lin, Yunbo Cao, Tianyu Liu, and Zhifang Sui. Making large language models better reasoners with alignment. arXiv preprint arXiv:2309.02144, 2023.
225
+ 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.
226
+ Zheng Yuan, Hongyi Yuan, Chuanqi Tan, Wei Wang, Songfang Huang, and Fei Huang. Rrhf: Rank responses to align language models with human feedback without tears. arXiv preprint arXiv:2304.05302, 2023.
227
+ Yao Zhao, Misha Khalman, Rishabh Joshi, Shashi Narayan, Mohammad Saleh, and Peter J Liu. Calibrating sequence likelihood improves conditional language generation. arXiv preprint arXiv:2210.00045, 2022.
228
+ Yao Zhao, Rishabh Joshi, Tianqi Liu, Misha Khalman, Mohammad Saleh, and Peter J Liu. Slic-hf: Sequence likelihood calibration with human feedback. arXiv preprint arXiv:2305.10425, 2023.
229
+ Zhanhui Zhou, Jie Liu, Chao Yang, Jing Shao, Yu Liu, Xiangyu Yue, Wanli Ouyang, and Yu Qiao. Beyond one-preference-for-all: Multi-objective direct preference optimization. arXiv preprint arXiv:2310.03708, 2023.
230
+ Daniel M Ziegler, Nisan Stiennon, Jeffrey Wu, Tom B Brown, Alec Radford, Dario Amodei, Paul Christiano, and Geoffrey Irving. Fine-tuning language models from human preferences. arXiv preprint arXiv:1909.08593, 2019.
231
+
232
+ A APPENDIX
233
+
234
+ A.1 STATISTICAL REJECTION SAMPLING ALGORITHM
235
+
236
+ A Python Implementation A Python implementation of the algorithm is shown in Algorithm 1.
237
+
238
+ # Algorithm 1 Statistical Rejection Sampling Algorithm in Python
239
+
240
+ from typing import List import numpy as np
241
+
242
+ def conduct_rejection_sampling(response_candidates: List[str], response_rewards: List[float], num_samples: int, beta: float): """Conducts rejection sampling guided by rewards.
243
+
244
+ Args:
245
+
246
+ response_candidates: response candidates from the SFT policy response_rewards: response rewards. num_samples: number of samples to sub-sample. beta: beta parameter in KL-constrained reward maximization objective.
247
+
248
+ Returns: Rejection sampled sequences from the estimated optimal policy.
249
+ """
250
+
251
+ candidates = {c: $\pm$ for c, $\boldsymbol { \mathbf { \bar { \varepsilon } } }$ in zip(response_candidates, response_rewards)} accepted $=$ []
252
+
253
+ # continue
254
+
255
+ # break
256
+
257
+ for c in to_remove: candidates.pop(c)
258
+
259
+ return accepted
260
+
261
+ # Derivation of Algorithm 1 According to Equation (4), we have
262
+
263
+ $$
264
+ \pi _ { r _ { \psi } } ( y | x ) = \frac { 1 } { Z _ { \psi } ( x ) } \pi _ { \mathrm { s f t } } ( y | x ) \exp \left( \frac { 1 } { \beta } r _ { \psi } ( x , y ) \right) ,
265
+ $$
266
+
267
+ where $\begin{array} { r } { Z _ { \psi } ( x ) = \sum _ { y } \pi _ { \mathrm { s f t } } ( y | x ) \exp ( \frac { 1 } { \beta } r _ { \psi } ( x , y ) ) } \end{array}$ . Then we have
268
+
269
+ $$
270
+ \frac { \pi _ { r _ { \psi } } ( y | x ) } { \pi _ { \mathrm { s f t } } ( y | x ) } = \frac { 1 } { Z _ { \psi } ( x ) } \exp \left( \frac { 1 } { \beta } r _ { \psi } ( x , y ) \right) .
271
+ $$
272
+
273
+ It’s clear that MDx , min{m | m · πsft(y|x) ≥ πrψ (y|x) for all y /∈ Dx} = maxy /∈Dx πrψ (y|x)πsft(y|x) , then
274
+
275
+ $$
276
+ M _ { D _ { x } } = \frac { 1 } { Z _ { \psi } ( x ) } \operatorname* { m a x } _ { y \notin D _ { x } } \left[ \exp \left( \frac { 1 } { \beta } r _ { \psi } ( x , y ) \right) \right] .
277
+ $$
278
+
279
+ Then we have
280
+
281
+ $$
282
+ \frac { \pi _ { r _ { \psi } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s f t } } ( y | x ) } = \exp \left( \frac { 1 } { \beta } \left( r _ { \psi } ( x , y ) - \operatorname* { m a x } _ { y \not \in D _ { x } } r _ { \psi } ( x , y ) \right) \right) .
283
+ $$
284
+
285
+ By using the sample version of $\operatorname* { m a x } _ { y \notin D _ { x } } r _ { \psi } ( x , y )$ , we have derived the Algorithm 1.
286
+
287
+ # A.2 PROOF OF THEOREM 1
288
+
289
+ Proof. Let the process of generation be the one described in Algorithm 1 and the accepted sequence set be $D _ { x }$ at the current step, we have
290
+
291
+ $$
292
+ \begin{array} { l l l } { { \displaystyle { \mathbb P } ( \mathrm { s a m p l e ~ } y \mathrm { ~ a n d ~ g e t ~ a c c e p t e d } | x ) = { \mathbb P } \left( u < \frac { \pi _ { r _ { \psi } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s f t } } ( y | x ) } \right) \pi _ { \mathrm { s f t } } ( y | x ) } } \\ { { \displaystyle ~ = \frac { 1 } { M _ { D _ { x } } } \pi _ { r _ { \psi } } ( y | x ) , } } \end{array}
293
+ $$
294
+
295
+ where $M _ { D _ { x } } \triangleq \operatorname* { m i n } \{ m \mid m \cdot \pi _ { \mathrm { s f t } } ( y | x ) \geq \pi _ { r _ { \psi } } ( y | x )$ for all $y \notin D _ { x } \}$ .
296
+
297
+ $$
298
+ \begin{array} { r l } { \mathbb { P } ( y \mathrm { ~ g e t ~ a c e p t e d } | x ) = \mathbb { P } ( u < \frac { \pi _ { r _ { \mathrm { s } } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s t } } ( y | x ) } ) } \\ & { = \mathbb { E } { \mathbf 1 } \left[ u < \frac { \pi _ { r _ { \mathrm { s } } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s t } } ( y | x ) } \right] } \\ & { = \mathbb { E } _ { \pi _ { \mathrm { s } } } \left[ \mathbb { E } { \mathbf 1 } \left[ u < \frac { \pi _ { r _ { \mathrm { s } } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s t } } ( y | x ) } \Big | y \right] \right] } \\ & { = \mathbb { E } _ { \pi _ { \mathrm { s } } } \left[ \frac { \pi _ { r _ { \mathrm { s } } } ( y | x ) } { M _ { D _ { x } } \pi _ { \mathrm { s t } } ( y | x ) } \right] } \\ & { = \frac { 1 } { M _ { D _ { x } } } } \\ & { = \frac { 1 } { M _ { D _ { x } } } } \end{array}
299
+ $$
300
+
301
+ $$
302
+ \mathbb { P } ( y | y \mathrm { i s ~ a c c e p t e d } , x ) = \frac { \mathbb { P } ( \mathrm { s a m p l e ~ } y \mathrm { ~ a n d ~ g e t ~ a c c e p t e d } | x ) } { \mathbb { P } ( y \mathrm { ~ g e t ~ a c c e p t e d } | x ) } = \pi _ { r _ { \psi } } ( y | x ) .
303
+ $$
304
+
305
+ By Equation (13), we have the acceptance rate
306
+
307
+ $$
308
+ \frac { 1 } { M _ { D _ { x } } } = \mathbb { E } _ { y \sim \pi _ { \mathrm { s f t } } ( y | x ) } \left[ \exp \left( \frac { 1 } { \beta } \cdot \left( r _ { \psi } ( x , y ) - \operatorname* { m a x } _ { y \notin D _ { x } } r _ { \psi } ( x , y ) \right) \right) \right]
309
+ $$
310
+
311
+ # A.3 QUALITATIVE EXAMPLES OF RSO COMPARING WITH OTHER APPROACHES
312
+
313
+ The qualitative comparisons between RSO and other approaches are shown in Figure 4 and Figure 5 for Reddit TL;DR and AnthropicHH, respectively.
314
+
315
+ ![](images/451199d184d9bcce4193a55c84c6983b7bb76d33d77a58728cc2074c8bffd8bb.jpg)
316
+
317
+ Figure 4: Example summaries generated by SFT, SLiC, DPO, and RSO policies for a Reddit post. RSO generates the best summary among the four because it concisely and precisely summarizes key information in the forum post. Salient details are bolded.
318
+
319
+ ![](images/73e3bfe8d9913d7273367af70587d49c17985011e9bade177af86ce513cda7eb.jpg)
320
+
321
+ Figure 5: Example responses generated by SFT, SLiC, DPO, and RSO policies for a HumanAssistant dialogue on AnthropicHH dataset. RSO generates the most helpful response among the four because it gives a clear and straightforward answer for sending a letter quickly through traditional mail. In contrast, SFT repeats information about email rather than answering the question about traditional mail. SLiC and DPO are vague and repetitive. Salient details are bolded.
322
+
323
+ A.4 PALM 2-L DETAILS AND FEW-SHOT SXS TEMPLATE
324
+
325
+ # A.4.1 DETAILS
326
+
327
+ The purpose of the AutoSxS is to prevent the artificially high reward scores by Reward Model due to reward hacking on learned policies. Since the policy is trained using the information in the pairwise reward-ranking model, it is not necessary the higher the win rate on reward-ranking model, the better the policy. AutoSxS uses PaLM 2-L few-shot in-context learning to infer 8 decodedsamples with 4 flipped order of response A and B. The label contains three choices: A, B, and tie withscore 1, 0, and 0.5, respectively. To ensure the robustness, we use average score to determine the win or loss if the magnitude exceeds 0.35. The AutoSxS has been demonstrated as effective and consistent in DPO using GPT-4 as zero-shot rater. In this work, we replace GPT-4 with PaLM 2-L for our evaluation using few-shot prompts. The quality of PaLM 2-L on similar tasks has been shown to be close to human raters (Lee et al., 2023; Shu et al., 2023). The systematic study on consistency and quality of AutoSxS is beyond the scope of this work.
328
+
329
+ # A.4.2 REDDIT TL;DR FEW-SHOT PROMPTS
330
+
331
+ task: Judge the quality of two TLDRs, choose the options among (A), (B) or same.
332
+
333
+ context: I’ve (M[21]) been in a relationship for a year and a half with F[22] and it really has never gone well. I think we want different things and we are not overly compatible. I broke up with her about a year ago and she tried to kill herself so we got back together. This week I met an F[19] who I think I’m really compatible with. She and I talked for a few hours and we have a lot in common. I like her a lot, but she is currently a freshman and I am currently a senior so I will be graduating in May and going on to a prestigious PhD program starting next fall.
334
+
335
+ So here are my questions: \* What should I do in regards to my current relationship? I know I need to end it, but I just don’t know how. \* What should I do in regards to the other girl? \* Do you think my feelings for the other girl stem from my distaste for my current relationship?
336
+
337
+ I appreciate any help you give me. tldr (A): I’m unhappy in my current relationship with a girl I just met, but don’t know how to end
338
+
339
+ it. I have no idea what I’m doing or what to do.
340
+
341
+ tldr (B): M[21] unhappy in relationship with F[22]. Met an F[19] in town with similar interests and I really like her. What should I do in regards to current relationship/other girl?
342
+
343
+ explanation: tldr (A)’s second and third sentences convey similar idea and are redundant. tldr (B) mentions an important piece of information of the new girl, contains more details than tldr (A) and is concise at the same time.
344
+
345
+ choose among (A), (B) or same: (B)
346
+
347
+ context: Before anything, not a sad story or anything, I don’t think she’s cheating or anything of the sorts. My country’s equivalent to Valentine’s Day is coming and I had this pretty simple idea to surprise my girlfriend and it would involve giving her some roses. The thing is, although I know she would appreciate my intention in and of itself, I don’t know if she would like the actual flowers and such, so I wanted to find out if she likes roses and if she would like getting some, but without her realizing it so as not to spoil the surprise. Any ideas on how to get that information out of her? tldr (A): How do I find out if my girlfriend likes roses without her realizing it?
348
+
349
+ tldr (B): I want to surprise my girlfriend with some flowers when Valentine’s Day is around the corner, but I don’t know if she would like the flowers or flowers themselves without her knowing.
350
+
351
+ explanation: tldr (A) is a concise that captures the main idea. tldr (B) also captures the main point with more details, but the language ’flowers or flowers themselves’ is not fluent.
352
+
353
+ choose among (A), (B) or same: (A)
354
+
355
+ context: Okay, so my younger brothers were out and about when they passed some teenagers who yelled obscenities at them. My father then went over and told them to knock it off, when they started yelling obscenities at him. My dad, with a small amount of temper, got angry and yelled at them. They started recording it and made a video on YouTube where it looked like he was just screaming at them. After that, we were able to get it taken down only to have it reuploaded with blurred faces. We have in no way given consent to be in this video. Is there any way we can get them to take it doen?
356
+
357
+ tldr (A): my dad got angry at teenagers for yelling obscenities at him, they got a video on youtube and blurred faces, what can we do to get it taken down?
358
+
359
+ tldr (B): My brothers were being verbally harassed by kids, father yelled at them, they made a video of it to get the video taken down, it was like a blur with blurred faces.
360
+
361
+ explanation: tldr (A) mentions most main points of story while skipping some details like younger brothers being yelled at and original videos taken down. tldr (B) has a major factual error, they didn’t make a video to get the video taken down.
362
+
363
+ choose among (A), (B) or same: (A)
364
+
365
+ context: Apologize for the throw away account.
366
+
367
+ My friend is interested in in making his way into the mainstream music industry as an A&R representative. He has a 4 year degree in English but did some extra curricular activities around music business in college. He also has had 2 internships out of college with small time record labels in the Chicago area. He has been trying for a few years now with no success. He lives in Chicago but has moved to LA for a year. He returned recently to Chicago. It has been about 3 years since his last internship, but he has done some online collaboration stuff. Still far and few in between.
368
+
369
+ My question is what path have any of you taken to make your way into the record industry? Is networking the only important thing? Is there a set of skills that are specifically looked for? tldr (A): My friend wants to make his way into the music industry as an A&R representative. What does he need to know to make it happen?
370
+ tldr (B): friend wants to break into the music industry as an A&R rep. what is the best way to do this?
371
+ explanation: tldr (A) and (B) are basically paraphrase of each other. With (A) slightly more verbose and (B) slightly more concise.
372
+
373
+ choose among (A), (B) or same: same
374
+
375
+ context: I was at a concert this weekend supporting my favorite artist. Most of the amphitheater was standing, however \*some\* people in my section were not (including some people behind me and to my right). All of a sudden at the end of the set I got basically shoved in the back and told to sit down. I told them absolutely not, I want to support my favorite artist (who kept saying STAND UP, btw). I paid over $\$ 100$ for these seats and I want to have a great time.. after all this IS a concert.
376
+
377
+ Not to mention, I heard them calling me names before they confronted me so now I was certainly not going to sit down. Then a few songs later the woman sitting next to me told me what a bitch I was for not letting the people behind me see. Was I in the wrong here?
378
+
379
+ tldr (A): I stood up at a concert, people in front of me didn’t and confronted me. Was I in the wrong? tldr (B): I stood up at a concert even though I was told not to. I got yelled at by a woman who was sitting next to me. Was I in the wrong?
380
+
381
+ explanation: tldr (A) doesn’t say who confronted the author or wrongly implied it was the people in front. tldr (B) is correct but could mention that more people confronted the author than the woman sitting next.
382
+
383
+ choose among (A), (B) or same: (B)
384
+
385
+ A.4.3 ANTHROPICHH FEW-SHOT PROMPTS
386
+
387
+ task: For the following query to a chatbot, which response is more helpful? Choose among (A), (B) and same.
388
+
389
+ context: Human: Why can’t humans build a space station on the moon? Assistant: That’s a really good question. We don’t know yet if we’ll be able to build a space station on the moon, though it seems quite feasible. But we can also look at the science for something more ambitious, like a spaceship that’s large enough to make a round trip to Mars. That might be hard to do! Even with the technology we have now, it’s not clear to scientists how you’d build a spaceship that would travel for months in space. Human: I think we should start on the Moon first.
390
+
391
+ response (A): Assistant: I think you’re right that the Moon is a good place to start, since it’s a natural satellite of Earth. There are a lot of interesting places on the Moon to study, but we have to go to Mars to check out the atmosphere, the conditions on the ground, and the survival potential of humans, and to see if there are living things.
392
+
393
+ response (B): Assistant: The problem is that we don’t know yet if it’s even possible to build a space station on the moon. But let’s assume we could do it, and see how far we could get with a spaceship to Mars.
394
+
395
+ explanation: Response (A) offers a more expansive and engaged exploration of the user’s sentiment about starting with the Moon, while Response (B) reiterates previous information without addressing the user’s perspective or adding new insights.
396
+
397
+ choose among (A), (B) and same: (A)
398
+
399
+ context: Human: What is garam masala?
400
+
401
+ Assistant: Garam masala is a mixture of spices, typically consisting of cumin, pepper, garlic, and either coriander, ginger, or both. It’s frequently used in curries or vegetable dishes, but it’s also added to some vegetable or meat sides, or used as a spread.
402
+
403
+ Human: What other things can I add to it to make it unique?
404
+
405
+ Assistant: Try adding some of the following ingredients, in any combination you like: turmeric cinnamon cardamom celery seeds fennel fresh chilies, like jalapenos or Thai chiles grated ginger ˜ green onions basil mint
406
+
407
+ Human: Is there a sweet garam masala?
408
+
409
+ Assistant: Yes, some garam masasalas are sweetened. They might contain sugar or honey, or they might be just made with ground cinnamon or cardamom. You might also want to mix some sort of mango or pineapple relish into your garam masala.
410
+
411
+ Human: What is a good use for sweet garam masala?
412
+
413
+ response (A): Assistant: You might use it to flavor vegetable or meat stews, or chilies, or as a spread on toast. You might mix some into yogurt or fruit salad, or serve it with nuts and chutney on crackers.
414
+
415
+ response (B): Assistant: Sweet garam masala is typically used in desserts like ice cream or fudge, or in sweet curries like risotto or kofte. You can also use it in curries to add a sweet flavor. You can ¨ also use it as a spice rub for meats, like chicken or fish. You can also use it as a spice mix in a curry, or you can use it to make a sweet sauce for a curry.
416
+
417
+ explanation: Response (B) offers specific and diverse uses of sweet garam masala, allowing the user to get a clearer idea of its potential applications in cooking.
418
+
419
+ choose among (A), (B) and same: (B)
420
+
421
+ context: Human: What is the customary amount to tip a taxi driver?
422
+
423
+ response (A): Assistant: The standard tip for taxi drivers in the United States is typically a $20 \%$ tip. This is a fairly standard tip that is given to taxi drivers for a job well done, and it’s also a nice gesture to show your appreciation for their service. The tip can be more or less depending on the driver’s service and the level of professionalism they showed. If you’re considering tipping a taxi driver, I would recommend giving them a tip of at least $20 \%$ .
424
+
425
+ response (B): Assistant: A standard $10 \%$ tip is recommended.
426
+
427
+ explanation: Response (A) provides a clear recommendation, contextualizes it to a specific country (the U.S.), and offers additional guidance based on the quality of service. It’s more comprehensive than response (B).
428
+
429
+ choose among (A), (B) and same: (A)
430
+
431
+ # A.5 HUMAN SXS TEMPLATES
432
+
433
+ Reddit TL;DR and AnthropicHH human evaluation template are shown in Figure 6 and Figure 7, respectively.
434
+
435
+ # Instructions:
436
+
437
+ 1. Carefully read the document and the summaries below.
438
+ 2. Rate the summaries for quality on a scale of 1-5. $\ 1 =$ Poor summary, $5 =$ Great summary)
439
+ 3. Select the summary that better summarizes the document.
440
+
441
+ # Document:
442
+
443
+ SoI'vebeenchatingonfbalmostweeklyforsubstantialperiodsoftime(20min-1hr)withaboywhograduatedfrommyschoollastyearfor almostayearowandIcan'ttellifhactuallenjsouroversatiosorflsobgatedtorespondandshesIouldleaveloeve beenabletoseeiinpersonacouleoftiessinceheleftforegeceenIvisitedisityandaskedandoneenheaebackand saidhe'dtrytoseemehichhedid.)overChistmasbreakItriedtoseimandhewasbusy(legitimatelyso,Ibelieve,uttherewasno mentionoftringanotrtime)andenImessagedhietokuchongerthanusualtoeplysoecidedottotrycontactingincasehe wastryingtogetidofe(Ialmostalwasstartthecoversation)Alitlevertwowekslaterhemesagedeandetalkedforboutan hour.Imessagedhimaboutaweekaftertosayourscholadpostedababyphotoofhim(he'sthesonoftwoteachers,thatswyitwasposted) andwetalkedfahileereasn'tacearendingtotheoversatioaseseedtomissentheotherwasoinebuteeevinga good conversation when he just stopped responding.It's been three daysand hehasn'tevenread the message.
444
+
445
+ Ican'tfigureout what'sgoingonhere.Doesheactualywanttobefriendsordoeshejustliketalkingtomewhenhe'sboredoram I the annoying girl who can't takea hint?Can Iask about it? $\tau ^ { \prime } \mathfrak { m }$ worried tosayanything because $\mathrm { i t } ^ { \prime } { 1 1 }$ probably come off as needy (and maybeit is)andIllokextreelyinsecurebutattheametieItiredfonstantlyoderingaboutthisatethatIgetorkedupitingfor himtoreplyandI'djustliketoknowhathe'sthinkingsoIknowifit'sevenworthittocontinuemakinganefforttobefriends.
446
+
447
+ What should I do? Is there any eloquent way to approach this or should I just let it be?
448
+
449
+ ![](images/5c1b14a2155e63c2c3f1fa829d513ea50f8893419fb88f05d901729142289fa4.jpg)
450
+ Figure 6: Example of human evaluation task on Reddit TL;DR dataset.
451
+
452
+ # A.6 REGULARIZATION IN SLIC
453
+
454
+ Table 5 shows the SLiC results with different regularization weights. There is no strong gain by adding the regularization loss. And we drop it to align better with the DPO setting.
455
+
456
+ # A.7 CROSS-TASK ADAPTATION AND GENERALIZATION
457
+
458
+ The CNN/DailyMail dataset (Hermann et al., 2015) contains only fine-tuned data $\mathcal { D } _ { \mathrm { s f t } } ^ { \mathrm { c n n d m } }$ with $2 8 7 \mathrm { k } / 1 3 \mathrm { k } / 1 1 \mathrm { k }$ examples in train, validation and test splits. We use the dataset to test the crosstask generalization of different approaches. We assume no access to any target or preference texts $\mathcal { D } _ { \mathrm { s f t } } ^ { \mathrm { t l d r } }$ e CNN/DailyMail dataset during training. Starting from a SFT model trained on, we further optimize the SFT policy using preference data from Reddit TL;DR $\mathcal { D } _ { \mathrm { h f } } ^ { \mathrm { t l d r } }$ it TL;DR. For “direct”, we use the preference directly. For “sft-sample-rank” and “rso-sample-rank”, we first fit a
459
+
460
+ # Instructions:
461
+
462
+ 1. Carefully read the dialog and the responses below.
463
+ 2. Evaluate quality and helpfullness of each response on a scale of 1-5. $\mathbf { \nabla } \cdot \mathbf { \vec { \mathbf { \tau } } } ^ { 1 } =$ Poor response, $5 =$ Great response)
464
+ 3. Select the best response for the given dialog context.
465
+
466
+ # Dialog context:
467
+
468
+ AssistantGodquestion!hisdependsonafewfactorsikethageandtemperamentofthebabybutIlgiveyousomeideastostartith Haveyoutriedrockingorsingingtothebaby,asthatseemstobewhatmostparentsdoforbabiestheirownage?Thatmighthelp.
469
+
470
+ Human: Okay, what other things can we do?
471
+
472
+ # Response 0:
473
+
474
+ # Response 1:
475
+
476
+ # Response 2:
477
+
478
+ Assistant: Here are some more ideas:- Give the baby a cuddle - Give the baby a cuddle with your hand or your finger - Give the babya kiss-Give the baby a cuddle with a favorite toy -Give the baby a massage - Give the baby a hug - Give the baby a kiss onthe forehead -Give the babya kiss on the back-Givethe babya kiss on the cheek-Give the babya kiss on the forehead - Give the baby a kiss on the back
479
+
480
+ Give the baby a cuddle - Hold the baby in your lap andtalk to them-Give the baby a bottle witha sips of water-Give the baby story - Give the baby a bottle with a toy - Give the baby a bottle with a rattle - Give the baby a bottle with a pacifier - Give the baby a bottle with a rattle - Give the baby a bottle with a bottle
481
+
482
+ youcan doto help the baby feel more Give the baby a cuddle - Give the baby a bottle- Give the babya bottle-Give the baby a bottle - Give the baby a bottle - Give the babya bottle-Give the baby a bottle - Give the baby a bottle - Give the baby a bottle - Give the baby a bottle - Give the babya bottle-Give the baby a bottle
483
+
484
+ ![](images/3dfe4dc637b977e1fd32fd803a2bc04612f6fef267a2f27868f64593d1f7a245.jpg)
485
+ Figure 7: Example of human evaluation task on AnthropicHH dialogue dataset.
486
+
487
+ Table 5: Comparison on different regularization in SLiC. Adding regularization does not show significant improvement.
488
+
489
+ <table><tr><td>Regularization</td><td>Proxy Reward (%)</td><td>AutoSxS (%)</td></tr><tr><td>0</td><td>90.15</td><td>67.34</td></tr><tr><td>0.5</td><td>90.45</td><td>67.64</td></tr><tr><td>5</td><td>90.25</td><td>67.79</td></tr><tr><td>50</td><td>90.83</td><td>67.84</td></tr><tr><td>500</td><td>90.06</td><td>67.44</td></tr></table>
490
+
491
+ reward-ranking model and then generete preference pairs using prompts from the training set of CNN/DailyMail. We evaluate the performance using target texts on validation split of $\mathcal { D } _ { \mathrm { s f t } } ^ { \mathrm { c n n d m } }$ . From Table 6, the RSO also consistently improves over SLiC and DPO for cross-task transfer.
492
+
493
+ <table><tr><td rowspan="2">Approach</td><td colspan="2">Ablation</td><td colspan="2">Metrics</td></tr><tr><td>Loss</td><td>Preference Pair</td><td>Proxy Reward (%)</td><td>AutoSxS (%)</td></tr><tr><td rowspan="3">DPO</td><td>sigmoid-norm</td><td>direct</td><td>61.31</td><td>37.36</td></tr><tr><td>sigmoid-norm</td><td>sft-sample-rank</td><td>62.72</td><td>38.63</td></tr><tr><td>sigmoid-norm</td><td>rso-sample-rank</td><td>69.38</td><td>39.71</td></tr><tr><td>SLiCdirect RSOsigmoid-norm</td><td>hinge</td><td>direct</td><td>64.18</td><td>33.63</td></tr><tr><td rowspan="4">SLiCsample-rank</td><td>hinge</td><td>sft-sample-rank</td><td>67.16</td><td>33.21</td></tr><tr><td>hinge</td><td>rso-sample-rank</td><td>71.62</td><td>35.46</td></tr><tr><td>hinge-norm</td><td>direct</td><td>60.04</td><td>33.91</td></tr><tr><td>hinge-norm</td><td>sft-sample-rank</td><td>61.77</td><td>40.63</td></tr><tr><td>RSOhinge-norm</td><td>hinge-norm</td><td>rso-sample-rank</td><td>69.82</td><td>42.18</td></tr></table>
494
+
495
+ Table 6: Compare different methods to leverage human feedback data on CNN/DailyMail.
496
+
497
+ # A.8 OTHER BASELINES
498
+
499
+ In Table 1, we did not include the baselines for RRHF and RLHF. For RRHF, we don’t have access to other LLM systems and it is hard to establish an apples-to-apples comparison. Furthermore, the loss function of RRHF is very similar to SLiC. We believe our sampling technique can also improve RRHF, but we leave it as a future study. For RLHF, we lack expertise on RLHF and DPO shows it to be a competitive alternative. The main purpose of this work is to improve upon DPO and SLiC with a better sampling strategy.
500
+
501
+ # A.9 DEEPER EXAMINATION OF BIAS AND FAIRNESS IN LANGUAGE MODELS
502
+
503
+ This section delves into the critical aspects of bias and fairness in language models, particularly in relation to our proposed methodology. The works of Anil et al. (2023) and Touvron et al. (2023) offer insightful evaluations of bias and fairness in both pre-trained and aligned language models. In terms of aligning with human preferences, our approach incorporates two academic datasets: the Reddit TL;DR summarization (Stiennon et al., 2020) and the AnthropicHH dialogue (Bai et al., 2022). Our primary objective is to enhance alignment with human preferences, focusing on the quality of summaries in Reddit TL;DR and the helpfulness in AnthropicHH dialogues.
504
+
505
+ In practical scenarios, reward scores are often multi-dimensional, and the aim of alignment is to attain a Pareto optimal frontier (Bai et al., 2022). This allows for the introduction of additional objectives such as harmlessness, safety, and bias preference pairs. Our method is adaptable, functioning with either weighted-averaged reward scores or through integration with multi-objective DPO loss functions (Zhou et al., 2023). Experimental studies have demonstrated that our RSO method effectively aligns with human preference pairs.
506
+
507
+ We posit that our approach has the potential to enhance fairness and reduce bias in language models, provided it is applied with appropriate human preference pairs. However, it is important to note that a comprehensive study of fairness and bias falls beyond the scope of this work.
508
+
509
+ # A.10 COMPUTATIONAL EFFICIENCY
510
+
511
+ Compared with PPO (Schulman et al., 2017), RSO only needs a policy network during training, while PPO needs four networks (policy, value, reward, and reference network). Besides, rsosample-rank is fully parallelized over the whole dataset, while PPO needs sampling at each step and is parallelized within the batch. Now we focus a comparative analysis of the computational efficiency among different offline methodologies. Our comparison includes RAFT (Dong et al., 2023), ReST (Gulcehre et al., 2023), DPO (Rafailov et al., 2023), SLiC-HF-direct (Zhao et al., 2023), SLiCHF-sample-rank (Zhao et al., 2023), and our proposed RSO. Notably, most approaches, except DPO and SLiC-HF-direct, require the training and inference of a (pairwise) reward model.
512
+
513
+ Table 7 delineates the efficiency comparison among the considered approaches. For methods involving a pairwise reward model with $n _ { c }$ decoded candidates and $n _ { d }$ selected candidates for RSO, the following specifics are noted:
514
+
515
+ • RAFT: Requires $n _ { c }$ decodings from the SFT policy and $n _ { c } - 1$ comparisons for tournament ranking.
516
+ • ReST: Involves $n _ { c }$ SFT decodings and $n _ { c } - 1$ comparisons with a randomly chosen baseline sequence, followed by normalization of reward scores and truncation based on a threshold.
517
+ • DPO/SLiC-HF-direct: directly optimize on the human preference data without a reward model and SFT decoded sequences.
518
+ • SLiC-HF-sample-rank: Samples $n _ { d }$ sequences, subsequently employing $n _ { d } - 1$ tournament ranking comparisons.
519
+ • RSO: Our method samples $n _ { c }$ decoded candidates from the SFT policy. Each candidate is assigned a reward score based on $n _ { c } - 1$ comparisons against a random chosen baseline. RSO then employs statistical rejection sampling for selecting $n _ { d }$ sequences and constructs preference pairs using $n _ { d } / 2$ comparisons.
520
+
521
+ Compared with DPO and SLiC-HF-direct, RSO introduces an additional sample and rank stage. These stages are scalable and can be parallelized across multiple model servers, significantly enhancing efficiency.
522
+
523
+ RSO needs more reward server inferences. The extra computation burden can be mitigated and addressed with prompt efficiency: With a fixed prompt for generating responses, RSO benefits from prompt caching on model servers, leading to faster response generation. The inference speed can further be improved with advance serving techniques (Pope et al., 2023). On the side of reward server, inference with decoder length 1 ensures quick processing times.
524
+
525
+ The statistical rejection sampling algorithm, as described in Algorithm 1, exhibits enhanced efficiency by employing a sampling-without-replacement strategy. This is achieved by excluding the selected sequences subsequent to each sampling round. Furthermore, at the commencement of each round, the maximum reward is recalculated. This recalibration ensures that, in every round, at least one sequence is invariably chosen. Specifically, the sequence whose reward is equivalent to the maximum reward is selected with a probability of one, thereby guaranteeing the selection of at least one optimal sequence in each round. This approach not only optimizes the selection process but also maintains the algorithm’s effectiveness throughout its execution.
526
+
527
+ RSO needs additional computation on sampling from the SFT policy and ranking from the pairwise reward model, but the additional cost is empirically minor compared to policy training. There are several reasons for that:
528
+
529
+ • We only need to sample once for each prompt in the training data. But the training of DPO can go through multiple epochs.
530
+ • Sampling and ranking are fully parallelizable over the whole training set but training is only parallelizable within the batch.
531
+ • Reward ranking can be fast because of the short decoding length (just one token). The input text can be encoded in a parallel way.
532
+ Our observations indicate that rso-sample-rank accounts for less than $10 \%$ of the total training time.
533
+ Batch decoding is scalable and efficient with many optimizations (Pope et al., 2023). In this work, we sample 64 responses from the SFT policy. Existing research works can sample similar or even way more samples from the SFT policy to construct best-of-N: 1. Up to 32 samples in Table 4 in Dong et al. (2023); 2. Up to 100 samples in Figure 7 in Touvron et al. (2023); 3. Up to 30k samples in Table 2 in Gao et al. (2023);
534
+
535
+ From the perspective of balancing between the additional burden in efficiency and the significant performance quality gains (as shown in the Section 5), RSO stands out as a recommended approach over the alternatives.
536
+
537
+ <table><tr><td>Approach</td><td>Reward Model</td><td>#SFTinference</td><td>#RewardModel inference</td></tr><tr><td>RAFT</td><td>Y</td><td>nc</td><td>nc-1</td></tr><tr><td>ReST</td><td>Y</td><td>nc</td><td>nc-1</td></tr><tr><td>DPO</td><td>N</td><td>0</td><td>0</td></tr><tr><td>SLiC-HF-direct</td><td>N</td><td>0</td><td>0</td></tr><tr><td>SLiC-HF-sample-rank</td><td>Y</td><td>nd</td><td>nd-1</td></tr><tr><td>RSO</td><td>Y</td><td>nc</td><td>nc-1+0.5*nd</td></tr></table>
538
+
539
+ Table 7: Efficiency comparison of difference approaches. $N _ { p }$ denotes the number of prompts, $n _ { c }$ denotes the number of decodes to sample from the SFT policy as RSO candidates, and $n _ { d }$ denotes the number of decodes for each prompt.
parse/test/xbjSwwrQOe/xbjSwwrQOe_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/xbjSwwrQOe/xbjSwwrQOe_middle.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/y886UXPEZ0/y886UXPEZ0.md ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/y886UXPEZ0/y886UXPEZ0_content_list.json ADDED
The diff for this file is too large to render. See raw diff
 
parse/test/y886UXPEZ0/y886UXPEZ0_model.json ADDED
The diff for this file is too large to render. See raw diff